--- porcelain counts ---
     56  M
     95 ??
--- tracked diff stat ---
 agent/auxiliary_client.py                          |   524 +-
 agent/codex_runtime.py                             |    15 +-
 gateway/__init__.py                                |    15 +-
 gateway/channel_directory.py                       |    26 +
 gateway/config.py                                  |   224 +-
 gateway/platforms/bluebubbles.py                   |    62 +-
 gateway/platforms/diagnostic_isolation.py          |     4 +-
 gateway/platforms/korean_humanizer.py              |   291 +-
 gateway/platforms/nutrition_coaching.py            | 10643 ++++++++++++++++---
 gateway/platforms/nutrition_coaching_config.py     |    64 +-
 gateway/platforms/physique_checkin.py              |   444 +-
 gateway/platforms/physique_checkin_prompts.py      |    83 +-
 gateway/platforms/telegram.py                      |  3989 +++++--
 gateway/run.py                                     |   283 +-
 gateway/status.py                                  |   666 +-
 hermes_cli/config.py                               |    53 +
 hermes_cli/gateway.py                              |   274 +-
 hermes_cli/gateway_windows.py                      |    85 +-
 hermes_cli/profiles.py                             |    60 +-
 hermes_cli/tools_config.py                         |     1 +
 plugins/platforms/photon/README.md                 |     3 +
 plugins/platforms/photon/adapter.py                |    32 +-
 plugins/platforms/photon/plugin.yaml               |    12 +
 plugins/platforms/photon/sidecar/index.mjs         |    37 +-
 .../sidecar/patch-spectrum-mixed-attachments.mjs   |     2 +-
 pyproject.toml                                     |     4 +
 scripts/run_tests_parallel.py                      |     2 +-
 tests/agent/test_auxiliary_client.py               |   306 +
 tests/conftest.py                                  |    28 +-
 tests/cron/test_cron_script.py                     |    16 +
 tests/gateway/conftest.py                          |    44 +-
 tests/gateway/test_adaptive_nutrition.py           |  6117 +++++++----
 tests/gateway/test_channel_directory.py            |    16 +
 tests/gateway/test_diagnostic_isolation.py         |    14 +-
 tests/gateway/test_dm_topics.py                    |    27 -
 tests/gateway/test_gateway_shutdown.py             |    71 +-
 tests/gateway/test_korean_humanizer.py             |   565 +
 tests/gateway/test_nutrition_coaching.py           |  6589 +++++++++++-
 tests/gateway/test_planned_stop_watcher.py         |     2 +
 tests/gateway/test_platform_reconnect.py           |     1 +
 tests/gateway/test_runner_fatal_adapter.py         |    25 +-
 tests/gateway/test_runner_startup_failures.py      |   182 +-
 .../test_shutdown_memory_provider_messages.py      |     1 +
 tests/gateway/test_status.py                       |   305 +-
 tests/gateway/test_telegram_conflict.py            |   182 +-
 tests/gateway/test_telegram_documents.py           |     2 +
 tests/gateway/test_telegram_group_gating.py        |   537 +-
 tests/gateway/test_telegram_physique_checkin.py    |  2049 +++-
 tests/gateway/test_wecom_callback.py               |     4 +
 tests/hermes_cli/test_gateway.py                   |   229 +-
 tests/hermes_cli/test_gateway_runtime_health.py    |    33 +-
 tests/hermes_cli/test_gateway_service.py           |    79 +-
 tests/hermes_cli/test_gateway_windows.py           |   213 +-
 tests/hermes_cli/test_profiles.py                  |   130 +
 tools/approval.py                                  |   116 +
 toolsets.py                                        |    19 +
 56 files changed, 30152 insertions(+), 5648 deletions(-)
--- tracked changed names ---
agent/auxiliary_client.py
agent/codex_runtime.py
gateway/__init__.py
gateway/channel_directory.py
gateway/config.py
gateway/platforms/bluebubbles.py
gateway/platforms/diagnostic_isolation.py
gateway/platforms/korean_humanizer.py
gateway/platforms/nutrition_coaching.py
gateway/platforms/nutrition_coaching_config.py
gateway/platforms/physique_checkin.py
gateway/platforms/physique_checkin_prompts.py
gateway/platforms/telegram.py
gateway/run.py
gateway/status.py
hermes_cli/config.py
hermes_cli/gateway.py
hermes_cli/gateway_windows.py
hermes_cli/profiles.py
hermes_cli/tools_config.py
plugins/platforms/photon/README.md
plugins/platforms/photon/adapter.py
plugins/platforms/photon/plugin.yaml
plugins/platforms/photon/sidecar/index.mjs
plugins/platforms/photon/sidecar/patch-spectrum-mixed-attachments.mjs
pyproject.toml
scripts/run_tests_parallel.py
tests/agent/test_auxiliary_client.py
tests/conftest.py
tests/cron/test_cron_script.py
tests/gateway/conftest.py
tests/gateway/test_adaptive_nutrition.py
tests/gateway/test_channel_directory.py
tests/gateway/test_diagnostic_isolation.py
tests/gateway/test_dm_topics.py
tests/gateway/test_gateway_shutdown.py
tests/gateway/test_korean_humanizer.py
tests/gateway/test_nutrition_coaching.py
tests/gateway/test_planned_stop_watcher.py
tests/gateway/test_platform_reconnect.py
tests/gateway/test_runner_fatal_adapter.py
tests/gateway/test_runner_startup_failures.py
tests/gateway/test_shutdown_memory_provider_messages.py
tests/gateway/test_status.py
tests/gateway/test_telegram_conflict.py
tests/gateway/test_telegram_documents.py
tests/gateway/test_telegram_group_gating.py
tests/gateway/test_telegram_physique_checkin.py
tests/gateway/test_wecom_callback.py
tests/hermes_cli/test_gateway.py
tests/hermes_cli/test_gateway_runtime_health.py
tests/hermes_cli/test_gateway_service.py
tests/hermes_cli/test_gateway_windows.py
tests/hermes_cli/test_profiles.py
tools/approval.py
toolsets.py
--- relevant file status ---
?? gateway/platforms/telegram_nutrition_onboarding_copy.py
?? scripts/source_golden_path.py
?? scripts/task26_evidence_contract.py
?? scripts/verify_source_golden_path.py
?? tests/gateway/test_installed_golden_path_provenance.py
?? tests/gateway/test_nutrition_onboarding_clarification_policy.py
?? tests/gateway/test_source_golden_path_verifier.py
?? tests/gateway/test_telegram_nutrition_onboarding_copy.py
--- relevant diff ---


**Planning acceptance test reading ranges**


Through the real staff Telegram card:

1. observe automatic generation pending;
2. observe draft created;
3. regenerate and edit;
4. approve;
5. prove customer delivery remains zero;
6. explicitly send;
7. observe the customer DM message;
8. prove one provider message and one `sent_audited` receipt;
9. repeat send, stale card, and wrong-role actions;
10. restart before and after the send boundary.

Acceptance:

- Every action uses Telegram, not direct service calls.
- Operator route uses the configured effective user/chat/message context.
- Owner/operator is the sole nutrition approval authority for the generated draft.
- Customer observes exactly one message.
- Negative actions create no second receipt or provider message.

### Specification 25 — Disable and clean the rehearsal

Use the canonical disable transaction. Verify:

- customer registry is disabled;
- scheduled jobs cannot deliver;
- bootstrap/activation projection is coherent;
- test gateway is stopped;
- gateway state reports stopped;
- no orphan monitors/processes remain;
- temporary credentials and evidence containing customer data are removed;
- other profiles retain their original PIDs and state;
- no trainer marker, claim, invite, card, route, observer, or temporary trainer artifact
  remains.

---

## Release Review

### Specification 26 — Run the multi-lane release review

Run independent reviewers for:

- objective and constraint coverage;
- code quality and maintainability;
- security, privacy, and authority;
- hands-on real-surface QA;
- context and evidence provenance;
- owner/operator-only authority and trainer-free v1 scope.

Every reviewer must receive:

- candidate manifest and digest;
- Golden Path and Recovery Runbook;
- automated evidence;
- live rehearsal evidence;
- durable receipts and cleanup evidence.

Acceptance:

- All reviewers return PASS.
- Missing, inconclusive, timed-out, or unverified lanes count as failure.
- Findings are fixed and the affected gates rerun against a new candidate digest.

### Specification 27 — Issue the release verdict

Release is permitted only when all previous tasks pass.

The release report must state:

- exact candidate digest;
- privacy architecture;
- all automated commands and results;
- real-surface evidence for the customer and owner/operator only;
- exactly-once delivery proof;
- recovery scenarios exercised;
- cleanup state;
- reviewer verdicts;
- residual risks;
- pilot scope and rollback criteria.

Initial rollout:

- one explicitly consenting pilot customer;
- no shared customer group;
- daily operator review;
- immediate disable on authorization, duplication, or delivery anomaly;
- expansion only after the defined observation window is clean.

## Todos

Every task below inherits **Execution constraints**, **Minimum-operation v1 scope
directive**, and **Per-checkbox execution rule**. A task's specification defines the
required operating behavior; it does not authorize customer-facing feature expansion,
speculative architecture, convenience work, or future scaffolding. The executor must
reuse already-correct live behavior, identify only the unsatisfied v1 gap, and record
the minimal delta plus rejected extras in its DoneClaim and ledger receipt.

- [x] 1. Build the immutable-candidate manifest
  - Recommended task executor category: `unspecified-high`
  - Dependencies: none.
  - References: Foundation, Specification 1.
  - Acceptance: reconcile every tracked/untracked file and produce the candidate digest.
  - Agent-executed QA: compare manifest counts and digests with Git and filesystem output.
  - Commit: none; the user prohibited commits in this workflow.

- [x] 2. Write the Golden Path contract
  - Recommended task executor category: `writing`
  - Dependencies: 1.
  - References: Foundation, Specification 2.

[277 more lines in file. Use offset=942 to continue.]


  - References: Real-Surface QA, Specification 23.
  - Acceptance: synthetic activation and the 12-question check-in complete in DM with one generation job after owner/operator readiness; no real customer activation.
  - Agent-executed QA: capture customer screen, durable event, Q7 controls, restart recovery, and delivery 0 before Task24.
  - Commit: none; the user prohibited commits in this workflow.

- [x] 24. Run operator review and exactly-once delivery
  - Recommended task executor category: `unspecified-high`
  - Dependencies: 23.
  - References: Real-Surface QA, Specification 24.
  - Acceptance: actual owner/operator staff buttons create, approve, and send one synthetic customer message and one receipt.
  - Agent-executed QA: capture the live owner/operator button path and synthetic customer DM receipt; verify regenerate, edit, approve, explicit send, wrong-role, stale, duplicate, and restart behavior against the sealed disposable-profile matrix in `.omo/evidence/dualcoach-task-24-evidence.json`.
  - Commit: none; the user prohibited commits in this workflow.

- [x] 25. Disable and clean the rehearsal
  - Recommended task executor category: `unspecified-high`
  - Dependencies: 24.
  - References: Real-Surface QA, Specification 25.
  - Acceptance: customer disabled, no future jobs, truthful stopped runtime, no orphan artifacts, and no trainer setup or authority artifacts.
  - Agent-executed QA: restart after disable and prove no delivery while other profiles remain unchanged.
  - Commit: none; the user prohibited commits in this workflow.

### Clarification root-fix and one-pass Golden Path amendment — 2026-08-18

Task 26 remains blocked until one replacement exact candidate proves the following
without a live customer rehearsal:

- A deterministic compiler owns clarification eligibility for all 22 onboarding
  fields. Provider output is advisory only and cannot create, select, order, persist,
  or publish a customer question.
- Production and preview use the same compiler result. Publications reload the
  committed reconciliation record rather than rendering a transient provider object.
- Every visible issue has a stable issue ID, canonical field, machine reason code,
  fixed copy, answer-digest binding, deterministic ordering, and exact revision
  binding. A valid canonical answer can never be asked again.
- Sensitive disclosures become deterministic safety holds where required; they are
  never converted into provider-authored clarification copy.
- Existing domain authorities remain authoritative. A new runtime-wide aggregate is
  rejected because replacing every proven persistence seam would materially expand
  scope and introduce a second migration risk. The Golden Path instead creates a
  hash-linked evidence graph over the existing committed receipts and independently
  verifies every edge.
- The installed-candidate Golden Path must exercise production ingress through all
  22 natural-language answers, zero-issue reconciliation, customer attestation,
  owner review, activation, one complete nutrition check-in, draft generation,
  approval, one-use capability, exactly one customer delivery, duplicate-send
  rejection, archive, disablement, quiescence, and truthful cleanup.
- The same invocation must prove provider-invented questions are invisible, genuine
  parse ambiguity is deterministic, later-field revision cannot target field zero,
  preview cannot satisfy production acceptance, approved-card projection failure
  blocks capability issuance, unknown delivery is never retried, and cleanup resumes
  forward with one terminal receipt.
- No further live invite may be issued until the exact installed candidate, complete
  Golden Path bundle, related/full suites, independent verifier, and cleanup seal all
  pass.

- [ ] 26. Run the multi-lane release review
  - Recommended task executor category: `unspecified-high`
  - Dependencies: 1-25.
  - References: Release Review, Specification 26.
  - Acceptance: objective, quality, security, owner/operator hands-on QA, and provenance lanes all return PASS.
  - Agent-executed QA: reconcile every finding to a fixed candidate, revalidate trainer-free scope, and rerun affected gates.
  - Commit: none; the user prohibited commits in this workflow.

- [ ] 27. Issue the release verdict
  - Recommended task executor category: `unspecified-high`
  - Dependencies: 26.
  - References: Release Review, Specification 27.
  - Acceptance: release report contains every named evidence item and authorizes only the limited pilot.
  - Agent-executed QA: run the completion audit and reject release on any missing or inconclusive evidence.
  - Commit: none; the user prohibited commits in this workflow.

## Final verification wave

Every final verifier inherits the same minimum-operation v1 directive and must judge the
exact fixed candidate. PASS means the existing lifecycle is ready for the bounded pilot
handoff defined above; it never authorizes automatic customer activation, delivery, or
new feature scope.

- [ ] F1. Verify objective and invariant coverage

[30 more lines in file. Use offset=1189 to continue.]


Task26 clear answer was re-asked or miscanonicalized

invalid-assignment on direct evidence-harness method monkeypatch

replaced direct assignments with setattr; reran source/installed Golden, contract tests, full Gateway, and all static gates

All activation, delivery, and cleanup behavior was synthetic and offline inside disposable evidence roots.


#!/usr/bin/env python3
from __future__ import annotations
import hashlib,importlib.util,json,os,re,subprocess,sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
def can(x):return json.dumps(x,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode()
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def fail(x):raise SystemExit(x)
manifest=json.loads((ROOT/'candidate.json').read_text());unsigned={k:v for k,v in manifest.items() if k!='candidate_digest'}
if hashlib.sha256(can(unsigned)).hexdigest()!=manifest['candidate_digest']:fail('candidate digest mismatch')
excluded={'candidate.json','seal.sha256','receipts/independent-verification.json','receipts/final-immutability.json'};actual=[]
for p in sorted(x for x in ROOT.rglob('*') if x.is_file() and x.relative_to(ROOT).as_posix() not in excluded):
 rel=p.relative_to(ROOT).as_posix();actual.append({'path':rel,'sha256':sha(p),'size':p.stat().st_size})
if actual!=manifest['evidence_inventory']:fail('evidence inventory mismatch')
verifier=ROOT/'tools/verify_source_golden_path.py'
def fresh_verify(bundle, *, source_mode=False):
 env=os.environ.copy();env['PYTHONDONTWRITEBYTECODE']='1'
 if source_mode:env['PYTHONPATH']=os.pathsep.join(manifest['source_roots'])
 else:env.pop('PYTHONPATH',None)
 run=subprocess.run([sys.executable,str(verifier),str(bundle)],cwd=ROOT,text=True,capture_output=True,env=env)
 if run.returncode:fail(f'fresh verifier failed: {run.stderr.strip()}')
 return json.loads(run.stdout)
installed=fresh_verify(ROOT/'installed-golden-bundle');source=fresh_verify(ROOT/'source-golden-bundle',source_mode=True)
if source['status']!='ACTUAL_SOURCE_GOLDEN_PATH_PASS' or installed['status']!='ACTUAL_INSTALLED_GOLDEN_PATH_PASS':fail('Golden status mismatch')
spec=importlib.util.spec_from_file_location('candidate_verifier',verifier);v=importlib.util.module_from_spec(spec);spec.loader.exec_module(v)
if source['task26_contract']['clause_count']!=7 or installed['task26_contract']['clause_count']!=7:fail('clause count mismatch')
expected=[('missing','inventory'),('summary','incomplete'),('forged','miscanonicalized')];attacks=[]
for name,needle in expected:
 try:v.verify_task26_contract(ROOT/f'adversarial-fixtures/{name}')
 except ValueError as e:
  if needle not in str(e):fail(f'wrong {name} rejection: {e}')
  attacks.append({'attack':name,'reason':str(e),'rejected':True})
 else:fail(f'{name} accepted')
parity=json.loads((ROOT/'seals/source-wheel-installed-product-parity.json').read_text());
if parity['status']!='PASS':fail('product parity failure')
checks={'profile':(ROOT/'receipts/profile-full.log',r'749 passed'), 'contract_source':(ROOT/'receipts/contract-focused-source.log',r'51 passed'), 'contract_installed':(ROOT/'receipts/contract-focused-installed.log',r'51 passed'), 'focused_source':(ROOT/'receipts/focused-source.log',r'106 passed'), 'focused_installed':(ROOT/'receipts/focused-installed.log',r'106 passed'), 'related_installed':(ROOT/'receipts/related-installed.log',r'76 passed'), 'gateway':(ROOT/'receipts/full-gateway.log',r'8288 tests passed, 0 failed')}
for name,(path,pattern) in checks.items():
 text=path.read_text(errors='replace')
 if not re.search(pattern,text) or 'EXIT=0' not in text:fail(f'{name} result mismatch')
if (ROOT/'receipts/static.log').read_text().strip().splitlines()[-1]!='EXIT=0':fail('static failed')
if (ROOT/'receipts/pip-check.log').read_text().strip().splitlines()[-1]!='EXIT=0':fail('pip check failed')
result={'schema':'task26-independent-verification-v1','status':'PASS','candidate_digest':manifest['candidate_digest'],'source_candidate_digest':source['candidate_digest'],'installed_candidate_digest':installed['candidate_digest'],'source_contract':source['task26_contract'],'installed_contract':installed['task26_contract'],'terminal_inventory':installed['terminal_inventory'],'adversarial_attacks':attacks,'verified_inventory_count':len(actual),'python':sys.executable}
print(json.dumps(result,ensure_ascii=False,sort_keys=True,separators=(',',':')))


"""Hash-linked same-invocation evidence writer for the Task26 Golden Path.

This module records raw inputs and native API outcomes.  It deliberately emits no
PASS counters or verdicts; the independent verifier owns every acceptance rule.
"""
from __future__ import annotations

import hashlib
import json
import os
import secrets
from pathlib import Path
from typing import Mapping

ZERO = "0" * 64
CLAUSES = (
    "onboarding_22_clear",
    "deterministic_ambiguity_revision",
    "preview_isolation",
    "approved_card_projection_gate",
    "unknown_delivery_no_retry",
    "successful_lifecycle",
    "cleanup_resume_terminal",
)

def canonical(value: object) -> bytes:
    return json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
        allow_nan=False,
    ).encode("utf-8")

def sha256_bytes(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()

class Task26EvidenceWriter:
    """Append one immutable artifact and one chained receipt per required clause."""

    def __init__(self, profile: Path, *, candidate_digest: str) -> None:
        self.root = profile / "task26-evidence"
        self.root.mkdir(mode=0o700)
        self.root.chmod(0o700)
        self.receipts = self.root / "receipts.jsonl"
        self.receipts.touch(mode=0o600)
        self.receipts.chmod(0o600)
        self.invocation_id = secrets.token_hex(16)
        self.candidate_digest = candidate_digest
        self._previous = ZERO
        self._sequence = 0

    def record(self, clause: str, payload: Mapping[str, object]) -> None:
        if clause not in CLAUSES or self._sequence >= len(CLAUSES):
            raise ValueError("Task26 clause is invalid or duplicated")
        if clause != CLAUSES[self._sequence]:
            raise ValueError("Task26 clauses must be emitted in contract order")
        self._sequence += 1
        artifact_name = f"{self._sequence:02d}-{clause}.json"
        artifact = {
            "schema": "task26-native-artifact-v1",
            "invocation_id": self.invocation_id,
            "candidate_digest": self.candidate_digest,
            "clause": clause,
            "payload": dict(payload),
        }
        artifact_bytes = canonical(artifact) + b"\n"
        artifact_path = self.root / artifact_name
        fd = os.open(
            artifact_path,
            os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW,
            0o600,
        )
        try:
            os.write(fd, artifact_bytes)
            os.fsync(fd)
        finally:
            os.close(fd)
        receipt = {
            "schema": "task26-native-receipt-v1",
            "sequence": self._sequence,
            "clause": clause,
            "invocation_id": self.invocation_id,
            "candidate_digest": self.candidate_digest,
            "previous_sha256": self._previous,
            "artifact": artifact_name,
            "artifact_sha256": sha256_bytes(artifact_bytes),
        }
        receipt["receipt_sha256"] = sha256_bytes(canonical(receipt))
        with self.receipts.open("ab") as stream:
            stream.write(canonical(receipt) + b"\n")
            stream.flush()
            os.fsync(stream.fileno())
        self._previous = str(receipt["receipt_sha256"])

    def finish(self) -> str:
        if self._sequence != len(CLAUSES):
            raise RuntimeError("Task26 evidence contract is incomplete")
        return self._previous


**Planning function verification with LSP symbols**

I read this as a proof-quality audit rather than accepting bundle summaries - I’m tracing the verifier’s clause derivations to raw native files, checking single-invocation/hash-chain enforcement, and validating each adversarial rejection path before executing it.

bash

B='.omo/evidence/task26/task26-native-seven-clause-installed-st_01a01574-v3'; V="$B/tools/verify_source_golden_path.py"; printf '%s\n' '--- verifier symbols ---'; rg -n '^def |^class |CLAUSE|task26|verify_|ACTUAL_|evidence|invocation|receipt_sha|transport' "$V" | head -500; printf '%s\n' '--- driver evidence calls ---'; rg -n 'Task26EvidenceWriter|\.record\(|finish\(|onboarding_22_clear|deterministic_ambiguity_revision|preview_isolation|approved_card_projection_gate|unknown_delivery_no_retry|successful_lifecycle|cleanup_resume_terminal|보통 수준입니다|transport' "$B/tools/source_golden_path.py"


--- verifier symbols ---
30:DEFAULT_SOURCE = Path("/home/cube/.cache/task26-strict-successor-1786976146/src-p")
31:TASK26_CLAUSES = (
100:def canonical(value: object, *, ascii_only: bool = False) -> bytes:
104:def sha(path: Path) -> str:
108:def obj(value: object, label: str) -> dict[str, Any]:
114:def read_json(path: Path, label: str) -> dict[str, Any]:
118:def serialize_terminal_inventory(terminal: object) -> dict[str, object]:
177:def lines(path: Path, label: str) -> list[dict[str, Any]]:
181:def private(path: Path, *, directory: bool = False, frozen: bool = False) -> None:
193:def verify_bootstrap_active_lineage(path: Path, customer: str) -> str:
220:def verify_provenance(root: Path) -> tuple[str, Path]:
254:def verify_installed_provenance(
277:        "task26_contract_sha256": sha(scripts / "task26_evidence_contract.py"),
326:def verify_observer(root: Path, candidate: str) -> dict[str, Any]:
353:def verify_cleanup(root: Path, customer: str) -> tuple[dict[str, Path], dict[str, Any]]:
447:def required(artifacts: dict[str, Path], suffix: str) -> Path:
454:def verify_canonical_journey_events(path: Path, customer: str) -> tuple[str, str]:
519:def verify_generation_lineage(
552:def verify_customer_quiescence(path: Path, customer: str) -> dict[str, object]:
596:def verify_task26_contract(
604:    evidence_root = root / "task26-evidence"
606:        private(evidence_root, directory=True)
607:        chain_path = evidence_root / "receipts.jsonl"
611:        raise ValueError("Task26 evidence contract is unavailable") from exc
612:    if len(receipts) != len(TASK26_CLAUSES):
613:        raise ValueError("Task26 evidence contract is incomplete")
616:        for index, clause in enumerate(TASK26_CLAUSES, 1)
618:    if {path.name for path in evidence_root.iterdir()} != expected_files:
619:        raise ValueError("Task26 evidence inventory is not exact")
622:    invocation_id: str | None = None
625:        zip(TASK26_CLAUSES, receipts, strict=True), 1
628:            "schema", "sequence", "clause", "invocation_id",
630:            "artifact_sha256", "receipt_sha256",
633:        body = {key: value for key, value in receipt.items() if key != "receipt_sha256"}
635:        current_invocation = receipt.get("invocation_id")
637:            receipt.get("schema") != "task26-native-receipt-v1"
641:            or receipt.get("receipt_sha256") != computed
642:            or not isinstance(current_invocation, str)
643:            or len(current_invocation) != 32
644:            or any(character not in "0123456789abcdef" for character in current_invocation)
645:            or (invocation_id is not None and current_invocation != invocation_id)
648:            raise ValueError("Task26 receipt chain or invocation binding is invalid")
649:        invocation_id = current_invocation
653:        artifact_path = evidence_root / artifact_name
659:            set(artifact) != {"schema", "invocation_id", "candidate_digest", "clause", "payload"}
660:            or artifact.get("schema") != "task26-native-artifact-v1"
661:            or artifact.get("invocation_id") != invocation_id
682:        raise ValueError("Task26 22-answer native evidence is incomplete")
772:        raise ValueError("Task26 preview evidence was used as production acceptance")
789:        "transport_required": False,
796:        or unknown.get("transport_calls_before_send") != 0
814:        or successful.get("transport_calls") != 1
832:    return {"clause_count": len(TASK26_CLAUSES), "chain_head": previous, "invocation_id": invocation_id}
835:def verify_native(root: Path, artifacts: dict[str, Path], customer: str, candidate: str) -> dict[str, Any]:
847:    session_id = verify_bootstrap_active_lineage(bootstrap_path, customer)
884:    checkin_id, draft_id = verify_canonical_journey_events(
890:    history = verify_generation_lineage(
905:    raw_calls = lines(root / "raw-customer-transport-calls.jsonl", "raw customer call")
907:        raise ValueError("raw transport cardinality or receipt binding is invalid")
927:    verify_customer_quiescence(service_path, customer)
937:def verify(root: Path) -> dict[str, object]:
942:    source_candidate, source = verify_provenance(root)
947:        candidate, authority_root = verify_installed_provenance(root, source_document)
955:    observer = verify_observer(root, candidate)
959:    artifacts, cleanup = verify_cleanup(root, customer)
975:    native = verify_native(root, artifacts, customer, candidate)
976:    task26_contract = verify_task26_contract(
984:        "task26_contract_head": task26_contract["chain_head"],
986:    status = "ACTUAL_INSTALLED_GOLDEN_PATH_PASS" if runtime_mode == "installed" else "ACTUAL_SOURCE_GOLDEN_PATH_PASS"
987:    return {"status": status, "runtime_mode": runtime_mode, "candidate_digest": candidate, "chain_head": chain_head, "source": str(source), "package_authority": str(authority_root), "observer_receipt_count": observer["receipt_count"], "task26_contract": task26_contract, **cleanup, **native}
990:def verify_envelope(*_args: object, **_kwargs: object) -> tuple[dict[str, object], dict[str, str]]:
994:def verify_phase_payload(phase: str, payload: dict[str, object]) -> None:
995:    calls = payload.get("transport_calls")
1001:        raise ValueError("sent audit is not bound to exactly one transport call")
1006:def main() -> int:
--- driver evidence calls ---
28:from task26_evidence_contract import Task26EvidenceWriter
48:    "보통 수준입니다.",
300:    evidence_contract = Task26EvidenceWriter(
330:    raw_customer = profile / "raw-customer-transport-calls.jsonl"
371:    runtime = TelegramNutritionOnboardingRuntime(adapter=adapter, profile_root=profile, bootstrap_transport=RoomBootstrapTransport(store, owner_id=str(OWNER_ID)), reconciler=cast(Any, UnavailableMaliciousProvider()))
398:    evidence_contract.record(
399:        "onboarding_22_clear",
497:    evidence_contract.record(
498:        "deterministic_ambiguity_revision",
526:    evidence_contract.record(
527:        "preview_isolation",
649:    evidence_contract.record(
650:        "approved_card_projection_gate",
661:    if not prepared_delivery.accepted or not prepared_delivery.transport_required:
667:    claim = coordinator.claim_delivery_transport(draft_id, owner, destination, approved.text, card_route=owner, card_message_id="700", card_nonce=nonce, card_payload_digest=payload_digest, now=datetime.now(timezone.utc), kst_date=date.today())
669:        raise RuntimeError("claim_delivery_transport rejected exact capability")
676:    evidence_contract.record(
677:        "unknown_delivery_no_retry",
682:                "transport_required": unknown_first.transport_required,
687:                "transport_required": unknown_second.transport_required,
690:            "transport_calls_before_send": len(raw_customer.read_text(encoding="utf-8").splitlines()),
705:    duplicate = coordinator.claim_delivery_transport(
720:    evidence_contract.record(
721:        "successful_lifecycle",
730:            "transport_calls": len(raw_customer.read_text(encoding="utf-8").splitlines()),
766:    evidence_contract.record(
767:        "cleanup_resume_terminal",
781:    task26_chain_head = evidence_contract.finish()


#!/usr/bin/env python3
"""Verify a source Golden Path from native production artifacts only."""
from __future__ import annotations

import argparse
import hashlib
import importlib
import importlib.util
import json
import os
import stat
import sys
from collections.abc import Mapping
from datetime import date
from pathlib import Path
from typing import Any, cast

_PROVENANCE_SPEC = importlib.util.spec_from_file_location(
    "golden_verifier_installed_wheel_provenance",
    Path(__file__).with_name("installed_wheel_provenance.py"),
)
if _PROVENANCE_SPEC is None or _PROVENANCE_SPEC.loader is None:
    raise RuntimeError("installed provenance helper is unavailable")
_PROVENANCE_MODULE = importlib.util.module_from_spec(_PROVENANCE_SPEC)
_PROVENANCE_SPEC.loader.exec_module(_PROVENANCE_MODULE)
collect_installed_runtime = _PROVENANCE_MODULE.collect_installed_runtime
loaded_module_receipts = _PROVENANCE_MODULE.loaded_module_receipts
read_private_json = _PROVENANCE_MODULE.read_private_json

DEFAULT_SOURCE = Path("/home/cube/.cache/task26-strict-successor-1786976146/src-p")
TASK26_CLAUSES = (
    "onboarding_22_clear",
    "deterministic_ambiguity_revision",
    "preview_isolation",
    "approved_card_projection_gate",
    "unknown_delivery_no_retry",
    "successful_lifecycle",
    "cleanup_resume_terminal",
)
TASK26_ANSWERS = (
    "1990년 1월 15일입니다.", "남성입니다.", "키는 180cm입니다.",
    "현재 체중은 80kg입니다.", "보통 수준입니다.",
    "주 3회 60분 근력 운동을 하고 평일에는 하루 8천 보 정도 걷습니다.",
    "현재 체중을 유지하고 싶습니다.",
    "유지가 목표라 목표 체중은 정하지 않겠습니다.",
    "유지가 목표라 목표 날짜도 정하지 않겠습니다.",
    "음식 알레르기는 없습니다.", "음식 불내증은 없습니다.",
    "종교적 또는 윤리적으로 제외하는 음식은 없습니다.",
    "싫어해서 피하는 음식은 없습니다.", "특별한 식단 선호는 없습니다.",
    "진단받은 질환은 없습니다.", "복용 중인 약이나 보충제는 없습니다.",
    "임신 또는 수유에 해당하지 않습니다.",
    "섭식장애 위험이나 과거력은 없습니다.",
    "가스레인지, 전자레인지, 냉장고를 사용할 수 있고 기본 조리가 가능합니다.",
    "식비 예산은 보통입니다.", "하루 세 끼를 먹습니다.",
    "평일 점심은 12시, 저녁은 운동 후 8시쯤이며 그 외 제약은 없습니다.",
)
PHASES = (
    "OBSERVER_SUBSCRIBED", "INVITE_RECEIPTED", "CONSENT_COMMITTED",
    "ONBOARDING_22_COMMITTED", "RECONCILIATION_COMMITTED", "CUSTOMER_ATTESTED",
    "OWNER_REVIEW_PUBLISHED", "READY_DISABLED", "ACTIVATED", "CHECKIN_FINALIZED",
    "GENERATION_DRAFTED", "OWNER_APPROVED", "APPROVED_CARD_PROJECTED",
    "CAPABILITY_ISSUED", "CAPABILITY_CONSUMED", "SENT_AUDITED",
    "SURFACE_CAPTURED", "QUIESCED", "ARCHIVED", "CLEANUP_COMPLETE",
    "SOURCE_GOLDEN_PATH_PASS",
)
ZERO = "0" * 64
TERMINAL_CATEGORY_FIELDS = frozenset(
    {
        "registry",
        "bootstrap",
        "onboarding",
        "outbox",
        "key",
        "owner_action",
        "service_state",
        "event",
        "customer_data",
        "activation",
        "sent_event",
        "candidate",
    }
)
TERMINAL_INVENTORY_FIELDS = frozenset(
    {
        "customer_key",
        "disabled",
        "nonconsenting",
        "categories",
        "active_count",
        "pending_count",
        "unknown_count",
        "orphan_count",
        "archive_verified",
        "journal_committed",
        "terminal",
    }
)

def canonical(value: object, *, ascii_only: bool = False) -> bytes:
    return json.dumps(value, ensure_ascii=ascii_only, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()

def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()

def obj(value: object, label: str) -> dict[str, Any]:
    if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
        raise ValueError(f"{label} is not an object")
    return cast(dict[str, Any], value)

def read_json(path: Path, label: str) -> dict[str, Any]:
    return obj(json.loads(path.read_text(encoding="utf-8")), label)

def serialize_terminal_inventory(terminal: object) -> dict[str, object]:
    fields = getattr(type(terminal), "__dataclass_fields__", None)
    if not isinstance(fields, dict) or set(fields) != TERMINAL_INVENTORY_FIELDS:
        raise ValueError("terminal inventory schema is invalid")
    customer_key = getattr(terminal, "customer_key", None)
    disabled = getattr(terminal, "disabled", None)
    nonconsenting = getattr(terminal, "nonconsenting", None)
    raw_categories = getattr(terminal, "categories", None)
    if not isinstance(raw_categories, Mapping):
        raise ValueError("terminal inventory categories are invalid")
    categories = dict(raw_categories)
    counts = {
        name: getattr(terminal, name, None)
        for name in (
            "active_count",
            "pending_count",
            "unknown_count",
            "orphan_count",
        )
    }
    booleans = {
        name: getattr(terminal, name, None)
        for name in (
            "archive_verified",
            "journal_committed",
            "terminal",
        )
    }
    if (
        not isinstance(customer_key, str)
        or not customer_key
        or type(disabled) is not bool
        or type(nonconsenting) is not bool
        or set(categories) != TERMINAL_CATEGORY_FIELDS
        or any(not isinstance(key, str) for key in categories)
        or any(type(value) is not int or value < 0 for value in categories.values())
        or any(type(value) is not int or value < 0 for value in counts.values())
        or any(type(value) is not bool for value in booleans.values())
    ):
        raise ValueError("terminal inventory field types are invalid")
    expected_terminal = bool(
        disabled
        and nonconsenting
        and all(value == 0 for value in counts.values())
        and booleans["archive_verified"]
        and booleans["journal_committed"]
    )
    if booleans["terminal"] is not expected_terminal:
        raise ValueError("terminal inventory verdict is inconsistent")
    return {
        "customer_key": customer_key,
        "disabled": disabled,
        "nonconsenting": nonconsenting,
        "categories": dict(sorted(categories.items())),
        **counts,
        **booleans,
    }

def lines(path: Path, label: str) -> list[dict[str, Any]]:
    return [obj(json.loads(line), label) for line in path.read_text(encoding="utf-8").splitlines() if line]

def private(path: Path, *, directory: bool = False, frozen: bool = False) -> None:
    info = path.lstat()
    if stat.S_ISLNK(info.st_mode) or info.st_uid != os.geteuid():
        raise ValueError(f"unsafe artifact path: {path}")
    expected_type = stat.S_ISDIR if directory else stat.S_ISREG
    if not expected_type(info.st_mode) or (not directory and info.st_nlink != 1):
        raise ValueError(f"artifact type is invalid: {path}")
    allowed = ({0o700, 0o500} if directory else {0o600, 0o400}) if frozen else ({0o700} if directory else {0o600})
    if stat.S_IMODE(info.st_mode) not in allowed:
        raise ValueError(f"artifact permissions are invalid: {path}")

def verify_bootstrap_active_lineage(path: Path, customer: str) -> str:
    private(path)
    ledger = read_json(path, "bootstrap ledger")
    if set(ledger) != {"schema", "sessions", "digest"}:
        raise ValueError("bootstrap ledger schema is invalid")
    sessions = ledger["sessions"]
    payload = {"schema": ledger["schema"], "sessions": sessions}
    if (
        ledger["schema"] != "telegram-customer-bootstrap-v1"
        or ledger["digest"] != hashlib.sha256(canonical(payload)).hexdigest()
        or not isinstance(sessions, list)
        or len(sessions) != 1
    ):
        raise ValueError("bootstrap ledger authority is invalid")
    session = obj(sessions[0], "bootstrap session")
    customer_draft = obj(session.get("customer_draft"), "bootstrap customer draft")
    session_id = session.get("session_id")
    if (
        customer_draft.get("customer_key") != customer
        or session.get("state") != "ACTIVE"
        or not isinstance(session_id, str)
        or not session_id
    ):
        raise ValueError("bootstrap ACTIVE lineage is invalid")
    return session_id

def verify_provenance(root: Path) -> tuple[str, Path]:
    path = root / "source-provenance.json"
    private(path)
    provenance = read_json(path, "source provenance")
    if provenance.get("schema") != "source-golden-provenance-v1":
        raise ValueError("source provenance schema is invalid")
    source = Path(str(provenance.get("source_root", "")))
    if source != DEFAULT_SOURCE or source.is_symlink() or not source.is_dir():
        raise ValueError("source provenance root is unavailable")
    rows = provenance.get("files")
    if not isinstance(rows, list) or not rows:
        raise ValueError("source provenance inventory is empty")
    expected_paths: list[str] = []
    for raw in rows:
        row = obj(raw, "source provenance row")
        relative = row.get("path")
        if not isinstance(relative, str) or Path(relative).is_absolute() or ".." in Path(relative).parts:
            raise ValueError("source provenance path is invalid")
        target = source / relative
        if target.is_symlink() or not target.is_file() or target.stat().st_nlink != 1:
            raise ValueError("source provenance file is unavailable")
        if sha(target) != row.get("sha256") or target.stat().st_size != row.get("size"):
            raise ValueError("source provenance file changed")
        expected_paths.append(relative)
    actual = sorted(
        path.relative_to(source).as_posix()
        for path in source.rglob("*.py")
        if path.is_file() and not path.is_symlink() and not any(part in {".venv", "__pycache__"} for part in path.parts)
    )
    if expected_paths != actual or hashlib.sha256(canonical(rows)).hexdigest() != provenance.get("tree_digest"):
        raise ValueError("source provenance inventory is incomplete")
    return str(provenance["tree_digest"]), source

def verify_installed_provenance(
    root: Path, source_provenance: dict[str, Any]
) -> tuple[str, Path]:
    path = root / "installed-provenance.json"
    document = read_private_json(path)
    if set(document) != {"schema", "binding", "candidate_digest", "loaded_modules"} or document.get("schema") != "installed-golden-provenance-v1":
        raise ValueError("installed provenance schema is invalid")
    binding = obj(document.get("binding"), "installed candidate binding")
    if binding.get("schema") != "installed-golden-candidate-binding-v1":
        raise ValueError("installed candidate binding schema is invalid")
    expected_candidate = hashlib.sha256(canonical(binding)).hexdigest()
    if document.get("candidate_digest") != expected_candidate:
        raise ValueError("installed candidate digest binding is invalid")
    if binding.get("source_provenance") != source_provenance:
        raise ValueError("installed source metadata binding is invalid")
    config = obj(binding.get("config"), "installed config binding")
    if config.get("runtime_mode") != "installed" or config.get("profile_source_metadata_only") != str(DEFAULT_SOURCE):
        raise ValueError("installed config binding is invalid")
    scripts = Path(__file__).resolve().parent
    expected_tools = {
        "harness_sha256": sha(scripts / "source_golden_path.py"),
        "provenance_helper_sha256": sha(scripts / "installed_wheel_provenance.py"),
        "verifier_sha256": sha(Path(__file__)),
        "task26_contract_sha256": sha(scripts / "task26_evidence_contract.py"),
    }
    if any(binding.get(key) != value for key, value in expected_tools.items()):
        raise ValueError("installed harness or verifier digest changed")
    runtime = obj(binding.get("runtime"), "installed runtime")
    distributions = obj(runtime.get("distributions"), "installed distributions")
    profile = obj(distributions.get("profile"), "installed profile distribution")
    hermes = obj(distributions.get("hermes"), "installed Hermes distribution")
    recomputed = collect_installed_runtime(
        venv=Path(str(runtime.get("venv", ""))),
        site_packages=Path(str(runtime.get("site_packages", ""))),
        profile_wheel=Path(str(profile.get("wheel_path", ""))),
        hermes_wheel=Path(str(hermes.get("wheel_path", ""))),
    )
    if recomputed != runtime:
        raise ValueError("installed runtime receipt differs from installed bytes")
    roots = tuple(
        Path(root_path)
        for distribution in (profile, hermes)
        for root_path in cast(list[str], distribution.get("package_roots"))
    )
    declarations = document.get("loaded_modules")
    if not isinstance(declarations, list) or not declarations:
        raise ValueError("installed loaded-module receipts are unavailable")
    declared_names: list[str] = []
    for raw in declarations:
        row = obj(raw, "loaded module receipt")
        name = row.get("module")
        if not isinstance(name, str) or not (name == "checkin_cli" or name.startswith("checkin_cli.") or name == "gateway" or name.startswith("gateway.")):
            raise ValueError("installed loaded-module name is invalid")
        declared_names.append(name)
    if declared_names != sorted(set(declared_names)):
        raise ValueError("installed loaded-module receipt set is invalid")
    actual_modules: dict[str, Path] = {}
    for name in declared_names:
        spec = importlib.util.find_spec(name)
        origin = None if spec is None else spec.origin
        if not isinstance(origin, str):
            raise ValueError(f"installed loaded-module origin is unavailable: {name}")
        actual_modules[name] = Path(origin)
    actual_receipts = loaded_module_receipts(actual_modules, allowed_roots=roots)
    if actual_receipts != declarations:
        raise ValueError("installed loaded-module declarations differ from import reality")
    authority = config.get("profile_package_authority")
    if not isinstance(authority, str) or Path(authority).resolve(strict=True) != Path(str(runtime["site_packages"])):
        raise ValueError("installed profile package authority is invalid")
    return expected_candidate, Path(authority)

def verify_observer(root: Path, candidate: str) -> dict[str, Any]:
    path = root / "observer-receipts.jsonl"
    private(path)
    receipts = lines(path, "observer receipt")
    if len(receipts) < 2 or receipts[0].get("kind") != "subscription_armed":
        raise ValueError("observer was not armed before mutation")
    previous = ZERO
    sequences: list[int] = []
    for row in receipts:
        if row.get("predecessor") != previous:
            raise ValueError("observer receipt chain is invalid")
        body = {key: value for key, value in row.items() if key != "receipt_hash"}
        current = hashlib.sha256(canonical(body)).hexdigest()
        if row.get("receipt_hash") != current:
            raise ValueError("observer receipt hash is invalid")
        previous = current
        if row.get("kind") == "commit_observed":
            sequence = row.get("sequence")
            if type(sequence) is not int:
                raise ValueError("observer sequence is invalid")
            sequences.append(sequence)
    armed = receipts[0]
    if armed.get("candidate_id") != candidate or sequences != list(range(1, len(sequences) + 1)) or len(sequences) < 4:
        raise ValueError("observer subscription binding is invalid")
    return {"receipt_count": len(receipts), "head": previous}

def verify_cleanup(root: Path, customer: str) -> tuple[dict[str, Path], dict[str, Any]]:
    journal = root / f"data/customer-cleanup/{customer}.journal.jsonl"
    private(journal)
    rows = lines(journal, "cleanup journal")
    phases = ["prepared", "copied_verified", "source_pruned", "committed"]
    if [row.get("phase") for row in rows] != phases:
        raise ValueError("cleanup journal is not terminal and forward-only")
    previous = ZERO
    operation = rows[0].get("operation_id")
    for row in rows:
        if row.get("operation_id") != operation or row.get("previous_digest") != previous:
            raise ValueError("cleanup journal chain is invalid")
        previous = hashlib.sha256(canonical(row, ascii_only=True)).hexdigest()
    archive = root / "data/customer-cleanup/archives" / str(operation)
    private(archive, directory=True, frozen=True)
    manifest_path = archive / "manifest.json"
    private(manifest_path, frozen=True)
    if sha(manifest_path) != rows[0].get("manifest_sha256"):
        raise ValueError("cleanup manifest digest mismatch")
    manifest = read_json(manifest_path, "cleanup manifest")
    if manifest.get("schema_version") != "customer-cleanup-archive-v2" or manifest.get("customer_key") != customer or manifest.get("operation_id") != operation:
        raise ValueError("cleanup manifest authority is invalid")
    inventory = manifest.get("inventory")
    if not isinstance(inventory, list) or not inventory:
        raise ValueError("cleanup inventory is empty")
    artifacts: dict[str, Path] = {}
    for raw in inventory:
        row = obj(raw, "cleanup inventory row")
        relative = row.get("relative_path")
        if not isinstance(relative, str) or Path(relative).is_absolute() or ".." in Path(relative).parts or relative in artifacts:
            raise ValueError("cleanup inventory path is invalid")
        target = archive / "files" / relative
        private(target, frozen=True)
        if target.stat().st_size != row.get("size") or sha(target) != row.get("sha256"):
            raise ValueError("cleanup archive bytes mismatch")
        artifacts[relative] = target
    shared = manifest.get("shared_ledger_projections")
    if not isinstance(shared, list) or len(shared) != 1:
        raise ValueError("cleanup shared-ledger projection cardinality is invalid")
    binding = obj(shared[0], "shared-ledger projection binding")
    source_relative = "data/owner-actions/draft-generations.json"
    projection_relative = f"projections/{source_relative}"
    source = root / source_relative
    projection = archive / projection_relative
    private(source)
    private(projection, frozen=True)
    if (
        binding.get("source_relative_path") != source_relative
        or binding.get("projection_archive_path") != projection_relative
        or binding.get("selector_version") != "draft-generations-customer-v1"
        or binding.get("source_sha256") != sha(source)
        or binding.get("source_size") != source.stat().st_size
        or binding.get("source_mode") != 0o600
        or binding.get("projection_sha256") != sha(projection)
    ):
        raise ValueError("cleanup shared-ledger source preservation binding is invalid")
    source_document = read_json(source, "shared draft-generation source")
    projected = read_json(projection, "draft-generation projection")
    selected = {
        token: history
        for token, history in sorted(source_document.items())
        if isinstance(history, list)
        and history
        and isinstance(history[0], dict)
        and history[0].get("customer_key") == customer
    }
    expected_projection = {
        "schema_version": "customer-cleanup-draft-generations-projection-v1",
        "customer_key": customer,
        "histories": selected,
    }
    record_digests = [
        hashlib.sha256(canonical(row, ascii_only=True)).hexdigest()
        for history in selected.values()
        for row in history
    ]
    if (
        projected != expected_projection
        or projection.read_bytes() != canonical(expected_projection, ascii_only=True) + b"\n"
        or binding.get("selected_record_count") != len(record_digests)
        or binding.get("ordered_record_digests") != record_digests
    ):
        raise ValueError("cleanup archive projection is not the exact target-only source projection")
    artifacts[projection_relative] = projection
    return artifacts, {
        "operation_id": operation,
        "inventory_count": len(inventory),
        "manifest_sha256": sha(manifest_path),
        "projection_sha256": sha(projection),
        "projection_record_count": len(record_digests),
        "preserved_source_sha256": sha(source),
    }

def required(artifacts: dict[str, Path], suffix: str) -> Path:
    matches = [path for relative, path in artifacts.items() if relative.endswith(suffix)]
    if len(matches) != 1:
        raise ValueError(f"required native artifact is unavailable or ambiguous: {suffix}")
    return matches[0]

def verify_canonical_journey_events(path: Path, customer: str) -> tuple[str, str]:
    private(path, frozen=True)
    raw_rows = lines(path, "wizard event")
    try:
        from checkin_cli.models import Event

        parsed_rows = [Event.model_validate(row) for row in raw_rows]

[560 more lines in file. Use offset=461 to continue.]


현재 체중은 80kg입니다.

주 3회 60분 근력 운동을 하고 평일에는 하루 8천 보 정도 걷습니다.

현재 체중을 유지하고 싶습니다.

유지가 목표라 목표 체중은 정하지 않겠습니다.

유지가 목표라 목표 날짜도 정하지 않겠습니다.

음식 알레르기는 없습니다.

음식 불내증은 없습니다.

종교적 또는 윤리적으로 제외하는 음식은 없습니다.

싫어해서 피하는 음식은 없습니다.

특별한 식단 선호는 없습니다.

진단받은 질환은 없습니다.

복용 중인 약이나 보충제는 없습니다.

임신 또는 수유에 해당하지 않습니다.

섭식장애 위험이나 과거력은 없습니다.

가스레인지, 전자레인지, 냉장고를 사용할 수 있고 기본 조리가 가능합니다.

식비 예산은 보통입니다.

하루 세 끼를 먹습니다.

평일 점심은 12시, 저녁은 운동 후 8시쯤이며 그 외 제약은 없습니다.


평일 점심 또는 저녁 중 하나만 가능합니다

주 3회 60분 근력 운동을 하고 평일에는 하루 8천 보 정도 걷습니다.

가스레인지, 전자레인지, 냉장고를 사용할 수 있고 기본 조리가 가능합니다.

평일 점심 또는 저녁 중 하나만 가능합니다

식사 시간 제약을 하나의 답변으로 입력해 주세요.

주 3회 60분 근력 운동을 하고 평일에는 하루 8천 보 정도 걷습니다.

가스레인지, 전자레인지, 냉장고를 사용할 수 있고 기본 조리가 가능합니다.

평일 점심은 12시, 저녁은 운동 후 8시쯤이며 그 외 제약은 없습니다.

reconciliation revision binding is stale

식사 시간 제약을 하나의 답변으로 입력해 주세요.

주 3회 60분 근력 운동을 하고 평일에는 하루 8천 보 정도 걷습니다.

가스레인지, 전자레인지, 냉장고를 사용할 수 있고 기본 조리가 가능합니다.

평일 점심은 12시, 저녁은 운동 후 8시쯤이며 그 외 제약은 없습니다.

주 3회 60분 근력 운동을 하고 평일에는 하루 8천 보 정도 걷습니다.

가스레인지, 전자레인지, 냉장고를 사용할 수 있고 기본 조리가 가능합니다.

평일 점심 또는 저녁 중 하나만 가능합니다

식사 시간 제약을 하나의 답변으로 입력해 주세요.


DraftGenerationTransitionError: delivery capability target is unavailable


현재 계획을 유지하고 다음 체크인을 확인하겠습니다.


**Planning verification for task26 clauses**


    except Exception as exc:
        raise ValueError("canonical wizard event schema is invalid") from exc
    if any(
        event.model_dump(mode="json", exclude_none=True) != row
        for event, row in zip(parsed_rows, raw_rows, strict=True)
    ):
        raise ValueError("canonical wizard event serialization is invalid")
    event_ids = [event.event_id for event in parsed_rows]
    dedupe_keys = [event.dedupe_key for event in parsed_rows]
    if (
        len(event_ids) != len(set(event_ids))
        or len(dedupe_keys) != len(set(dedupe_keys))
    ):
        raise ValueError("canonical wizard event identity is duplicated")
    checkins = [
        event for event in parsed_rows if event.event_type.value == "nutrition_checkin"
    ]
    if (
        len(checkins) != 1
        or not checkins[0].event_id
        or checkins[0].supersedes is not None
        or checkins[0].check_in is None
    ):
        raise ValueError("check-in finalization cardinality is invalid")
    lifecycle_types = ("draft_created", "draft_approved", "draft_sent")
    if {event.event_type.value for event in parsed_rows} != {
        "nutrition_checkin",
        *lifecycle_types,
    }:
        raise ValueError("canonical journey event type set is invalid")
    draft_events: dict[str, Any] = {}
    draft_id: str | None = None
    for event_type in lifecycle_types:
        matches = [event for event in parsed_rows if event.event_type.value == event_type]
        if len(matches) != 1:
            raise ValueError("draft lifecycle cardinality is invalid")
        event = matches[0]
        payload = event.draft
        if payload is None:
            raise ValueError("draft lifecycle cardinality is invalid")
        source_ref = event.provenance.source_ref
        if (
            not payload.draft_id
            or source_ref != f"pilot:{customer}:{event_type}"
            or event.dedupe_key != f"{event_type}:{customer}:{payload.draft_id}"
            or event.supersedes is not None
        ):
            raise ValueError("draft lifecycle customer binding is invalid")
        if draft_id is None:
            draft_id = payload.draft_id
        elif payload.draft_id != draft_id:
            raise ValueError("draft lifecycle identity is inconsistent")
        draft_events[event_type] = event
    if draft_id is None or set(draft_events) != set(lifecycle_types):
        raise ValueError("draft lifecycle is incomplete")
    return checkins[0].event_id, draft_id

def verify_generation_lineage(
    generations: object,
    customer: str,
    checkin_id: str,
    draft_id: str,
) -> list[dict[str, Any]]:
    document = obj(generations, "generation projection histories")
    if set(document) != {draft_id}:
        raise ValueError("generation lineage cardinality is invalid")
    history = document[draft_id]
    if not isinstance(history, list) or not history:
        raise ValueError("generation lineage is invalid")
    rows = [obj(row, "generation row") for row in history]
    if rows[-1].get("state") != "sent_audited" or any(
        row.get("customer_key") != customer
        or row.get("checkin_event_id") != checkin_id
        for row in rows
    ):
        raise ValueError("generation lineage is invalid")
    previous: str | None = None
    for row in rows:
        record_digest = row.get("record_digest")
        if (
            row.get("predecessor_digest") != previous
            or not isinstance(record_digest, str)
            or len(record_digest) != 64
            or any(character not in "0123456789abcdef" for character in record_digest)
        ):
            raise ValueError("generation digest chain is invalid")
        previous = record_digest
    return rows

def verify_customer_quiescence(path: Path, customer: str) -> dict[str, object]:
    private(path)
    document = read_json(path, "service state")
    if set(document) != {"schema", "states", "payload_digest"}:
        raise ValueError("service state ledger shape is invalid")
    states = document.get("states")
    unsigned = {"schema": document.get("schema"), "states": states}
    if (
        document.get("schema") != "customer-service-state-v1"
        or not isinstance(states, dict)
        or document.get("payload_digest")
        != hashlib.sha256(canonical(unsigned)).hexdigest()
    ):
        raise ValueError("service state ledger authority is invalid")
    for customer_key, raw_row in states.items():
        if not isinstance(customer_key, str) or not customer_key:
            raise ValueError("service state customer key is invalid")
        row = obj(raw_row, "service state row")
        updated_on = row.get("updated_on")
        try:
            valid_date = (
                isinstance(updated_on, str)
                and date.fromisoformat(updated_on).isoformat() == updated_on
            )
        except ValueError:
            valid_date = False
        if (
            set(row) != {"state", "revision", "updated_on"}
            or row.get("state") not in {"active", "paused"}
            or type(row.get("revision")) is not int
            or row["revision"] < 1
            or not valid_date
        ):
            raise ValueError("service state row is invalid")
    selected = states.get(customer)
    if not isinstance(selected, dict) or selected.get("state") != "paused":
        raise ValueError("customer quiescence is unavailable")
    return {
        "state": selected["state"],
        "revision": selected["revision"],
        "updated_on": selected["updated_on"],
    }

def verify_task26_contract(
    root: Path,
    *,
    candidate: str | None = None,
    native: Mapping[str, object] | None = None,
    cleanup: Mapping[str, object] | None = None,
) -> dict[str, object]:
    """Derive every Task26 branch verdict from raw, hash-bound API outcomes."""
    evidence_root = root / "task26-evidence"
    try:
        private(evidence_root, directory=True)
        chain_path = evidence_root / "receipts.jsonl"
        private(chain_path)
        receipts = lines(chain_path, "Task26 receipt")
    except OSError as exc:
        raise ValueError("Task26 evidence contract is unavailable") from exc
    if len(receipts) != len(TASK26_CLAUSES):
        raise ValueError("Task26 evidence contract is incomplete")
    expected_files = {"receipts.jsonl"} | {
        f"{index:02d}-{clause}.json"
        for index, clause in enumerate(TASK26_CLAUSES, 1)
    }
    if {path.name for path in evidence_root.iterdir()} != expected_files:
        raise ValueError("Task26 evidence inventory is not exact")

    previous = ZERO
    invocation_id: str | None = None
    artifacts: dict[str, dict[str, Any]] = {}
    for sequence, (clause, receipt) in enumerate(
        zip(TASK26_CLAUSES, receipts, strict=True), 1
    ):
        if set(receipt) != {
            "schema", "sequence", "clause", "invocation_id",
            "candidate_digest", "previous_sha256", "artifact",
            "artifact_sha256", "receipt_sha256",
        }:
            raise ValueError("Task26 receipt schema is invalid")
        body = {key: value for key, value in receipt.items() if key != "receipt_sha256"}
        computed = hashlib.sha256(canonical(body)).hexdigest()
        current_invocation = receipt.get("invocation_id")
        if (
            receipt.get("schema") != "task26-native-receipt-v1"
            or receipt.get("sequence") != sequence
            or receipt.get("clause") != clause
            or receipt.get("previous_sha256") != previous
            or receipt.get("receipt_sha256") != computed
            or not isinstance(current_invocation, str)
            or len(current_invocation) != 32
            or any(character not in "0123456789abcdef" for character in current_invocation)
            or (invocation_id is not None and current_invocation != invocation_id)
            or (candidate is not None and receipt.get("candidate_digest") != candidate)
        ):
            raise ValueError("Task26 receipt chain or invocation binding is invalid")
        invocation_id = current_invocation
        artifact_name = f"{sequence:02d}-{clause}.json"
        if receipt.get("artifact") != artifact_name:
            raise ValueError("Task26 artifact binding is invalid")
        artifact_path = evidence_root / artifact_name
        private(artifact_path)
        if sha(artifact_path) != receipt.get("artifact_sha256"):
            raise ValueError("Task26 artifact hash binding is invalid")
        artifact = read_json(artifact_path, "Task26 artifact")
        if (
            set(artifact) != {"schema", "invocation_id", "candidate_digest", "clause", "payload"}
            or artifact.get("schema") != "task26-native-artifact-v1"
            or artifact.get("invocation_id") != invocation_id
            or artifact.get("candidate_digest") != receipt.get("candidate_digest")
            or artifact.get("clause") != clause
        ):
            raise ValueError("Task26 native artifact envelope is invalid")
        artifacts[clause] = obj(artifact.get("payload"), f"Task26 {clause} payload")
        previous = computed

    from checkin_cli.nutrition_onboarding import QUESTION_FIELDS
    from checkin_cli.nutrition_onboarding_clarification_policy import compile_clarification_policy
    from checkin_cli.nutrition_onboarding_reconciliation import build_reconciliation
    from gateway.platforms.telegram_nutrition_onboarding_copy import parse_answer

    onboarding = artifacts["onboarding_22_clear"]
    observations = onboarding.get("observations")
    if (
        onboarding.get("question_fields") != list(QUESTION_FIELDS)
        or not isinstance(observations, list)
        or len(observations) != 22
        or len(TASK26_ANSWERS) != 22
    ):
        raise ValueError("Task26 22-answer native evidence is incomplete")
    canonical_answers: dict[str, object] = {}
    for index, (field, raw, raw_observation) in enumerate(
        zip(QUESTION_FIELDS, TASK26_ANSWERS, observations, strict=True)
    ):
        observation = obj(raw_observation, "Task26 answer observation")
        parsed = parse_answer(field, raw)
        if observation != {
            "index": index,
            "field": field,
            "raw": raw,
            "canonical": parsed,
            "before_count": index,
            "after_count": index + 1,
            "handled": True,
            "reask_count": 0,
        }:
            raise ValueError("Task26 clear answer was re-asked or miscanonicalized")
        canonical_answers[field] = parsed
    if onboarding.get("production_answers") != canonical_answers:
        raise ValueError("Task26 production answers differ from raw canonical results")

    ambiguity = artifacts["deterministic_ambiguity_revision"]
    ambiguous_answers = obj(ambiguity.get("ambiguous_answers"), "ambiguous answers")
    revised_answers = obj(ambiguity.get("revised_answers"), "revised answers")
    try:
        reference_date = date.fromisoformat(str(ambiguity.get("reference_date")))
    except ValueError as exc:
        raise ValueError("Task26 ambiguity reference date is invalid") from exc
    first = compile_clarification_policy(ambiguous_answers, reference_date=reference_date)
    second = compile_clarification_policy(ambiguous_answers, reference_date=reference_date)
    revised = compile_clarification_policy(revised_answers, reference_date=reference_date)
    first_record = build_reconciliation(
        answers=ambiguous_answers,
        answers_digest=first.answers_digest,
        advisory={"status": "unavailable"},
        reference_date=reference_date,
    )
    binding = obj(ambiguity.get("revision_binding"), "revision binding")
    native_branch = obj(ambiguity.get("native_branch"), "native ambiguity branch")
    workflow_relative = native_branch.get("workflow_path")
    if (
        not isinstance(workflow_relative, str)
        or Path(workflow_relative).is_absolute()
        or ".." in Path(workflow_relative).parts
    ):
        raise ValueError("Task26 native ambiguity workflow path is invalid")
    workflow_path = root / workflow_relative
    private(workflow_path)
    workflow = read_json(workflow_path, "native ambiguity workflow")
    changed_fields = [
        field for field in QUESTION_FIELDS
        if ambiguous_answers.get(field) != revised_answers.get(field)
    ]
    if (
        ambiguity.get("first_result") != first.model_dump(mode="json")
        or ambiguity.get("second_result") != second.model_dump(mode="json")
        or first != second
        or len(first.issues) != 1
        or first.issues[0].field != "schedule_constraints"
        or binding != {
            "issue_id": first.issues[0].issue_id,
            "field": "schedule_constraints",
            "field_index": QUESTION_FIELDS.index("schedule_constraints"),
            "answers_digest": first.answers_digest,
            "reconciliation_digest": first.result_digest,
        }
        or binding["field_index"] == 0
        or changed_fields != ["schedule_constraints"]
        or ambiguity.get("revised_result") != revised.model_dump(mode="json")
        or revised.issues
        or native_branch.get("workflow_sha256") != sha(workflow_path)
        or native_branch.get("field_zero_rejection") != "reconciliation revision binding is stale"
        or obj(native_branch.get("status"), "native revised status").get("state") != "customer_attestation"
        or native_branch.get("initial_reconciliation") != first_record
        or native_branch.get("revised_reconciliation") != workflow.get("reconciliation")
        or obj(native_branch.get("revised_reconciliation"), "native revised reconciliation").get("state") != "resolved"
        or native_branch.get("answers") != revised_answers
        or workflow.get("answers") != revised_answers
    ):
        raise ValueError("Task26 deterministic ambiguity or revision binding is invalid")

    preview = artifacts["preview_isolation"]
    if (
        preview.get("preview_phase") != "confirming"
        or preview.get("preview_clarifications") != []
        or preview.get("production_answer_count") != 22
        or preview.get("production_state") != "customer_attestation"
        or (native is not None and preview.get("production_session_id") != native.get("session_id"))
    ):
        raise ValueError("Task26 preview evidence was used as production acceptance")

    projection = artifacts["approved_card_projection_gate"]
    if (
        projection.get("projection_fault_seen") is not True
        or projection.get("projection_error") != "source-golden-approved-card-projection-fault"
        or projection.get("delivery_rows_after_failure") != {}
        or not str(projection.get("capability_error", "")).startswith(
            "DraftGenerationTransitionError: delivery capability target is unavailable"
        )
    ):
        raise ValueError("Task26 projection failure did not prevent capability issuance")

    unknown = artifacts["unknown_delivery_no_retry"]
    expected_unknown = {
        "accepted": True,
        "status": "unknown_provider_outcome",
        "transport_required": False,
    }
    unknown_ledger = obj(unknown.get("delivery_ledger"), "unknown delivery ledger")
    unknown_rows = list(unknown_ledger.values())
    if (
        unknown.get("first") != expected_unknown
        or unknown.get("second") != expected_unknown
        or unknown.get("transport_calls_before_send") != 0
        or len(unknown_rows) != 1
        or not isinstance(unknown_rows[0], dict)
        or unknown_rows[0].get("status") != "unknown_provider_outcome"
        or obj(unknown_rows[0].get("delivery_capability"), "unknown capability").get("status") != "consumed"
    ):
        raise ValueError("Task26 unknown delivery outcome was retryable")

    successful = artifacts["successful_lifecycle"]
    delivery_path = root / "data/owner-actions/draft-deliveries.json"
    if (
        successful.get("attestation_state") != "owner_review"
        or successful.get("owner_review_state") != "ready"
        or successful.get("activation_state") != "ACTIVE"
        or successful.get("checkin_finalized") is not True
        or successful.get("approval_status") != "approved"
        or successful.get("delivery_status") != "sent_audited"
        or successful.get("surface_schema") != "telegram-customer-surface-receipt-v2"
        or successful.get("transport_calls") != 1
        or successful.get("duplicate_rejected") is not True
        or successful.get("delivery_ledger_sha256") != sha(delivery_path)
    ):
        raise ValueError("Task26 successful lifecycle native binding is invalid")

    terminal = artifacts["cleanup_resume_terminal"]
    journal = root / "data/customer-cleanup/client_001.journal.jsonl"
    if (
        terminal.get("fault_phase") != "copied_verified"
        or terminal.get("fault_seen") is not True
        or terminal.get("terminal_phase") != "committed"
        or terminal.get("terminal") is not True
        or any(terminal.get(key) != 0 for key in ("active_count", "pending_count", "unknown_count", "orphan_count"))
        or terminal.get("journal_sha256") != sha(journal)
        or (cleanup is not None and terminal.get("operation_id") != cleanup.get("operation_id"))
    ):
        raise ValueError("Task26 cleanup did not resume forward to one terminal receipt")
    return {"clause_count": len(TASK26_CLAUSES), "chain_head": previous, "invocation_id": invocation_id}

def verify_native(root: Path, artifacts: dict[str, Path], customer: str, candidate: str) -> dict[str, Any]:
    if (root / "lifecycle-events.jsonl").exists():
        raise ValueError("self-authored lifecycle/PASS declarations are forbidden")
    registry = read_json(root / "customers/registry.json", "registry")
    matches = [row for row in registry.get("customers", []) if isinstance(row, dict) and row.get("customer_key") == customer]
    if len(matches) != 1 or matches[0].get("enabled") is not False or obj(matches[0].get("ai_processing_consent"), "consent").get("granted") is not False:
        raise ValueError("terminal registry authority is not withdrawn")
    activation = read_json(root / "data/customer-activation-journal.json", "activation journal")
    if activation.get("state") != "committed" or activation.get("customer_id") != customer:
        raise ValueError("activation commit is unavailable")

    bootstrap_path = root / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json"
    session_id = verify_bootstrap_active_lineage(bootstrap_path, customer)

    ready = read_json(required(artifacts, "nutrition-onboarding/ready.json"), "onboarding ready")
    baseline = read_json(required(artifacts, "nutrition-onboarding/baseline-v1.json"), "onboarding baseline")
    readiness = read_json(required(artifacts, "nutrition-onboarding/readiness-current.json"), "readiness pointer")
    receipt = read_json(required(artifacts, "nutrition-onboarding/readiness-receipt-v1.json"), "readiness receipt")
    if ready.get("state") != "ready" or ready.get("customer_key") != customer or receipt.get("delivery_enabled") is not False or receipt.get("activation_enabled") is not False:
        raise ValueError("native readiness state is invalid")
    if (
        baseline.get("customer_key") != customer
        or baseline.get("equation_sex_basis") != "male"
        or baseline.get("height_cm") != 180.0
        or baseline.get("weight_kg") != 80.0
        or baseline.get("activity_category") != "moderate"
        or baseline.get("goal_type") != "maintain"
        or baseline.get("target_weight_kg") is not None
        or baseline.get("target_date") is not None
        or baseline.get("meal_count") != 3
        or baseline.get("schedule_constraints") != TASK26_ANSWERS[-1]
        or any(
            baseline.get(field) != []
            for field in (
                "allergies", "intolerances", "religious_ethical_exclusions",
                "disliked_foods", "dietary_preferences", "conditions", "medications",
            )
        )
        or baseline.get("pregnancy_breastfeeding") is not False
        or not isinstance(baseline.get("customer_attested_at_kst"), str)
        or not isinstance(baseline.get("owner_review_receipt"), str)
        or len(str(baseline.get("owner_review_receipt"))) != 64
    ):
        raise ValueError("native onboarding baseline does not prove the canonical answers and reviews")
    for document, label in ((baseline, "baseline"), (readiness, "readiness"), (receipt, "readiness receipt")):
        claimed = document.get("digest")

[140 more lines in file. Use offset=881 to continue.]


def verify_native(root: Path, artifacts: dict[str, Path], customer: str, candidate: str) -> dict[str, Any]:
    if (root / "lifecycle-events.jsonl").exists():
        raise ValueError("self-authored lifecycle/PASS declarations are forbidden")
    registry = read_json(root / "customers/registry.json", "registry")
    matches = [row for row in registry.get("customers", []) if isinstance(row, dict) and row.get("customer_key") == customer]
    if len(matches) != 1 or matches[0].get("enabled") is not False or obj(matches[0].get("ai_processing_consent"), "consent").get("granted") is not False:
        raise ValueError("terminal registry authority is not withdrawn")
    activation = read_json(root / "data/customer-activation-journal.json", "activation journal")
    if activation.get("state") != "committed" or activation.get("customer_id") != customer:
        raise ValueError("activation commit is unavailable")

    bootstrap_path = root / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json"
    session_id = verify_bootstrap_active_lineage(bootstrap_path, customer)

    ready = read_json(required(artifacts, "nutrition-onboarding/ready.json"), "onboarding ready")
    baseline = read_json(required(artifacts, "nutrition-onboarding/baseline-v1.json"), "onboarding baseline")
    readiness = read_json(required(artifacts, "nutrition-onboarding/readiness-current.json"), "readiness pointer")
    receipt = read_json(required(artifacts, "nutrition-onboarding/readiness-receipt-v1.json"), "readiness receipt")
    if ready.get("state") != "ready" or ready.get("customer_key") != customer or receipt.get("delivery_enabled") is not False or receipt.get("activation_enabled") is not False:
        raise ValueError("native readiness state is invalid")
    if (
        baseline.get("customer_key") != customer
        or baseline.get("equation_sex_basis") != "male"
        or baseline.get("height_cm") != 180.0
        or baseline.get("weight_kg") != 80.0
        or baseline.get("activity_category") != "moderate"
        or baseline.get("goal_type") != "maintain"
        or baseline.get("target_weight_kg") is not None
        or baseline.get("target_date") is not None
        or baseline.get("meal_count") != 3
        or baseline.get("schedule_constraints") != TASK26_ANSWERS[-1]
        or any(
            baseline.get(field) != []
            for field in (
                "allergies", "intolerances", "religious_ethical_exclusions",
                "disliked_foods", "dietary_preferences", "conditions", "medications",
            )
        )
        or baseline.get("pregnancy_breastfeeding") is not False
        or not isinstance(baseline.get("customer_attested_at_kst"), str)
        or not isinstance(baseline.get("owner_review_receipt"), str)
        or len(str(baseline.get("owner_review_receipt"))) != 64
    ):
        raise ValueError("native onboarding baseline does not prove the canonical answers and reviews")
    for document, label in ((baseline, "baseline"), (readiness, "readiness"), (receipt, "readiness receipt")):
        claimed = document.get("digest")
        if claimed != hashlib.sha256(canonical({key: value for key, value in document.items() if key != "digest"})).hexdigest():
            raise ValueError(f"{label} digest is invalid")

    checkin_id, draft_id = verify_canonical_journey_events(
        required(artifacts, "wizard/events.jsonl"), customer
    )
    generations = read_json(required(artifacts, "projections/data/owner-actions/draft-generations.json"), "generation projection")
    if generations.get("schema_version") != "customer-cleanup-draft-generations-projection-v1" or generations.get("customer_key") != customer:
        raise ValueError("generation projection schema is invalid")
    history = verify_generation_lineage(
        generations.get("histories"), customer, checkin_id, draft_id
    )

    deliveries_path = root / "data/owner-actions/draft-deliveries.json"
    private(deliveries_path)
    deliveries = read_json(deliveries_path, "delivery ledger")
    if len(deliveries) != 1:
        raise ValueError("delivery cardinality is invalid")
    delivery = next(iter(deliveries.values()))
    capability = obj(delivery.get("delivery_capability"), "delivery capability")
    bindings = obj(capability.get("bindings"), "delivery capability bindings")
    if delivery.get("draft_id") != draft_id or delivery.get("customer_key") != customer or delivery.get("status") != "sent_audited" or capability.get("status") != "consumed" or bindings.get("candidate_digest") != candidate:
        raise ValueError("delivery capability lineage is invalid")

    raw_calls = lines(root / "raw-customer-transport-calls.jsonl", "raw customer call")
    if len(raw_calls) != 1 or raw_calls[0].get("provider_message_id") != delivery.get("message_id") or raw_calls[0].get("text_sha256") != hashlib.sha256(str(delivery.get("text", "")).encode()).hexdigest():
        raise ValueError("raw transport cardinality or receipt binding is invalid")
    surface_path = root / "data/owner-actions/customer-surface-receipts-v2/receipts.jsonl"
    private(surface_path)
    surfaces = lines(surface_path, "surface receipt")
    surface = surfaces[0] if len(surfaces) == 1 else {}
    if (
        surface.get("schema") != "telegram-customer-surface-receipt-v2"
        or surface.get("draft_id") != draft_id
        or surface.get("provider_message_id") != delivery.get("message_id")
        or surface.get("customer_key") != customer
        or surface.get("approved_generation") != delivery.get("generation")
        or surface.get("approved_generation_record_digest")
        != delivery.get("generation_record_digest")
        or surface.get("terminal_generation") != history[-1].get("generation")
        or surface.get("terminal_generation_record_digest")
        != history[-1].get("record_digest")
    ):
        raise ValueError("customer surface receipt descendant binding is invalid")

    service_path = root / "data/owner-actions/customer-service-state.json"
    verify_customer_quiescence(service_path, customer)
    outbox_path = root / "data/onboarding/telegram-publication-outbox-v1/ledger.json"
    private(outbox_path)
    outbox = read_json(outbox_path, "publication outbox")
    records = outbox.get("records")
    if not isinstance(records, list) or not records or any(row.get("session_id") != session_id or row.get("state") != "COMMITTED" for row in records):
        raise ValueError("publication receipt lineage is invalid")
    return {"customer_key": customer, "session_id": session_id, "draft_id": draft_id, "publication_count": len(records), "generation_count": len(history)}

def verify(root: Path) -> dict[str, object]:
    root = root.absolute()
    private(root, directory=True)
    if (root / "lifecycle-events.jsonl").exists():
        raise ValueError("self-authored lifecycle/PASS declarations are forbidden")
    source_candidate, source = verify_provenance(root)
    source_document = read_json(root / "source-provenance.json", "source provenance")
    input_doc = read_json(root / "driver-input.json", "driver input")
    runtime_mode = input_doc.get("runtime_mode", "source")
    if runtime_mode == "installed":
        candidate, authority_root = verify_installed_provenance(root, source_document)
    elif runtime_mode == "source":
        candidate, authority_root = source_candidate, source
        source_text = str(source)
        if source_text not in sys.path:
            sys.path.insert(0, source_text)
    else:
        raise ValueError("driver runtime mode is invalid")
    observer = verify_observer(root, candidate)
    customer = input_doc.get("customer_key")
    if input_doc.get("candidate_digest") != candidate or not isinstance(customer, str):
        raise ValueError("driver input binding is invalid")
    artifacts, cleanup = verify_cleanup(root, customer)
    from checkin_cli.customer_cleanup import post_cleanup_authority_inventory

    terminal = post_cleanup_authority_inventory(root, customer)
    terminal_inventory = serialize_terminal_inventory(terminal)
    if not terminal.terminal or any(
        value != 0
        for value in (
            terminal.active_count,
            terminal.pending_count,
            terminal.unknown_count,
            terminal.orphan_count,
        )
    ):
        raise ValueError("post-cleanup authority inventory is not terminal")
    cleanup["terminal_inventory"] = terminal_inventory
    native = verify_native(root, artifacts, customer, candidate)
    task26_contract = verify_task26_contract(
        root, candidate=candidate, native=native, cleanup=cleanup
    )
    chain_head = hashlib.sha256(canonical({
        "candidate": candidate,
        "observer": observer["head"],
        "manifest": cleanup["manifest_sha256"],
        "native": native,
        "task26_contract_head": task26_contract["chain_head"],
    })).hexdigest()
    status = "ACTUAL_INSTALLED_GOLDEN_PATH_PASS" if runtime_mode == "installed" else "ACTUAL_SOURCE_GOLDEN_PATH_PASS"
    return {"status": status, "runtime_mode": runtime_mode, "candidate_digest": candidate, "chain_head": chain_head, "source": str(source), "package_authority": str(authority_root), "observer_receipt_count": observer["receipt_count"], "task26_contract": task26_contract, **cleanup, **native}

def verify_envelope(*_args: object, **_kwargs: object) -> tuple[dict[str, object], dict[str, str]]:
    raise ValueError("declaration, not a production artifact")

def verify_phase_payload(phase: str, payload: dict[str, object]) -> None:
    calls = payload.get("transport_calls")
    if phase == "SENT_AUDITED" and (
        payload.get("state") != "sent_audited"
        or not isinstance(calls, list)
        or len(calls) != 1
    ):
        raise ValueError("sent audit is not bound to exactly one transport call")
    if phase == "CLEANUP_COMPLETE" and any(obj(payload.get("inventory"), "cleanup inventory").get(key) != 0 for key in ("pending", "unknown", "orphan", "residual_authorities")):
        raise ValueError("cleanup inventory is not empty")

def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("bundle", type=Path)
    args = parser.parse_args()
    try:
        print(json.dumps(verify(args.bundle), sort_keys=True, separators=(",", ":")))
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print(json.dumps({"status": "SOURCE_GOLDEN_PATH_FAIL", "reason": str(exc)}, sort_keys=True), file=sys.stderr)
        return 1
    return 0

if __name__ == "__main__":
    raise SystemExit(main())