diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70c3e041..d3da6909 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,8 +110,9 @@ jobs: # `.github/workflows/publish-image.yml` that no green run can show — that # no pull-request event reaches a job holding `packages: write`, that every # published tag is immutable, that the anonymous-pull check is actually - # anonymous, that BOTH pods are pushed and each carries its OWN controls, - # that the whole GO half runs before the first PYTHON step, and that the + # anonymous, that every image (the pod and the UI) is pushed and each + # carries its OWN controls, that the whole pod leg runs before the first UI + # step, and that the # `nix build` resolving skopeo names an OUTPUT rather than the bare # multi-output attribute whose `-man` path prints FIRST (which is what made # every run of this workflow exit 127) — and it pins them with regular @@ -122,19 +123,16 @@ jobs: # rather than the setting, and survived a mutant that flipped the real # value — and a later blind audit found four more, every one of them # measured SURVIVED against a fully green suite: the Go anonymous-pull - # proof re-aimed at the PYTHON package, the `/data`-is-empty control - # deleted from EITHER pod, and a refusal whose `exit 1` became `exit 0` + # proof re-aimed at another package, the `/data`-is-empty control + # deleted, and a refusal whose `exit 1` became `exit 0` # while both its words survived. Every control step is now pinned by its # whole normalised command text, the way every push step is. (⚠ This said # "the four control steps … the four push steps"; the UI leg made it six of # each and nothing went red. The pinned dicts are the count.) # - # ⚠ THE ORDERING CLAIM ABOVE USED TO READ "the whole PYTHON half runs before - # the first GO step", AND IT REVERSED. `cairn-store-go` is the DEPLOYED pod, - # so it publishes FIRST and is the leg least exposed to an earlier red step; - # the retracted rationale — the Go half as an unexercised first execution — - # and the run-history measurement that retired it are recorded once, in - # `tests/test_publish_workflow.py`'s ordering test, rather than restated here. + # ⚠ THE ORDERING CLAIM ABOVE WAS BETWEEN TWO PODS until the retired Python + # pod's publish leg was deleted; it is now pod-before-UI, and why is recorded + # once, in `tests/test_publish_workflow.py`'s ordering test. # # 🔴 THE STEP NAME CARRIES NO COUNT, AND `tests/test_control_mutant_count_is_pinned.py` # REFUSES ONE COMING BACK. The authz battery's number went stale twice in this same @@ -158,8 +156,8 @@ jobs: # paragraph above says it prevents. The floor WAS `m - min(50, max(1, m/20))` # for a measured `m`: close enough that a real narrowing cannot hide under # it, loose enough that removing a handful of tests in a PR does not turn - # this into a permanently-red gate nobody reads. (That formula still sets - # the parity harness's case floor.) This step's floor is now `m` ITSELF — + # this into a permanently-red gate nobody reads. (That formula also set the + # retired parity harness's case floor.) This step's floor is now `m` ITSELF — # the last transition above the `FLOOR` literal says why. # # ⚠ THIS IS AN INVARIANT GUARD, NOT REGRESSION COVERAGE. No bug ever @@ -755,7 +753,16 @@ jobs: # (+6 net in `tests/test_memeval_harness.py`, now 89, after removing the judge_ok tests) and the # world file's refusal/opt-in case (now 18). Measured 3063 with `pytest tests -p no:randomly # --collect-only -q`, so `FLOOR = m = 3063`. - FLOOR = 3063 + # ⚠ 3063 -> 881, THE FIRST LARGE MOVE DOWN, AND IT IS THE PYTHON ORACLE'S RETIREMENT: every + # Python test whose subject was the deleted client, `lib/` or `server/server.py` went with + # them (the store-API, CLI, write, instances, doctor, read-store/recall/resolver suites, + # the parity and dual-run harness ledgers, among others), the conformance suite lost its + # oracle-booting tests, and the Go-facing halves were SPLIT into new files rather than + # dropped (`test_seed.py`, `test_server_deployment_defaults.py`, + # `test_cpython_re_folding_runes.py`). The per-item record is + # `claudedocs/plan-cairn-v1-event-log.md` §6.3. Measured 881 with + # `python3 -m pytest tests -p no:randomly --collect-only -q`, so `FLOOR = m = 881`. + FLOOR = 881 t = ET.parse("/tmp/r.xml").getroot() suites = [t] if t.tag == "testsuite" else list(t) ran = sum(int(s.get("tests", 0)) for s in suites) @@ -845,8 +852,8 @@ jobs: # 🔴 `vet` BEFORE `test`, and both before the corpus. Each is a different # question: vet reads the code, the unit tests exercise the guards, and the - # conformance corpus measures the SERVED behaviour against the oracle's - # recorded contract. A green on any one of them is not the others. + # conformance corpus measures the SERVED behaviour against the contract the + # retired oracle recorded (frozen) plus the Go-recorded goldens since. A green on any one of them is not the others. # 🔴 THIS JOB IS THE TIER THAT MUST NOT SKIP A GIT-DEPENDENT TEST. # `internal/depspolicy`'s `TestAnUNTRACKEDNestedModuleIsIGNOREDButATRACKEDOneIsNOT` is the only # thing that exercises the tracked-file path behind `NestedModuleDirs` — the path that stops a @@ -1066,20 +1073,20 @@ jobs: # are the `mutants` job below, sharded, with `mutants-aggregate` checking the union. They # were this job's critical path; nothing in them depends on a step above. - # 🔴 THE LEDGERS THAT ARE BLIND TO A COMPILED CLIENT, AND THIS IS THE ONLY JOB THAT - # CAN READ THEM. `capability_ledger.cli_verbs_from_parser` asks the PYTHON argparse - # parser what subcommands it has, and `test_cairn_doctor.py` walks the `cairn` - # script's AST for its `EXIT_*` constants — neither has an equivalent for a binary. - # `tests/test_go_client_ledgers.py` reads both out of the RUNNING Go client, so it - # needs a Go toolchain and SKIPS in the `tests` job. A skip nobody counts is - # indistinguishable from a pass, which is why it is run explicitly here and why the - # step refuses on a skip rather than reading the exit code. - - name: the Go client's own verb and exit-code ledgers + # 🔴 THE PYTEST FILES THAT DRIVE A COMPILED BINARY, AND THIS IS THE ONLY JOB THAT CAN RUN + # THEM. `tests/test_go_client_ledgers.py` reads `cairn -verbs`/`-exit-codes` and + # `cairn-server -routes` out of the RUNNING binaries and compares them with the capability + # ledger; `tests/test_memeval_world.py`'s synthetic world answers its l0 arm with the real + # `cairn` client. Both need a Go toolchain and SKIP in the `tests` job. A skip nobody + # counts is indistinguishable from a pass, which is why they are run explicitly here and + # why the step refuses on a skip rather than reading the exit code. (Until the Python + # client was retired, the ledgers' other operand was that client's parser and AST.) + - name: the binaries' own ledgers, and the eval harness's synthetic world run: | set -o pipefail python3 -m pip install --quiet pytest - python3 -m pytest tests/test_go_client_ledgers.py -q -p no:randomly \ - --junitxml=/tmp/ledgers.xml | tee /tmp/ledgers.txt + python3 -m pytest tests/test_go_client_ledgers.py tests/test_memeval_world.py \ + -q -p no:randomly --junitxml=/tmp/ledgers.xml | tee /tmp/ledgers.txt python3 - <<'PY' import sys, xml.etree.ElementTree as ET t = ET.parse("/tmp/ledgers.xml").getroot() @@ -1088,30 +1095,27 @@ jobs: skipped = sum(int(s.get("skipped", 0)) for s in suites) fail = sum(int(s.get("failures", 0)) + int(s.get("errors", 0)) for s in suites) print(f"collected={ran} skipped={skipped} failed={fail}") - # 🔴 A SKIP HERE IS A REAL HOLE, NOT A DETAIL: these three tests are the ONLY - # thing that reads the Go client's tables, so a skipped one leaves the capability - # gate and the shared-exit-code ledger green over an unmeasured binary. + # 🔴 A SKIP HERE IS A REAL HOLE, NOT A DETAIL: these are the ONLY tests that read the + # binaries' tables, so a skipped one leaves the capability gate and the shared-exit-code + # ledger green over an unmeasured binary. if skipped: - print("REFUSING: a ledger test SKIPPED in the one job that can run it") + print("REFUSING: a binary-driven test SKIPPED in the one job that can run it") sys.exit(1) - # FOUR tests in that file now: the verb-set equality, the {0,9} intersection, the - # cross-client exit-code equality, and — added with the AGENTS.md weight work — the - # Go-ONLY ledger-flag set, which is the one thing that notices a third `-verbs`-shaped - # flag arriving. That last one is the gate over residual 7 in tests/parity/README.md, so - # it is exactly as load-bearing as the other three and belongs under the same floor. - # FIVE since the arcs/sessions S0 slice: the go-only ROUTE triangle (Go's - # `-routes` minus the oracle's tables == the declared go-only routes), the one - # place a Go-only route is checked against the running server binary. - if ran < 5: - print(f"REFUSING: collected {ran} < 5 — the ledger file narrowed") + # FOUR in the ledger file (the ledger-flag set, the verb set, the route triangle, the + # {0,9} exit-code intersection) and EIGHTEEN in the world file (seven tests over two + # runtimes, plus four that run once) — measured with `--collect-only`. + if ran < 22: + print(f"REFUSING: collected {ran} < 22 — a file narrowed") sys.exit(1) sys.exit(1 if fail else 0) PY - # 🔴 THE P1 GATE ITSELF: the conformance corpus, replayed against the Go - # server. At P1a it was expected to be PARTIAL — the `/recall` and `/search` - # rendering was P1b's — so this asserted a SPLIT. P1b landed the renderer and - # the split is gone, so the assertion is now zero failures of every kind. + # 🔴 THE CONFORMANCE GATE: the corpus — FROZEN at the retired Python oracle, plus the + # goldens recorded from the Go server since (`tests/conformance/README.md`) — replayed + # against the Go server built from this tree. At P1a it was expected to be PARTIAL, so + # this asserted a SPLIT; P1b landed the renderer and the assertion is zero failures of + # every kind. A tampered frozen golden is a `FAIL frozen-corpus` line, which counts as + # a failing case below. # # ⚠ THE PASS FLOOR STAYS, AND IT IS NOT REDUNDANT WITH "ZERO FAILURES". A run # that collected nothing has zero failures too; the floor is what tells a green @@ -1138,39 +1142,74 @@ jobs: skips=$(grep -c '^SKIP ' /tmp/conformance.txt || true) echo "passes=$passes failing-cases=$cases failing-normalizations=$norms failing-relations=$relations skips=$skips" - # Measured at P1b: 116 PASS lines (cases and relations), 0 failing cases, - # 0 failing normalizations, 0 failing relations, 5 SKIP lines (4 - # oracle-specific cases plus the one uniform-401 member that belongs to - # one of them). At P1a it was 94 / 22 / 44 / 0 / 5 — the 22 were every - # `/recall` and `/search` RENDERING case and the 44 were their two - # report-body normalizations, which cannot fire on a 501 body. + # Measured on the tree that retired the oracle: 211 PASS lines (cases, relations and + # the canary), 0 failing cases, 0 failing normalizations, 0 failing relations, 5 SKIP + # lines (4 frozen oracle-specific cases plus the one uniform-401 member that belongs + # to one of them). ⚠ 5 -> 0 SKIP lines (#327 audit, D1): those four rows were compared + # on no run, so they were deleted with their goldens; re-measured by RUNNING + # `run_go.sh` on that tree — `SUMMARY requests=173 assertions=929 failures=0 + # skipped=0`, 211 PASS / 0 FAIL / 0 SKIP (the PASS count is unchanged: a skipped row + # never printed a PASS). At P1b it was 116 PASS (the Go-recorded rows came later), and at + # P1a 94 / 22 / 44 / 0 / 5 — the 22 were every `/recall` and `/search` RENDERING case + # and the 44 were their two report-body normalizations, which cannot fire on a 501. # # ⚠ THE PREVIOUS VERSION OF THIS STEP ALSO CHECKED THAT EVERY FAILING LINE # NAMED A REPORT ROUTE, so a regression could not hide inside the expected # partial split. With the ceiling at zero that check is subsumed: there is no # allowed failure left for anything to hide among, which is why it is deleted # rather than kept as a second spelling of the same refusal. - if [ "$passes" -lt 116 ]; then - echo "REFUSING: $passes passes, and 116 were measured at P1b — the run got worse" + if [ "$passes" -lt 211 ]; then + echo "REFUSING: $passes passes, and 211 were measured — the run got worse" exit 1 fi if [ "$cases" -ne 0 ] || [ "$norms" -ne 0 ] || [ "$relations" -ne 0 ]; then echo "REFUSING: $cases failing cases, $norms failing normalizations," - echo " $relations failing relations; P1b measured 0 of each" + echo " $relations failing relations; 0 of each were measured" grep '^FAIL ' /tmp/conformance.txt exit 1 fi # 🔴 AND THE SKIP SET IS PINNED BY SIZE, BECAUSE A SKIP NOBODY COUNTS IS - # INDISTINGUISHABLE FROM A PASS. Four rows are `oracle_only` plus the one - # uniform-401 member belonging to one of them; the mechanism is the one thing - # in this corpus that is ALLOWED to stop comparing a case, so a fifth - # oracle-specific row appearing has to be a decision somebody made. - if [ "$skips" -ne 5 ]; then - echo "REFUSING: $skips SKIP lines, and 5 were measured — a row stopped being compared" + # INDISTINGUISHABLE FROM A PASS. No row is `oracle_only` any more; the mechanism + # is the one thing in this corpus that is ALLOWED to stop comparing a case, so a + # row starting to skip has to be a decision somebody made. + if [ "$skips" -ne 0 ]; then + echo "REFUSING: $skips SKIP lines, and 0 were measured — a row stopped being compared" grep '^SKIP ' /tmp/conformance.txt exit 1 fi + # 🔴 THE CONFORMANCE GATE'S NEGATIVE CONTROL, AGAINST THE REAL SERVER. Until the oracle was + # retired, `tests/test_conformance_suite.py` booted a deliberately MUTATED copy of it and + # required the suite to go red; there is no server left that a pytest tier without Go can + # boot. So this replays the corpus against the same Go server over a copy of the goldens + # with ONE Go-recorded golden's status changed (`sessions-authorized`: 200 -> 299), and + # requires EXACTLY that case to FAIL and nothing else — a comparator wired to nothing, or + # a run that compared nothing, cannot produce that. (A Go-recorded golden rather than a + # frozen one, so the frozen-corpus check does not fire instead and win the race.) + - name: the conformance corpus goes RED on one broken golden (negative control) + if: ${{ needs.changes.result != 'success' || needs.changes.outputs.heavy != 'false' }} + run: | + set -o pipefail + broken=$(mktemp -d) + cp tests/conformance/golden/*.json "$broken/" + python3 - "$broken/sessions-authorized.json" <<'PY' + import json, sys + path = sys.argv[1] + rec = json.load(open(path)) + assert rec["status"] == 200 and rec.get("recorded_from") == "cmd/cairn-server", rec["status"] + rec["status"] = 299 + open(path, "w").write(json.dumps(rec, indent=2, ensure_ascii=False) + "\n") + PY + tests/conformance/run_go.sh --golden-dir "$broken" > /tmp/conformance-broken.txt 2>&1 || true + grep '^SUMMARY' /tmp/conformance-broken.txt + failing=$(grep '^FAIL ' /tmp/conformance-broken.txt | grep -vE '^FAIL (normalization|relation) ' || true) + echo "failing cases: ${failing:-}" + if [ "$failing" != "FAIL sessions-authorized" ]; then + echo "REFUSING TO VOUCH: the broken golden did not fail exactly its own case, so a green" + echo "conformance run above is not evidence the comparator can go red." + exit 1 + fi + # 🔴 THE SCOPE-REFS CLOSING CHECK (part 2 of `claudedocs/plan-cairn-scope-refs.md`'s closing # condition): bare repositories over `file://`, a loopback GitHub stub, a pod serving a sources # journal written through `internal/codesrc`, and `cairn sources` / `cairn audit-refs` asserted @@ -1545,433 +1584,6 @@ jobs: if: ${{ !cancelled() }} run: python3 tests/routing_mutants.py --aggregate mutant-results --scope-from-event - # 🔴 THE P2 GATE, AND IT IS ITS OWN JOB FOR THE SAME REASON THE CORPUS IS: its verdict is - # readable on its own in the checks list, and a failure in either language can never mask it. - # It needs BOTH runtimes — the Python client is the oracle and the Go client is under test — - # so it is the one job that pins both pins. - parity: - runs-on: ubuntu-latest - needs: changes - if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.heavy != 'false') }} - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version: "1.25" - cache: false - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - # 🔴 THE CONTROLS FIRST, AND BOTH OF THEM, BECAUSE A GREEN FROM THIS HARNESS IS - # INDISTINGUISHABLE FROM A HARNESS WIRED TO NOTHING UNTIL THEY HAVE BEEN WATCHED TO WORK. - # That is not cautionary: the first full run of this gate reported 72 PASS / 0 FAIL while - # every request was refused `401 status=no-client-ip`, no cache was ever written, and every - # report rendered `store-unreachable`. Two clients failing identically compare equal. - - name: prove the differ can go RED (stdout, stderr AND the exit code) - run: python3 tests/parity/harness.py --self-test - - - name: prove the pre-flight REFUSES a pod that cannot answer - run: | - set +e - python3 tests/parity/harness.py --break-pod > /tmp/broken.txt 2>&1 - rc=$? - set -e - cat /tmp/broken.txt - # exit 2 is "could not vouch", which is a DIFFERENT verdict from 1 ("a row differs"). - if [ "$rc" -ne 2 ]; then - echo "REFUSING: a pod configured to refuse every direct request produced rc=$rc," - echo " not 2. The pre-flight is the only thing standing between this gate" - echo " and a green computed over two identical failures." - exit 1 - fi - grep -q 'REFUSING TO VOUCH' /tmp/broken.txt - - - name: the parity gate - run: | - set -o pipefail - python3 tests/parity/harness.py | tee /tmp/parity.txt - passes=$(grep -c '^PASS ' /tmp/parity.txt || true) - fails=$(grep -c '^FAIL ' /tmp/parity.txt || true) - echo "passes=$passes failures=$fails" - # 138 PASS lines measured on this head: 134 cases plus FOUR structural checks — - # re-derived by RUNNING the harness on this tree and reading `grep -c '^PASS '`, never - # by arithmetic on the previous literal. - # ⚠ 136 -> 138 ON #266's AUDIT: two more `ledger-*` rows (output that LISTS other scopes - # records them — a scope-absent recall, a refused `validate --scope`). - # ⚠ 126 -> 136 WHEN S11's READ LEDGER LANDED: nine `ledger-*` rows (each also compares - # the two clients' ledger FILES) and a fourth structural check, `read-ledger-leak`, - # which counts ledger files a client wrote with a session id the harness exported into - # its OWN environment — `env_pin` must clear it. Its line is asserted below. - # ⚠ 127 -> 126 WHEN `recall-tag-repeated-is-AND` WAS DELETED: `--tag` became SCALAR on - # an operator decision, so the row comparing the two clients on a REPEATED flag has - # nothing left to measure — a repeated scalar flag is last-wins by the same - # construction every other value-bearing flag on both clients uses. The gap to the case - # count is still three, which is the check that nothing was miscounted: both numbers - # moved by the same one. - # ⚠ 117 -> 127 WHEN THE TEN `--tag` ROWS LANDED. The gap to the case count is unchanged - # at three, which is the check that nothing was miscounted: both numbers moved by the - # same ten. - # ⚠ 110 -> 117 WHEN THE SEVEN `--ref-to` ROWS LANDED. The gap to the case count is - # unchanged at three, which is the check that nothing was miscounted: both numbers - # moved by the same seven. - # ⚠ 111 -> 110 WHEN `validate-unreadable-cache-root` WAS REMOVED: ONE row, because - # `recall` and `search` never had one — they reach the cache-ROOT walk through - # `load_store`/`LoadStore` and already agreed, so rows on them would have been - # INVARIANT guards wearing a regression row's name. The wrap that row gated is gone - # with it, and the cache-root depth is declared open again in `tests/parity/README.md` - # row 4. FOUR rows remain in this family: a mode-000 ENTRY FILE and a mode-000 SCOPE - # DIRECTORY, under `validate` and under `recall`. - # ⚠ THIS LITERAL HAS BEEN STALE BEFORE, IN THE REASSURING DIRECTION: it sat at 106 - # against a run producing 108, so deleting either of the two #111 rows left - # `passes=107 >= 106` green with no guard firing. The ledger that matters is the - # number, not the prose: run it and copy what it prints. - # ⚠ THE STALE COUNT BELOW IS KEPT AS THE RECORD OF WHAT MOVED, not as a claim about - # this head: the sentence "103 cases … The newest case is - # `validate-write-protocol-advisories`" was true two rounds ago. - # `cache-mtime-parity`, `orphan-reap-parity` and `nonregular-path-parity`. The - # last of those seeds a FIFO named `*.md` into a synced cache and runs both - # clients' `validate --no-sync` under a timeout: the world CANNOT carry a - # non-regular path (the pod tars it, and neither a fifo nor a device node - # survives that pipe), so no `Case` row can present the shape, and both clients - # wedged forever on it until the advisories were gated on the loader's own path - # classifier. The newest case is - # `validate-write-protocol-advisories`, a scope whose entries PARSE and still hold - # content no reader can reach — every other scope in the world parses cleanly, so - # both of `validate`'s advisories print their ZERO branch everywhere else and a - # client implementing neither would compare equal. - # It was 104 (102 cases) before that. 🔴 THE STRUCTURAL CHECK IS - # WHY THIS MOVED BY TWO WHILE ONLY ONE CASE LANDED: the reap returns a count no - # client prints, so it is unreachable from any stdout/stderr/exit row and has to be - # read off the filesystem. The one new case is - # `recall-focus-resolved-through-an-explicit-repo-PATH`, which hands `--repo` an - # ABSOLUTE path — the three focus rows beside it default it to `.`, so no world's - # glob metacharacter can reach the anchor through them. - # It was 102 (101 cases) before that, and 91 (90 cases) at `871e6ff`; the eleven rows - # added between those two are the - # `routes` verb, which the verb ledger requires a case for, `exit 11`, which the - # exit-code ledger requires a row to reach, TWO MULTI-INSTANCE rows that stand up - # a second pod — the shape every other row is blind to by construction, and the one - # that catches a client reading every instance from the DEFAULT instance's config — - # a routed `put` at a NON-DEFAULT alias (until it landed both `` rows were - # `routes --check`, so the routed WRITE path had no cross-client byte comparison at - # all), three routed READS, and a routed `validate` whose COUNT caught a defect in the - # ORACLE. - # ⚠ THE FLOOR IS NOT REDUNDANT WITH "ZERO FAILURES". A run that compared nothing has - # zero failures too; the floor is what tells a green gate from an absent one. - # 🔴 AND IT IS RAISED WITH EVERY ROW THAT LANDS. It sat at 98 for four rows after the - # rows were added, which is a floor that cannot see the four newest disappear. - if [ "$passes" -lt 138 ]; then - echo "REFUSING: $passes passes, and 138 were measured — the gate got smaller" - exit 1 - fi - if [ "$fails" -ne 0 ]; then - echo "REFUSING: $fails failing row(s)" - exit 1 - fi - # …and the harness's own FIVE in-run content controls, read rather than assumed — - # over SIX printed fields, which is not a miscount: see the next paragraph. - # ⚠ FOUR -> FIVE WITH THE `--tag` ROWS, AND THE "PAIR" CLAIM THAT STOOD HERE WAS - # BACKWARDS ABOUT ITS OWN MEASUREMENT. It read "a PAIR because one cannot do the job"; - # the cited measurement — stripping the tags out of `tests/parity/world.py` leaves 126 - # PASS / 0 failures, `tag-narrowing=True`, `tag-match=False`, rc 2, re-measured on this - # tree rather than carried forward (127 PASS when the corpus was 124 cases) — says the - # opposite: - # `tag-match` ALONE does the job and `tag-narrowing` is the half that cannot. The two - # are not independent either: the harness can only set `tag-match` inside the block - # `tag-narrowing` opens, so `tag-match ⟹ tag-narrowing` and a conjunction over both is - # `tag-match`. The floor term is therefore `tag-match`, and the vacuity it closes is - # the one the `--ref-to` rows shipped with until a fixture was planted. - # ⚠ `tag-narrowing` IS STILL PRINTED AND STILL NAMED IN THE ANCHOR BELOW, which is why - # this grep matches six fields for five controls: it separates "the line was never - # rendered" from "rendered at 0" for whoever reads the run, and the test named below - # requires every field the harness prints to be named here. - # 🔴 ALL SIX FIELDS ARE NAMED, AND THE ANCHOR IS WHY THAT MATTERS. A prefix match - # says nothing about the fields AFTER the ones it spells, so a short anchor reads as - # coverage of the whole line while checking only its head. - # 🔴 IT HAS GONE STALE THAT WAY TWICE, WHICH IS WHY A TEST NOW OWNS THE AGREEMENT - # RATHER THAN THIS COMMENT: `tests/test_parity_harness.py::test_the_CI_content_floor_ - # grep_names_EVERY_field_the_harness_prints` derives the field names from the - # harness's own `CONTENT-FLOOR` f-string and fails in BOTH directions — a field the - # harness prints and this grep does not name, AND a field named here the harness no - # longer prints. That second direction is what forced this line to shrink when the - # `unreadable-cache-root` sentinel was deleted with its row. Re-derive rather than - # trusting this comment: `grep -n 'CONTENT-FLOOR' tests/parity/harness.py`. - # ⚠ IN BOTH STALE ROUNDS THE MISSING SENTINELS WERE STILL ENFORCED — the harness - # refuses to vouch and exits 2, which `set -o pipefail` above turns into a failed - # step — so each was a coverage-WORDING gap rather than a hole. Widened anyway: a - # check whose comment overstates it is what stops the next reader looking. - # ⚠ THE TRAILING `mtime-files=…` FIELDS ARE DELIBERATELY NOT MATCHED: they carry a - # measured number, not a verdict, so spelling them here would make this line red on - # every corpus change. - grep -q '^CONTENT-FLOOR live-banner=True rendered-digest=True unreadable-entry=True unreadable-scope-dir=True tag-narrowing=True tag-match=True req-open=True' /tmp/parity.txt - grep -q 'dead-normalizations=0' /tmp/parity.txt - # 🔴 THE READ LEDGER (S11): all eleven `ledger-*` rows ran, the oracle wrote at least ONE - # record across them (a TOTAL, not per row — two clients that both write nothing agree on - # every ledger row, and this is the floor against that; a single row writing nothing is - # seen only by its own comparison, e.g. `ledger-sync-records-nothing` is MEANT to), and NO - # client wrote a ledger with the session id exported into the harness's environment. - grep -Eq '^READ-LEDGER rows=11 oracle-records=[1-9][0-9]* leak-files=0$' /tmp/parity.txt - - # 🔴 P1's LAST STEP, AND IT IS ITS OWN JOB FOR THE SAME REASON THE CORPUS AND THE PARITY - # GATE ARE: its verdict is readable on its own in the checks list, and a failure in either - # language can never mask it. It needs BOTH runtimes — the Python server is the oracle and - # the Go one is under test — so it pins both pins. - # - # 🔴 IT RUNS MODE 2 ONLY, AND THAT IS NOT A SHORTCUT. Mode 1 is pointed at an operator's - # real store, and this repository is PUBLIC: mode 1's per-target lines name that - # operator's scopes, so its output belongs nowhere near a CI log. Mode 2's generated store - # is synthetic by construction. `tests/dualrun/README.md` states what mode 2 can and - # cannot stand in for; CI can only ever run the synthetic one. - dualrun: - runs-on: ubuntu-latest - needs: changes - if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.heavy != 'false') }} - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version: "1.25" - cache: false - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - # 🔴 THE CONTROLS FIRST, ALL THREE, BECAUSE TWO SERVERS FAILING IDENTICALLY COMPARE - # EQUAL AND THIS GATE'S WHOLE OUTPUT IS AN EQUALITY. The P2 parity gate's first full - # run reported 72 PASS / 0 FAIL while every request was refused; there is no reason - # this shape would be safer. - - name: prove every ARM can go RED (each mutant on the comparison it names) - run: python3 tests/dualrun/harness.py --self-test - - - name: prove the PRE-FLIGHT refuses two servers that both answer nothing - run: | - set +e - python3 tests/dualrun/harness.py --break-both > /tmp/dualrun-broken.txt 2>&1 - rc=$? - set -e - cat /tmp/dualrun-broken.txt - # exit 2 is "could not vouch", which is a DIFFERENT verdict from 1 ("a target - # differs"). A 1 here would mean the gate had reported a comparison result over a - # run in which nothing was comparable. - if [ "$rc" -ne 2 ]; then - echo "REFUSING: two servers configured to refuse every direct request produced" - echo " rc=$rc, not 2. The pre-flight is the only thing standing between" - echo " this gate and a green computed over two identical failures." - exit 1 - fi - grep -q 'REFUSING TO VOUCH' /tmp/dualrun-broken.txt - - # 🔴 THE POSITIVE CONTROL, AND IT IS A DIFFERENT CLAIM FROM THE OTHER TWO. They prove - # the gate can go red; this proves the COUNT is counting the store. A harness - # enumerating a hardcoded list would print the same reassuring number over an empty one. - - name: prove the comparison count MOVES when the store grows - run: python3 tests/dualrun/harness.py --positive-control - - - name: the dual-run gate - run: | - # 🔴 `set -euo pipefail` EXPLICITLY, AND NOT BECAUSE OF A STYLE PREFERENCE. The - # runner's default shell already carries `-e`, so a step can look correct while - # depending on it — and a block whose verdict depends on the RUNNER's flags is one - # whose verdict cannot be reproduced by running the same lines locally. MEASURED: - # this block was first written with its `python3 - <<'PY'` check in the MIDDLE, - # where the heredoc's `sys.exit(1)` is swallowed by the commands after it, and - # under `bash -c` (no `-e`) it printed `REFUSING: 1 difference(s)` and exited 0. - # Every assertion is now ordered so the exit status cannot be lost, and the - # deciding check is LAST. - set -euo pipefail - python3 tests/dualrun/harness.py | tee /tmp/dualrun.txt - passes=$(grep -c '^PASS ' /tmp/dualrun.txt || true) - fails=$(grep -c '^FAIL ' /tmp/dualrun.txt || true) - echo "passes=$passes failures=$fails" - # ⚠ 478 -> 467 WHEN THE ELEVEN `tag-repeated` TARGETS WENT WITH THE REPEATABILITY: - # `?tag=` became SCALAR on an operator decision, so the one target per scope that sent - # it twice is gone — ONE per scope over nine wide scopes and two narrow ones. The gap - # to the target count is still two, which is the check that nothing was miscounted: - # both numbers moved by the same eleven. - # ⚠ 412 -> 478 WITH THE SIXTY-SIX `?tag=` TARGETS, and the gap to the target count is - # unchanged at two — which is the check that nothing was miscounted: both numbers moved - # by the same sixty-six. - # 467 PASS lines measured on this branch: 465 targets plus the audit-stream and - # process-stream arms. ⚠ THE FLOOR IS NOT REDUNDANT WITH "ZERO FAILURES" — a run - # that compared nothing has zero failures too, which is the whole reason the - # summary reports a PAIR. - if [ "$passes" -lt 467 ]; then - echo "REFUSING: $passes passes, and 467 were measured — the gate got smaller" - exit 1 - fi - if [ "$fails" -ne 0 ]; then - echo "REFUSING: $fails differing target(s)" - grep '^FAIL ' /tmp/dualrun.txt - exit 1 - fi - # Every declared licence to differ must have FIRED. One that matched nothing is - # either dead, or a difference that has been closed, or a pattern that stopped - # matching and is now hiding a real difference. - for name in date-header snapshot-gzip-envelope json-decoder-diagnostic \ - audit-timestamp-instant listen-port; do - grep -q "^DIFFERENCE $name " /tmp/dualrun.txt || { - echo "REFUSING: the declared licence '$name' did not fire"; exit 1; } - done - # …and the two arms no other gate in this repository reads at all. PRESENCE here; - # their COUNTS are floored in the block below, where a refusal can name a number. - grep -q '^PASS audit-stream' /tmp/dualrun.txt - grep -q '^PASS process-stream' /tmp/dualrun.txt - # 🔴 LAST, SO ITS EXIT STATUS IS THE STEP'S. The in-run numbers, read rather than - # assumed — the comparison floor is what makes `differences=0` mean something. - python3 - <<'PY' - import re, sys - text = open("/tmp/dualrun.txt").read() - m = re.search(r"^SUMMARY targets=(\d+) comparisons=(\d+) differences=(\d+) " - r"entries=(\d+)$", text, re.M) - if not m: - print("REFUSING: no SUMMARY line — the run did not finish") - sys.exit(1) - targets, comparisons, differences, entries = (int(g) for g in m.groups()) - # 🔴 THE TWO ARMS THAT PRINT THEIR OWN COUNT, READ AS NUMBERS AND NOT ONLY AS - # PRESENCE. `comparisons` above is a SUM over four arms and only these two publish a - # subtotal, so without these the total is the only floor and a move in it cannot be - # attributed to an arm — see the paragraph before `problems` for what that costs and - # what it still cannot buy. A FAIL arm prints no PASS line at all, so an absent match - # is a refusal rather than a zero. - arms = {} - for arm in ("audit-stream", "process-stream"): - a = re.search(rf"^PASS {arm} \((\d+) lines compared", text, re.M) - if not a: - print(f"REFUSING: no `PASS {arm} ( lines compared` line — that arm " - f"either failed or stopped reporting its own count") - sys.exit(1) - arms[arm] = int(a.group(1)) - print(f"targets={targets} comparisons={comparisons} " - f"differences={differences} entries={entries} " - f"audit-stream={arms['audit-stream']} " - f"process-stream={arms['process-stream']}") - # Measured on this branch: 465 / 1913 / 0 / 119. Floors rather than equalities, so - # ADDING a target is not a red gate; a NARROWING is. - # - # ⚠ 476 -> 465 AND 1958 -> 1913 WHEN `tag-repeated` WAS DELETED, and every part of the - # comparisons move is attributed by the same arithmetic the paragraph below demands, - # against the numbers the run PRINTS: 11 targets x 3 compared fields = 33, the audit - # stream -11 (491 -> 480, one line per target), and the process stream -1 (28 -> 27). - # 33 + 11 + 1 = 45, and 1958 - 45 = 1913. `entries` is unchanged at 119 because the tag - # arm adds no per-entry comparison. - # - # 🔴 THE PROCESS-STREAM -1 IS THE ORDERING PROOF READ BACKWARDS, AND IT IS WHY THIS IS - # -1 RATHER THAN -11. `_exit_for` writes its stderr sentence only for an UNREADABLE - # status, so the tag arm's process-stream lines were the FIVE non-malformed tag targets - # on `epsilon-rubble` — the scope whose every file is malformed — and deleting one - # target removes one of those five. Every `tag-repeated` target on any OTHER scope - # contributed nothing to that stream. - # - # ⚠ 410 -> 476 WHEN THE `?tag=` SWEEP LANDED: SIX targets per scope over nine wide - # scopes and two narrow ones, so SIXTY-SIX — counted as `PASS tag…` / `PASS search-tag…` - # lines in the run, not inferred. FIVE per scope now, and the paragraph above is the - # head this step's literals are set from. `entries` is unchanged at 119 because the tag - # arm adds no per-entry comparison, exactly as the ref-to arm did not. - # - # 🔴 AND EVERY PART OF THE COMPARISONS MOVE IS ATTRIBUTED BY MEASUREMENT, WHICH IS THE - # DISCIPLINE THE PARAGRAPH BELOW EXISTS FOR. 1689 -> 1958 is +269, and it closes - # exactly: 66 new targets x 3 compared fields = 198, the audit stream +66 (one line per - # new target, 425 -> 491), the process stream +5 (23 -> 28), and the per-scope ref-set - # arm unchanged at 11. 198 + 66 + 5 = 269. - # - # 🔴 THE PROCESS-STREAM +5 IS THE ONE THAT NEEDED MEASURING RATHER THAN ARITHMETIC, AND - # ITS MECHANISM IS ITSELF THE ORDERING PROOF. `_exit_for` writes its stderr sentence - # only for an UNREADABLE status, so the five lines are the five non-malformed tag - # targets on `epsilon-rubble` — the scope whose every file is malformed. They answer - # `scope-unreadable`/`search-unreadable` BECAUSE that discriminator runs BEFORE the tag - # filter, which is the placement the whole feature is built on; `tag-malformed` on the - # same scope adds NOTHING, because a 400 is answered before any report exists. - # Measured with `--only`: `tag-hit:wide-writer:epsilon-rubble` prints a 4-line process - # stream against a 3-line baseline, `tag-malformed` on the same scope prints 3, and - # `search-tag` on every other scope answers `search-no-match` and prints 3. - # - # ⚠ 366 -> 410 WHEN THE `?ref-to=` SWEEP LANDED: FOUR targets per scope over nine - # wide scopes and two narrow ones, so FORTY-FOUR — counted as `PASS ref-to…` / - # `PASS search-ref-to…` lines in the run, not inferred. Comparisons 1510 -> 1690 at - # that point, 1689 now — the paragraph after next says why, and it is not a loss; - # `entries` is unchanged at 119 because the ref-to arm adds no per-entry comparison. - # - # 🔴 AND THE LITERALS THIS REPLACED WERE ALREADY STALE BEFORE THAT SWEEP, WHICH IS - # WHY THE ARITHMETIC DOES NOT CLOSE ON THE OLD NUMBERS. They read 361 / 1489 / 363 - # against a tree that measured 366 / 1510 / 368 — five targets, twenty-one - # comparisons and five PASS lines of drift already present, MEASURED by running this - # harness at `021be7a` rather than derived. A difference computed against a stale - # floor attributes that drift to whatever change happens to be in flight (here it - # read as "the sweep added 49"), which is how a floor silently loosens twice over. - # Re-derive a floor by RUNNING the harness, never by subtracting from the literal - # above it. - # - # 🔴 1690 -> 1689 IS A STATUS CHANGE, NOT A NARROWING, AND THE *ARM* IS WHAT SAYS SO. - # This total is the sum of FOUR arms and exactly one of them moved. Measured by - # instrumenting `compare`, `compare_audit` and `compare_process_stream` at both heads - # over the same generated store (seed and scale unchanged), not derived: - # - # arm parent head - # per-target status + headers + body 1230 1230 (410 targets x 3, all) - # one ref-set comparison per scope 11 11 - # audit stream, line for line 425 425 - # process stream — the servers' STDERR 24 23 <- the entire delta - # - # What left the process stream is a diagnostic that was FALSE, and BOTH servers - # stopped writing it: `subsystem-recall: search-unreadable: all 2 entry files under - # `delta-mixed/` are MALFORMED — nothing could be read …`, written for the target - # `search-ref-to:wide-writer:delta-mixed`. `genstore.py` gives that scope TWO READABLE - # entries beside two malformed ones, so "nothing could be read" was a lie about it — - # the `?ref-to=` filter had skipped the readable pair upstream of the counter the - # status was selected on. A filter-driven zero now answers `search-no-match`, and - # `_exit_for` writes a stderr line only for an UNREADABLE status, so there is one - # fewer line IN EXISTENCE to compare. Isolated with - # `--only search-ref-to:wide-writer:delta-mixed`: process stream 4 lines at the - # parent and 3 at the head, that target's own three comparisons unchanged, PASS on - # both. Its status, headers and body are all still compared, so nothing about the - # response went unmeasured — and the exit code the status carries (3 -> 0) is one of - # the header fields being compared, not a field that disappeared. - # - # 🔴 HENCE WHAT THIS NUMBER IS AND IS NOT, AND THE FIRST DRAFT OF THIS PARAGRAPH WAS - # WRONG IN THE REASSURING DIRECTION. It aggregates a count of the two servers' STDERR - # LINES alongside the per-response field sets, so removing an operator diagnostic - # lowers it while every response is compared exactly as before. It said a response - # that lost a compared field "would lower it by the same 1", making the two - # "indistinguishable in the TOTAL". 🔴 MEASURED FALSE, AND WORSE THAN - # INDISTINGUISHABLE — INVISIBLE: `comparisons` is incremented at exactly THREE sites - # in `compare()` (status, the WHOLE header tuple, body), each unconditional before - # every return, so the count does not depend on how many header FIELDS the header - # comparison covers. Dropping `X-Store-Exit` from the compared set leaves - # comparisons=1689, 412 passes and differences=0 all UNCHANGED and this block exits - # 0. (The field IS compared today: forcing the Go server to emit `Exit + 7` yields - # `FAIL … header X-Store-Exit: '0' vs '7'`.) So no number here can refuse a narrowing - # INSIDE the header tuple — what refuses one is the per-field `FAIL header ` - # line and `internal/api`'s own tests, and ⚠ do NOT close the gap by counting - # per-field in `compare()`: that re-bases every floor above. - # - # 🔴 WHAT THE TWO ARM FLOORS BELOW DO BUY IS ATTRIBUTION, WHICH IS THE PART THAT WAS - # PROSE. "Attribute any move by measuring the ARMS" was an instruction to a human; the - # audit and process streams are the only arms that publish their own subtotal, so - # flooring those two makes a -1 in either one refuse under its OWN name, and a -1 that - # trips the total while both arms hold is thereby located in the per-target or ref-set - # arms. Measured on this branch: 480 and 27, the same run the 1913 came from. It does - # NOT close the invisible case above, and it does not floor the two arms that print no - # count — a floor re-derived without running the harness is a floor whose reason is a - # guess. - problems = [] - if targets < 465: - problems.append(f"targets {targets} < 465") - if comparisons < 1913: - problems.append(f"comparisons {comparisons} < 1913") - if arms["audit-stream"] < 480: - problems.append(f"audit-stream arm {arms['audit-stream']} < 480") - if arms["process-stream"] < 27: - problems.append(f"process-stream arm {arms['process-stream']} < 27") - if entries < 119: - problems.append(f"per-entry comparisons {entries} < 119") - if differences: - problems.append(f"{differences} difference(s)") - if problems: - print("REFUSING: " + "; ".join(problems)) - sys.exit(1) - PY - # 🔴 A FLAKE NOBODY BUILDS IS DECORATION, AND ITS ROT IS SILENT. `flake.nix` # is what a consumer pins — alpha-toolkit is the first — so a break here does not # surface in this repo at all: it surfaces in someone else's `home-manager @@ -1980,10 +1592,10 @@ jobs: # rather than a claim. # # Its own verdict is trustworthy for the same reason the suite's is: the - # things being built REFUSE rather than warn. `packages.cairn` runs an - # `installCheckPhase` that dies if the packaged client cannot import its own - # `lib/`, and `checks.client-resolves-its-lib` runs a real subcommand and - # fails on an ImportError. Neither can pass by doing nothing. + # things being built REFUSE rather than warn — every Go package depends on its + # module's test run, and every `checks.*` below asserts a non-empty answer. + # (The retired Python client's package and its `client-resolves-its-lib` + # check were built here until that client was deleted.) nix: runs-on: ubuntu-latest needs: changes @@ -2000,20 +1612,6 @@ jobs: # can report a failure that a sequential run of the SAME tree does not # reproduce. Separate steps also mean the checks list says WHICH output # broke instead of "the nix job is red". - - name: the client package builds, and can import its own lib/ - run: nix build .#packages.x86_64-linux.cairn --no-link --print-build-logs - - - name: the packaged client runs a real subcommand from /nix/store - run: nix build .#checks.x86_64-linux.client-resolves-its-lib --no-link --print-build-logs - - # The image is built because it is what a deployment consumes, and - # because a break in it is otherwise found only by whoever next tries to - # ship the pod — which may be months later and someone else's problem. - # This asserts it BUILDS; that it RUNS is not asserted here, and saying - # so is the point: a green here is not a claim about a working pod. - - name: the server image builds - run: nix build .#packages.x86_64-linux.server-image --no-link --print-build-logs - # 🔴 EACH GO MODULE'S SUITE RUNS ONCE IN THIS JOB, HERE, UNDER THE PINNED TOOLCHAIN — a # second, independent reading of the `go` job's verdict (the `setup-go` toolchain, no # sandbox). Every Go package below DEPENDS on its module's entry, so none of them can build @@ -2025,8 +1623,9 @@ jobs: - name: the plugins module's suite passes under the pinned toolchain (once, for both plugins) run: nix build .#checks.x86_64-linux.plugins-module-tests --no-link --print-build-logs - # 🔴 THE GO POD'S IMAGE IS BUILT HERE FOR THE REASON THE PYTHON ONE ABOVE IS, AND - # ONE MORE. `tests/test_flake_go_image_runtime_contract.py` is a STRUCTURAL check on + # 🔴 THE POD'S IMAGE IS BUILT HERE because it is what a deployment consumes, and a break + # in it is otherwise found only by whoever next tries to ship the pod — AND because + # `tests/test_flake_go_image_runtime_contract.py` is a STRUCTURAL check on # `flake.nix` — it reads the declaration and is blind to layer contents by # construction — so nothing in the `tests` job can tell a declaration that builds # from one that does not. This step is that half. It asserts it BUILDS; that it @@ -2159,8 +1758,8 @@ jobs: # 🔴 THE ONE JOB THAT RENDERS A PAGE IN A BROWSER, AND THE ONLY ONE THAT CAN SEE THE # FOUR THINGS `uiaudit/README.md` ENUMERATES. Every other job in this file reads bytes: - # the conformance corpus reads a served HTTP contract, the parity harness reads two - # CLIs' stdout, `internal/report`'s fixture reads the oracle's rendered text. None of + # the conformance corpus reads a served HTTP contract, `internal/report`'s frozen + # fixture reads the retired oracle's rendered text. None of # them can observe a cookie flag a browser HONOURED, an axe violation that is a function # of computed style, or a layout at 390px. # @@ -2905,7 +2504,7 @@ jobs: grep -F "$line" "$UIAUDIT_WORK/walk.log" done - # 🔴 THE POSTGRES TIER, AND IT IS ITS OWN JOB FOR THE REASON `parity` IS: its verdict is + # 🔴 THE POSTGRES TIER, AND IT IS ITS OWN JOB FOR THE REASON `go` IS: its verdict is # readable on its own in the checks list, and it is the ONLY job in this workflow that # can fail for "the SQL is wrong". Folding it into `go` would put a database-shaped # failure behind a 38-minute mutation battery and make the two indistinguishable at a diff --git a/.github/workflows/publish-image.yml b/.github/workflows/publish-image.yml index 7d3f01d3..83c2bd61 100644 --- a/.github/workflows/publish-image.yml +++ b/.github/workflows/publish-image.yml @@ -1,63 +1,31 @@ -# Publish the server images to a PUBLIC registry, so a cluster that holds no +# Publish the deployed images to a PUBLIC registry, so a cluster that holds no # credential for this repository can pull them. # -# 🔴 TWO PODS, TWO GHCR PACKAGES, ONE WORKFLOW. `packages.server-image` is the -# PYTHON pod and `packages.server-image-go` is the Go one; they go to -# `cairn-store` and `cairn-store-go` respectively, never to two tags of one -# package. The reason is READABILITY OF THE TAG LIST: a package holding one -# implementation can be pinned by reading it, and a mixed list distinguished only -# by a tag prefix reads as a mistake to whoever finds it later. Their tag SCHEMES -# are identical on purpose: `sha-<40-hex>` derived from the same rev, so one -# revision names one artefact in each package and the two are comparable. +# 🔴 TWO IMAGES, TWO GHCR PACKAGES, ONE WORKFLOW. `packages.server-image-go` is +# the pod and goes to `cairn-store-go`; `packages.ui-image` is the browser +# surface and goes to `cairn-ui`. Never two tags of one package: a package +# holding one artefact can be pinned by reading its tag list, and a mixed list +# distinguished only by a tag prefix reads as a mistake to whoever finds it +# later. Their tag SCHEMES are identical on purpose: `sha-<40-hex>` derived from +# the same rev, so one revision names one artefact in each package. # -# 🔴 AN EARLIER DRAFT JUSTIFIED THIS BY VISIBILITY — "sharing a package would flip -# the Go pod public as a side effect of the Python one" — AND THAT WAS BACKWARDS. -# `cairn-store` is ALREADY public (measured: an anonymous tag-list read answers -# 200), and the job below FAILS unless the Go pod is anonymously pullable, so the -# "side effect" being avoided was the state this workflow is trying to reach. The -# retracted reason is recorded rather than deleted so nobody derives it again. -# ⚠ A SECOND PREDICTION IN THIS PARAGRAPH WAS ALSO WRONG — it said the first run -# publishing a NEW package "goes red until a one-time manual flip". It did not: -# `cairn-store-go` was created PUBLIC by Actions and its proof passed first time. -# The separate package's real cost is therefore smaller than stated here, and the -# retraction with its scope lives at that step. +# ⚠ THE RETIRED PYTHON POD'S PACKAGE, `cairn-store`, IS NO LONGER PUSHED. Its +# existing tags remain in ghcr, untouched: nothing here deletes, retags or +# re-publishes them, so a deployment still pinned to one keeps pulling it. # -# 🔴 AND THE GO HALF RUNS FIRST, WHOLE, BECAUSE `cairn-store-go` IS THE DEPLOYED -# POD. Build, controls, both pushes and the anonymous-pull proof for -# `cairn-store-go` all complete before the FIRST Python-image step. The rule the -# ordering encodes: THE POD THE CLUSTER ACTUALLY PULLS PUBLISHES FIRST, so it is -# the leg LEAST exposed to an earlier step going red. Every step is exposed to -# every step in front of it; the only question this file gets to answer is which -# artefact sits at the front. -# -# ⚠ THE RETRACTED ORDERING AND ITS RETRACTED REASON, KEPT SO NOBODY RE-DERIVES -# THEM. The Python half used to run first, and the argument was: "`ci.yml` asserts -# only that the Go image BUILDS, so every Go step here is a FIRST execution, and a -# first execution in front of the Python publish gates that publish on a path that -# has never run once — the same shape as the failure this file was written to fix, -# seven runs in a row where nothing published because one step nobody had -# exercised went red." Both halves of that are spent. MEASURED before the -# reversal: the last fifteen runs of this workflow are 14 success / 1 cancelled, -# and a recent successful run executed `push the Go pod's immutable sha tag` AND -# `push the Python pod's immutable sha tag` to success — so NEITHER half is a -# first execution any more. And the pod the old ordering protected is the one -# NOTHING deploys: the cutover made `cairn-store-go` the deployed pod, so the -# Python-first ordering published the DEPLOYED pod LAST and most exposed, which -# is the opposite of what its own rationale asked for. +# 🔴 EACH LEG RUNS WHOLE — build, controls, both pushes, anonymous-pull proof — +# AND THE TWO NEVER INTERLEAVE. The pod leg runs first, then the UI leg. A red +# step in the second leg therefore cannot leave the first half-published (a sha +# tag with no proof behind it, or a sha tag with no version tag on a tag push). +# Which leg goes first is a choice; that they do not interleave is the property. # `tests/test_publish_workflow.py` pins the ORDER, not only the membership. # -# 🔴 WHY THIS EXISTS, AND WHAT WAS ACTUALLY MEASURED. `ci.yml`'s `nix` job builds -# `packages.server-image` and asserts nothing further — its own comment says so: -# "This asserts it BUILDS; that it RUNS is not asserted here". Nothing in this -# repository has ever PUBLISHED it. Measured on `main` before this file existed: -# every publish-shaped token in `ci.yml` — `docker/login`, `docker/build-push`, -# `registry`, `ghcr`, `skopeo`, `nix copy`, `docker push`, `crane`, -# `packages: write` — returned ZERO, against a positive control of 1 for -# `server-image`; and a paginated enumeration of the owner's container packages -# returned 20 names, none of them this one. The only publish path that existed -# was `server/build-push.sh`, which is run BY HAND, requires the operator to name -# a registry (`CAIRN_REGISTRY`, no default), and in practice targets a LAN-only -# host that a second cluster cannot resolve, let alone reach. +# 🔴 WHY THIS EXISTS. Before this file, nothing in this repository PUBLISHED an +# image: every publish-shaped token in `ci.yml` — `docker/login`, +# `docker/build-push`, `registry`, `ghcr`, `skopeo`, `nix copy`, `docker push`, +# `crane`, `packages: write` — returned ZERO, measured, and the only publish +# path was a by-hand script that required the operator to name a registry and +# in practice targeted a LAN-only host a second cluster could not reach. # # 🔴 A SEPARATE WORKFLOW, NOT A JOB IN `ci.yml`, AND THAT IS THE FORK-PR GUARD. # "PRs must not publish" can be written as an `if:` on a job, and an `if:` is one @@ -69,14 +37,14 @@ # class (`pull_request`, `pull_request_target`, `workflow_run` on a # PR-triggered workflow), not the one spelling somebody thought to ban. # -# 🔴 THE TAG IS IMMUTABLE AND THERE IS NO `latest`. `server/build-push.sh` states -# the reason and it is this repository's own position: "A `:latest` default is how -# a mutable tag gets clobbered by a concurrent build and a pod silently restarts -# on somebody else's code." The consuming design says both clusters pull the SAME -# tag; a tag whose contents can change under a running deployment does not satisfy -# that sentence, it only looks like it does. So: `sha-<40-hex commit sha>` always, -# plus a bare semver on a version tag push. Both are derivable from a rev, which -# is what "the same tag" needs in order to be checkable. +# 🔴 THE TAG IS IMMUTABLE AND THERE IS NO `latest`. This repository's position: +# a `:latest` default is how a mutable tag gets clobbered by a concurrent build +# and a pod silently restarts on somebody else's code. The consuming design says +# both clusters pull the SAME tag; a tag whose contents can change under a +# running deployment does not satisfy that sentence, it only looks like it does. +# So: `sha-<40-hex commit sha>` always, plus a bare semver on a version tag push. +# Both are derivable from a rev, which is what "the same tag" needs in order to +# be checkable. name: publish-image on: @@ -145,25 +113,21 @@ jobs: run: | set -euo pipefail owner=$(printf '%s' "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]') - image="ghcr.io/$owner/cairn-store" - # 🔴 A SECOND PACKAGE, NOT A SECOND TAG OF THE FIRST — and the reason is - # the TAG LIST, not visibility. A list mixing two implementations, - # separated only by a tag prefix, cannot be read by anyone pinning one. - # Do NOT restore the visibility argument: `cairn-store` is already - # public, so it was backwards. The header records why. + # 🔴 The pod's package. `cairn-store` — the retired Python pod's — is + # deliberately NOT derived here any more: nothing pushes to it, and its + # existing tags stay in ghcr untouched. image_go="ghcr.io/$owner/cairn-store-go" - # 🔴 A THIRD PACKAGE, AND IT IS THE BROWSER SURFACE RATHER THAN A POD. + # 🔴 A SECOND PACKAGE, AND IT IS THE BROWSER SURFACE RATHER THAN A POD. # `cairn-ui` serves no `/api/v1` route, so it is not interchangeable with - # either pod and gets its own package rather than a tag of one: a consumer + # the pod and gets its own package rather than a tag of it: a consumer # who pulled the wrong one would get a container that starts, health-checks # and answers nothing they asked for. image_ui="ghcr.io/$owner/cairn-ui" # The 40-hex commit sha, not the short one. Both are derivable from a # rev; only the full one cannot collide, and a registry tag is the # thing a cluster pins for months. ONE tag scheme for both packages, so - # a revision names one artefact in each and the two are comparable. + # a revision names one artefact in each. sha_tag="sha-${{ github.sha }}" - printf 'image=%s\n' "$image" >> "$GITHUB_OUTPUT" printf 'image_go=%s\n' "$image_go" >> "$GITHUB_OUTPUT" printf 'image_ui=%s\n' "$image_ui" >> "$GITHUB_OUTPUT" printf 'sha_tag=%s\n' "$sha_tag" >> "$GITHUB_OUTPUT" @@ -173,26 +137,23 @@ jobs: refs/tags/*) raw="${GITHUB_REF#refs/tags/}" # A leading `v` is stripped so the published tag matches the - # convention the deployed image already uses (`…:0.8.1`) and the - # argument `server/build-push.sh` takes (`0.8.0`). Both spellings - # of the git tag therefore land on one registry tag. + # convention the deployed image already uses (`…:0.8.1`), so both + # spellings of the git tag land on one registry tag. version_tag="${raw#v}" ;; esac printf 'version_tag=%s\n' "$version_tag" >> "$GITHUB_OUTPUT" - echo "image = $image" echo "image (go) = $image_go" echo "sha tag = $sha_tag" echo "version tag = ${version_tag:-}" - # ── THE TWO SHARED PREREQUISITES, ABOVE BOTH HALVES AND BELONGING TO + # ── THE TWO SHARED PREREQUISITES, ABOVE BOTH LEGS AND BELONGING TO # NEITHER. skopeo is the binary every push and every anonymous-pull proof # runs, and the ghcr login is what every push needs; they sit here rather - # than inside a half because whichever half goes first would otherwise own - # them, and the next reordering would strand the other half with no binary - # and no credential. They were inside the PYTHON half while that half ran - # first, which is exactly the coupling this position removes. + # than inside a leg because whichever leg goes first would otherwise own + # them, and the next reordering would strand the other leg with no binary + # and no credential. # ───────────────────────────────────────────────────────────────────────── # 🔴 skopeo IS TAKEN FROM THE FLAKE'S OWN PINNED nixpkgs, NOT FROM THE @@ -248,33 +209,15 @@ jobs: | "${{ steps.skopeo.outputs.bin }}" login ghcr.io \ -u '${{ github.actor }}' --password-stdin - # ── THE GO POD, AND IT GOES FIRST BECAUSE IT IS THE DEPLOYED ONE. Build, - # controls, both pushes and the anonymous-pull proof for `cairn-store-go` - # all complete before the FIRST Python-image step below. The cluster pulls - # THIS package, so it is the leg that must be least exposed to an earlier - # step going red. - # ⚠ THIS BLOCK USED TO SIT SECOND AND READ "Nothing below this line runs - # until the Python pod above is built, controlled, pushed and proved - # anonymously pullable … every step from here down is a FIRST execution of - # an image nothing in this repository has ever run." The second half is - # spent: this half has published green, measured on this workflow's own run - # history, so it is not a first execution. Kept so nobody re-derives it. + # ── THE POD (`cairn-store-go`). Build, controls, both pushes and the + # anonymous-pull proof all complete before the FIRST UI step below; the + # header says why the legs never interleave. # ───────────────────────────────────────────────────────────────────────── - # 🔴 THE GO POD IS BUILT HERE AND PUBLISHED BELOW, AND IT IS WHAT RUNS. - # ⚠ This read "NOTHING DEPLOYS IT YET" and cited `flake.nix` as saying the - # Go image is deployed by nothing. The first half was stale — the cluster - # pulls `cairn-store-go`. 🔴 THE SECOND HALF WAS TRUE, AND AN EARLIER DRAFT - # OF THIS SWEEP RETRACTED IT AS NEVER-TRUE: `flake.nix` DID say it, at the - # `server-image-go` block ("PUBLISHED IS NOT DEPLOYED — no manifest - # references it"), which that draft had not opened while editing the same - # file. Both are corrected now. Retracting a TRUE claim is the same defect - # as leaving a false one, pointed the other way. - # `ci.yml` does still assert only that it BUILDS. What changes HERE is - # publication, not deployment: - # `cairn-store-go` gets the same immutable tags as the Python package so - # that pointing a pod at it is a manifest edit rather than a build, - # and so the two pods over one revision can be pulled and compared. + # 🔴 THE POD IS BUILT HERE AND PUBLISHED BELOW, AND IT IS WHAT RUNS: the + # cluster pulls `cairn-store-go`. `ci.yml` asserts only that it BUILDS; + # what this file adds is publication under immutable tags, so pointing a + # deployment at a revision is a manifest edit rather than a build. # # `buildLayeredImage` is single-output, so `--print-out-paths` prints one # line here — unlike `nixpkgs#skopeo` above, which is why that step names @@ -289,25 +232,35 @@ jobs: echo "archive = $out" ls -l "$out" - # 🔴 THE GO POD'S OWN CONTROLS, AND WHICH ONES TRANSFER WAS MEASURED RATHER - # THAN ASSUMED. Copying the Python control step wholesale is the obvious - # move and it is wrong in one specific place: + # 🔴 THE POD'S CONTROLS, THREE OF THEM, AND EACH IS A DIFFERENT CLAIM. + # + # * `/data` is EMPTY — the control that matters most here. This pushes to + # a PUBLIC registry, and a store entry baked into a layer is a private + # note published to the internet: the class the leak gate exists to + # stop, one step past its reach, because the leak gate reads the TREE + # and this reads the ARTEFACT. Read through `/bin/busybox`, which + # `flake.nix`'s `goServerTools` puts in the image with `PATH=/bin`. + # * the POSITIVE half of that zero is the route ledger: + # `cairn-server -routes`, read out of the RUNNING image. "`/data` holds + # 0 files" is also what an image with no filesystem would report, so the + # zero is only a measurement once the binary is shown to be there. + # ⚠ It is NOT an interpreter `-c 'import …'` probe, which is what the + # retired Python pod's control used: this image's `Cmd[0]` is the SERVER + # BINARY, which has no `-c` and answers + # `flag provided but not defined: -c`. + # * the image RUNS and REFUSES BY NAME with no token source — it prints + # its `subsystem-store-api:` prefix and exits non-zero (78, EX_CONFIG — + # asserted as "non-zero and named" here because the exact code is + # `cmd/cairn-server`'s own printed contract, pinned by `main_test.go`, + # and restating it here would be a second spelling of it). # - # * `/data` is empty — TRANSFERS. Both images report 0, through the same - # `/bin/busybox`: `flake.nix`'s `goServerTools` is `serverTools` plus CA - # roots, so busybox and `PATH=/bin` are present here too. - # * the image RUNS and REFUSES BY NAME with no token source — TRANSFERS. - # The Go server prints the same `subsystem-store-api:` prefix and exits - # non-zero (78, EX_CONFIG — asserted as "non-zero and named" here - # because the exact code is `cmd/cairn-server`'s own printed contract, - # pinned by `main_test.go`, and restating it here would be a second - # spelling of it). - # * the POSITIVE control does NOT transfer. The Python step runs the - # image's own `Cmd[0]` — an interpreter — with `-c 'import …'`. This - # image's `Cmd[0]` is the SERVER BINARY, which has no `-c` and answers - # `flag provided but not defined: -c`. The Go equivalent is the route - # ledger: `cairn-server -routes`, read out of the RUNNING image, which - # is the one claim a build cannot make. + # 🔴 THE `/data` BLOCK IS PINNED THREE WAYS AND IT USED TO BE PINNED NONE. + # MEASURED: deleting it left the whole suite green. + # `test_the_pod_control_REFUSES_on_a_non_empty_data_directory` now reads the + # PROBE, the BRANCH on `$leaked`, and that branch's exit code; the step's + # whole command text is pinned as well. A variable which merely EXISTS is + # not a guard, so moving the measurement out of the `if` is the same defect + # as deleting it. # # 🔴 AND IT ASSERTS THE LEDGER IS NON-EMPTY AND THE BINARY EXITED 0 — IT # DOES NOT NAME ROUTES, DELIBERATELY. `AGENTS.md` states that adding a route @@ -315,8 +268,8 @@ jobs: # `tests/conformance/requests.json`, the construction check, and # `checks.go-server-declares-its-routes`. Route names written out here would # be a FIFTH spelling that none of those four can see — rename a route and - # all four stay green while this job refuses mid-push, after the Python pod - # has already been published. The question a publish control exists to + # all four stay green while this job refuses before the pod is pushed. The + # question a publish control exists to # answer is "can this binary ever observe the thing": a zero-line ledger or # a non-zero exit fails loudly here, and WHICH routes are declared is the # four ledgers' claim rather than this one's. @@ -327,7 +280,7 @@ jobs: # the control printed a refusal and published anyway. The guard that # asserted those two words is gone; # `test_no_control_step_can_REFUSE_and_exit_ZERO` reads the `exit` - # STATEMENTS of all four control steps and the branch on `$declared`. + # STATEMENTS of every control and proof step and the branch on `$declared`. - name: control — the GO image is EMPTY of store data, declares its routes, and refuses run: | set -euo pipefail @@ -372,7 +325,7 @@ jobs: echo "positive control: the server ran, exited 0 and declared $declared ledger line(s) — OK" # …and the image RUNS: with no token source it must refuse for a NAMED - # configuration reason and exit non-zero, exactly as the Python pod does. + # configuration reason and exit non-zero. set +e startup=$(docker run --rm "$loaded" 2>&1) rc=$? @@ -392,6 +345,26 @@ jobs: esac echo "control: the Go image runs and refuses by name — OK" + # 🔴 `docker-archive:` READS THE GZIPPED TAR THE FLAKE PRODUCES DIRECTLY — + # measured, not assumed: `dockerTools.buildLayeredImage` defaults to a gzip + # compressor and skopeo detects it. No decompression step, and in + # particular no change to the derivation's `compressor`, which would move + # the artefact the flake's image contract tests are pinned to. + # + # 🔴 EVERY PUSH STEP IN THIS FILE IS PINNED BY ITS WHOLE NORMALISED COMMAND + # TEXT in `tests/test_publish_workflow.py`, not by a keyword. Which archive + # goes to which package under which tag is the entire contract, and a guard + # on words is walkable by rewording. A cosmetic edit here fails that test; + # that is the price of a machine-readable claim, and it is paid on purpose. + # + # 🔴 AND SO IS EVERY `control — …` AND `PROVE …` STEP — for the same reason + # and after a measurement: they were once pinned by NOTHING, and mutants + # that re-aimed a proof at another package, deleted the `/data` emptiness + # check, and turned a refusal's `exit 1` into `exit 0` each SURVIVED a fully + # green suite. Reformatting any of them now fails a test. + # ⚠ NO COUNTS HERE, DELIBERATELY. A count of these steps went stale once + # already with nothing going red; the pinned dicts in + # `tests/test_publish_workflow.py` ARE the count. - name: push the Go pod's immutable sha tag run: | set -euo pipefail @@ -424,9 +397,9 @@ jobs: # So the refusal below STAYS: it is cheap, and it is the only thing that # would catch the case where the inheritance does not happen. # - # …once, by hand, and re-runs the workflow (`workflow_dispatch` is in the - # trigger set for exactly this). The same thing happened to `cairn-store`; - # the step below prints the owner-substituted URL when it refuses. + # If it does refuse, the remedy is a one-time visibility flip, by hand, + # then a re-run (`workflow_dispatch` is in the trigger set for exactly + # this); the step prints the owner-substituted URL when it refuses. # # 🔴 THE STEP IS NOT SOFTENED FOR THAT. A `continue-on-error` here would # make the first run green and every LATER regression green too — and a @@ -434,33 +407,36 @@ jobs: # job, which is the whole reason this check exists. An expected failure # that is explained is cheaper than a gate that cannot fail. # - # 🔴 AND THE WHOLE GO HALF NOW RUNS BEFORE THE WHOLE PYTHON ONE, NOT ONLY - # THIS STEP. The deployed pod publishes first, so this half is the one least - # exposed to an earlier red step; a step of the PYTHON half going red can no - # longer strand it. - # ⚠ TWO RETRACTED VERSIONS OF THIS PARAGRAPH, KEPT SO NEITHER IS RE-DERIVED. - # It first read "the whole Go half runs AFTER the whole Python one … an - # earlier draft put the Go build and the Go controls in front of the Python - # push and claimed 'it runs last' on the strength of this step alone — which - # left the THEN-deployed Python pod unable to publish if any first-execution - # Go step went red, the exact failure mode of the seven runs this file was - # written to fix." Then it said "the pod that IS deployed", which named the - # right pod only before the cutover. Both are spent: this half is no longer - # a first execution — it has published green, measured on the run history — - # and the pod the ordering protected is the one nothing pulls. The narrow - # claim the first version got RIGHT survives and is the reason the step below - # is still not softened: "it runs last" is a property of ONE step, never of - # the half it is read as covering. + # 🔴 `--no-creds` IS THE POINT: it is the same read an unauthenticated + # cluster makes. The run is still logged in from the login step, so without + # that flag this would pass on THIS job's credentials and prove nothing — a + # private image and a working one are indistinguishable from inside this + # job, and the difference only surfaces as `ImagePullBackOff` in somebody + # else's cluster. + # + # 🔴 AND THE `ref` IS PER-PACKAGE. The absent-tag control is COUNTED one per + # package; the reference that must RESOLVE is reached through `$ref`, one + # indirection away, and was once constrained by nothing — MEASURED: aiming + # it at another package left the suite green while the job printed + # `ANONYMOUS PULL OK` for the wrong package. + # `test_each_anonymous_proof_inspects_ITS_OWN_package` pins each proof + # step's `ref`, forbids the other package's expression anywhere in the + # step, and requires the printed settings URL to name this step's package. + # + # ⚠ "It runs last" was once claimed of a whole leg on the strength of this + # step alone. That is a property of ONE step, never of the leg it is read + # as covering; the leg ordering is pinned separately. - name: PROVE the published GO image is pullable with NO credentials run: | set -euo pipefail ref='${{ steps.ref.outputs.image_go }}:${{ steps.ref.outputs.sha_tag }}' skopeo='${{ steps.skopeo.outputs.bin }}' - # This package's OWN negative control. The Python step's control says - # nothing about this registry path: they are two packages with two - # visibility settings, and an instrument proved honest about one of - # them has not been proved honest about the other. + # This package's OWN negative control, FIRST, so a pass below is a + # measurement rather than a claim. Another package's control says + # nothing about this registry path: separate packages have separate + # visibility settings, and an instrument proved honest about one has + # not been proved honest about another. set +e $skopeo inspect --no-creds \ "docker://${{ steps.ref.outputs.image_go }}:sha-0000000000000000000000000000000000000000" \ @@ -511,223 +487,11 @@ jobs: echo "digest: $digest" echo "pin this in a deployment: $ref" - # ── THE PYTHON POD, AND IT GOES SECOND BECAUSE NOTHING DEPLOYS IT. - # Everything about `cairn-store` — build, control, both pushes, and the - # anonymous-pull proof — happens after the whole Go half above. ⚠ This read - # "happens before the first Go step", which was true and is not: the - # ordering reversed when `cairn-store-go` became the deployed pod. Publishing - # this half is still load-bearing — it is the ORACLE, and the parity gate - # compares against it until P8 — so a red step here still stops a publish; - # it stops the publish of the pod that nothing pulls. - # ───────────────────────────────────────────────────────────────────────── - - # 🔴 ONE BUILD, AND IT IS THE FLAKE'S. A second `docker build` here would - # be a THIRD way to produce this pod, and the premise of - # `tests/test_flake_image_matches_dockerfile.py` is that there are two and - # they are pinned against each other. Publishing the nix output keeps the - # published artefact inside that pin. - - name: build the Python server image from the flake - id: build - run: | - set -euo pipefail - out=$(nix build .#packages.x86_64-linux.server-image \ - --no-link --print-out-paths --print-build-logs) - printf 'archive=%s\n' "$out" >> "$GITHUB_OUTPUT" - echo "archive = $out" - ls -l "$out" - - # 🔴 THE CONTROL THAT MATTERS MOST HERE, AND IT IS STRICTER THAN THE ONE IN - # `server/build-push.sh` FOR A REASON: that script pushes to whatever - # registry the operator names, usually a private one. This pushes to a - # PUBLIC one. A store entry baked into a layer is a private note published - # to the internet — the exact class the leak gate exists to stop, one step - # past the leak gate's reach, because the leak gate reads the TREE and this - # reads the ARTEFACT. - # - # 🔴 AND IT IS A PAIR. "`/data` holds 0 files" is also what an image with no - # filesystem at all would report, and a reassuring zero is indistinguishable - # from a probe wired to nothing. The second command is the positive half: - # the code IS in the image and imports, so the zero above was measured - # against a real root. - # - # 🔴 THE `/data` BLOCK IS PINNED THREE WAYS AND IT USED TO BE PINNED NONE. - # MEASURED: deleting it from EITHER pod's control left the whole suite - # green. `test_both_image_controls_REFUSE_on_a_non_empty_data_directory` - # now reads the PROBE, the BRANCH on `$leaked`, and that branch's exit - # code; this step's whole command text is pinned as well. Do not delete or - # reword it without reading that test — and note that a variable which - # merely EXISTS is not a guard, so moving the measurement out of the `if` - # is the same defect as deleting it. - - name: control — /data is EMPTY in the image, and the code is really there - run: | - set -euo pipefail - loaded=$(docker load -i "${{ steps.build.outputs.archive }}" \ - | sed -n 's/^Loaded image: //p') - echo "loaded = $loaded" - test -n "$loaded" - - leaked=$(docker run --rm --entrypoint /bin/busybox "$loaded" \ - sh -c 'ls -A /data | wc -l') - if [ "$leaked" != "0" ]; then - echo "REFUSING TO PUBLISH: /data in the image holds $leaked entr(y|ies)." - echo " This image is about to become PUBLIC. Store content must arrive" - echo " at runtime on a volume and must never be in a layer." - docker run --rm --entrypoint /bin/busybox "$loaded" sh -c 'ls -A /data' - exit 1 - fi - echo "control: /data holds $leaked files (must be 0) — OK" - - # 🔴 THE INTERPRETER IS READ OUT OF THE IMAGE'S OWN `Cmd`, NOT SPELLED - # `python3`. It is NOT on this image's `PATH` — measured: `PATH=/bin` - # and `/bin` is busybox alone, so `command -v python3` returns nothing. - # `server/build-push.sh` gets away with the bare name because the - # Dockerfile image is `python:3.12-slim` and inherits one; the flake - # image names an absolute store path in `Cmd` instead. A control - # written the other way would fail here for a reason that has nothing - # to do with what it claims to measure. - py=$(docker inspect -f '{{index .Config.Cmd 0}}' "$loaded") - echo "interpreter (from the image's own Cmd) = $py" - docker run --rm --entrypoint "$py" "$loaded" -c \ - 'import sys; sys.path.insert(0, "/app/lib"); import subsystem_recall as r; print("positive control: subsystem_recall imported,", len(r.RECALL_MODES), "modes")' - - # …and the image RUNS: with no token source it must refuse for a NAMED - # configuration reason and exit non-zero, which is a different claim - # from "the container was created". A container that started and sat - # there would satisfy a naive smoke test and tell you nothing. - set +e - startup=$(docker run --rm "$loaded" 2>&1) - rc=$? - set -e - echo "no-config start: rc=$rc" - echo "$startup" - if [ "$rc" -eq 0 ]; then - echo "REFUSING TO PUBLISH: the server exited 0 with no token source." - echo " It is supposed to refuse. A 0 here means the entrypoint is not" - echo " running the server at all." - exit 1 - fi - case "$startup" in - *"subsystem-store-api:"*) ;; - *) echo "REFUSING TO PUBLISH: the refusal did not come from the server" - exit 1 ;; - esac - echo "control: the image runs and refuses by name — OK" - - # 🔴 `docker-archive:` READS THE GZIPPED TAR THE FLAKE PRODUCES DIRECTLY — - # measured, not assumed: `dockerTools.buildLayeredImage` defaults to a gzip - # compressor and skopeo detects it. No decompression step, and in - # particular no change to the derivation's `compressor`, which would move - # the artefact that `test_flake_image_matches_dockerfile.py` is pinned to. - # - # 🔴 EVERY PUSH STEP IN THIS FILE IS PINNED BY ITS WHOLE NORMALISED COMMAND - # TEXT in `tests/test_publish_workflow.py`, not by a keyword. Which archive - # goes to which package under which tag is the entire contract, and a guard - # on words is walkable by rewording. A cosmetic edit here fails that test; - # that is the price of a machine-readable claim, and it is paid on purpose. - # - # 🔴 AND SO IS EVERY `control — …` AND `PROVE …` STEP — for the same reason - # and after a measurement: three of them were pinned by NOTHING, and mutants - # that re-aimed the Go proof at the Python package, deleted either pod's - # `/data` emptiness check, and turned a refusal's `exit 1` into `exit 0` - # each SURVIVED a fully green suite. Reformatting any of them now fails a - # test. - # ⚠ NO COUNTS HERE, DELIBERATELY. This said FOUR of each and "those eight - # steps" while SIX of each existed — the UI leg made it stale and nothing - # went red. The pinned dicts in `tests/test_publish_workflow.py` ARE the - # count; a number restated beside them is one more thing to forget. It also - # said the push steps were "BELOW", which the Go-first reordering made false - # for the Go pair that now runs above this comment. - - name: push the Python pod's immutable sha tag - run: | - set -euo pipefail - "${{ steps.skopeo.outputs.bin }}" copy --all \ - "docker-archive:${{ steps.build.outputs.archive }}" \ - "docker://${{ steps.ref.outputs.image }}:${{ steps.ref.outputs.sha_tag }}" - - - name: push the Python pod's version tag, on a tag push only - if: steps.ref.outputs.version_tag != '' - run: | - set -euo pipefail - "${{ steps.skopeo.outputs.bin }}" copy --all \ - "docker-archive:${{ steps.build.outputs.archive }}" \ - "docker://${{ steps.ref.outputs.image }}:${{ steps.ref.outputs.version_tag }}" - - # 🔴 THE ONLY CHECK THAT ANSWERS THE QUESTION THIS WORKFLOW EXISTS FOR, AND - # A GREEN PUSH DOES NOT ANSWER IT. A ghcr package is PRIVATE on first - # publish. A private image and a working one are indistinguishable from - # inside this job — the push succeeded either way — and the difference only - # surfaces as `ImagePullBackOff` in somebody else's cluster, hours later, - # with nothing pointing back here. - # - # `--no-creds` is the point: it is the same read an unauthenticated cluster - # makes. The run is still logged in from two steps ago, so without that flag - # this would pass on THIS job's credentials and prove nothing at all. - # - # 🔴 AND THE `ref` IS PER-PACKAGE, WHICH NOTHING USED TO SAY. The absent-tag - # control below is COUNTED one per package; the reference that must RESOLVE - # is reached through `$ref`, one indirection away, and was constrained by - # nothing. MEASURED: aiming the GO step's `ref` at this package left the - # suite green while the job pushed the Go image and then printed - # `ANONYMOUS PULL OK` for `cairn-store`. - # `test_each_anonymous_proof_inspects_ITS_OWN_package` now pins each proof - # step's `ref`, forbids the other package's expression anywhere in the - # step, and requires the printed settings URL to name this step's package. - - name: PROVE the published image is pullable with NO credentials - run: | - set -euo pipefail - ref='${{ steps.ref.outputs.image }}:${{ steps.ref.outputs.sha_tag }}' - skopeo='${{ steps.skopeo.outputs.bin }}' - - # The negative control FIRST, so a pass below is a measurement rather - # than a claim: if an inspect of a tag that cannot exist also succeeds, - # this instrument is answering something other than the question. - set +e - $skopeo inspect --no-creds \ - "docker://${{ steps.ref.outputs.image }}:sha-0000000000000000000000000000000000000000" \ - >/dev/null 2>&1 - control_rc=$? - set -e - if [ "$control_rc" -eq 0 ]; then - echo "REFUSING: an anonymous inspect of a tag that does not exist SUCCEEDED." - echo " This check cannot distinguish a public image from anything." - exit 1 - fi - echo "negative control: absent tag refused anonymously (rc=$control_rc) — OK" - - set +e - out=$($skopeo inspect --no-creds "docker://$ref" 2>&1) - rc=$? - set -e - if [ "$rc" -ne 0 ]; then - echo "$out" - echo - echo "REFUSING: $ref was PUSHED but cannot be pulled without credentials." - echo " A package created by Actions in a PUBLIC repo has been measured to" - echo " come out PUBLIC, so this is NOT the expected first-publish state --" - echo " something made this one private. GitHub exposes no REST route for" - echo " the flip; it is a ONE-TIME manual step, per package:" - echo - echo " https://github.com/users/${{ github.repository_owner }}/packages/container/cairn-store/settings" - echo " -> Danger Zone -> Change visibility -> Public" - echo - echo " Until then no cluster outside this repository can pull this image," - echo " which is the entire reason this workflow exists." - exit 1 - fi - # A here-string and readers that drain their input — never `| head` - # under `pipefail` over an output that grows; the Go proof says why. - sed -n '1,20p' <<<"$out" - digest=$(sed -n 's/.*"Digest": "\([^"]*\)".*/\1/p' <<<"$out" | sed -n '1p') - echo - echo "ANONYMOUS PULL OK: $ref" - echo "digest: $digest" - echo "pin this in a deployment: $ref" - # ── THE BROWSER SURFACE. Build, controls, both pushes and its own - # anonymous-pull proof, AFTER both pods for the reason the Python/Go split - # already records: a leg that fails must not leave an earlier one half-published. + # anonymous-pull proof, AFTER the whole pod leg and never interleaved with + # it: a leg that fails must not leave an earlier one half-published. # - # 🔴 IT IS NOT A POD AND ITS CONTROLS ARE NOT THE PODS'. A copy of the Go pod's + # 🔴 IT IS NOT A POD AND ITS CONTROLS ARE NOT THE POD'S. A copy of the Go pod's # control would assert a route ledger this binary does not have — `cairn-ui` # registers no `-routes` flag — so a transplanted control fails for the wrong # reason or gets edited until it passes. What transfers is the SHAPE: make the diff --git a/AGENTS.md b/AGENTS.md index 39f92964..7ccca551 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,8 +62,7 @@ every session pays both before doing anything, and the prose rule above did not in one session (the measured curve is in the test). `tests/test_agent_instructions_weight.py` owns the ceiling and the working margin and prints WHAT to evict and WHERE on failure. Never satisfy it by deleting a claim or narrowing a rule: history goes -to `tests/parity/README.md` or `tests/conformance/README.md`, which are read on demand and therefore -free. +to `tests/conformance/README.md` or a package README, which are read on demand and therefore free. ## Evidence rules @@ -85,208 +84,88 @@ These are the house style, and they are why the guards here are worth trusting: | path | what | |---|---| -| `cairn` | the PYTHON client CLI and the ORACLE — every verb `cairn -verbs` prints; do not hand-list them here, a hand-list here silently omitted one for a whole phase | -| `lib/` | the Python reader: cache resolution, recall rendering, scope/ref resolution, doctor | -| `server/` | the pod: `server.py`, `Dockerfile`, `seed.sh`, `verify-byte-identity.sh` | -| `cmd/cairn-server`, `internal/api` | the Go port of the server (P1), stdlib-only — see below | -| `cmd/cairn`, `internal/client`, `internal/doctor` | the Go port of the CLIENT (P2), over the SAME `internal/report` the pod uses | +| `cmd/cairn`, `internal/client`, `internal/doctor` | the CLIENT — every verb `cairn -verbs` prints; do not hand-list them here, a hand-list here silently omitted one for a whole phase | +| `cmd/cairn-server`, `internal/api` | the POD — stdlib-only, **DEPLOYED** (`cairn-store-go`) | | `internal/report`, `internal/store` | the ONE renderer and the store loader, shared by pod and CLI | +| `server/` | the pod's OPERATIONS: `seed.sh` and `README.md` | | `cmd/cairn-ui`, `internal/ui` | the BROWSER surface — BROWSE+SEARCH, gomponents, COOKIE SESSIONS, the SHARE FLOW, GitHub sign-in; **DEPLOYED**; 📄 its own README | | `internal/depspolicy` | the ALLOWLIST and import BAN that replaced `vendorHash = null` | | `internal/control` | P3: the ONE authz predicate the pod now authorises from, and `tokenfile/` (the token file, projected); 📄 its own README | | `internal/identity` | P4: the ONE `Authenticator` (🔴 one backend BYPASSES auth on a DIRECTLY-reached pod; never default, refuses to start); 📄 its own README | | `cmd/cairn-capture`, `internal/{capture,transcript,worker,plugins}`, `plugins/` | TRANSCRIPTS + PLUGINS: host capture, worker listener, the plugin API; `plugins/` is a NESTED stdlib-only module; 📄 their READMEs | -| `tests/` | the suites, `leakscan.py`, `conformance/`+`dualrun/` (P1's gates), `parity/` (P2's) | -| `flake.nix` | both clients (**`default` is the GO one; `#cairn` is the Python one**), BOTH pod images, the UI, and the checks | - -## 🔴 TWO SERVERS ARE ALIVE, AND `server/server.py` IS THE ORACLE - -`cmd/cairn-server` is the Go port, and 🔴 **IT IS NOW THE DEPLOYED POD** — the cluster -pulls `cairn-store-go`. It also exists so the conformance corpus can be replayed against -both implementations on one store and the difference MEASURED. ⚠ So the ORACLE now runs -NOWHERE, and a divergence ships before any gate reading `server.py` sees it. - -📄 **P1'S HISTORY LIVES IN `tests/conformance/README.md` AND `tests/dualrun/README.md`, -NOT HERE** — the corpus splits, the runner fixtures, the mutation rounds, the closed -`ErrFocusSelectorUnported` row, the `?page=<21 digits>` example and the byte-identity -story. Records of rounds, read on demand. What is below is what binds the next edit. - -✅ **ALL THREE STEPS ARE DONE, STEP TWO IS `tests/dualrun/`**, and 🔴 **do not declare a -step done early** — a sentence about the CORPUS is satisfied by a green corpus while every -step stands untouched. ⚠ **It reads NEITHER IMAGE, so it licenses an image swap's -PRECONDITION and never the swap** — diff the two images. See `tests/dualrun/README.md`. - -🔴 **AND THE BYTE-IDENTITY GATE IS SCOPED TO THE *UNCOMPRESSED* TAR.** **Do not add a gate on the -gzip bytes, and do not read this row as "nobody looked"** — why gzip identity is unattainable -there, and what an extracted-tree comparison cannot see, are in `server/README.md`. **Byte-diff -the two archives when you change `internal/snapshot/paxtar.go`**: the tree comparison cannot see it. - -**The corpus is the specification, and it is GREEN for both implementations** (the -per-implementation skip counts are in `tests/conformance/README.md`). 🔴 **A GREEN CORPUS IS -THE START OF THE BYTE-IDENTITY QUESTION, NOT THE END OF IT** — it replays a declared list -against a declared world; `tests/dualrun/` is what compares the two servers over a store -nobody wrote a fixture for. +| `tests/` | the Python-run suites, `leakscan.py`, `conformance/` (the HTTP contract gate) | +| `flake.nix` | the client (`default`), the pod image, the UI, and the checks | + +## 🔴 THE PYTHON IMPLEMENTATION IS RETIRED, AND WHAT IT LEFT BEHIND IS FROZEN + +A Python client and a Python pod (the `cairn` script, `lib/`, `server.py`) were the ORACLE the +Go port was measured against, through the parity and dual-run gates. All of it is deleted +(Phase 5 of `claudedocs/plan-cairn-v1-event-log.md`; §6.3 there is the per-item disposition). +🔴 **What it RECORDED is kept as FROZEN CONTRACTS, recorded at `ec1b756`, pinned by digest, and +NEVER re-recorded from Go — that would make a test agree with itself:** the conformance goldens +with no `recorded_from` (`tests/conformance/README.md`), `internal/report/testdata/ +reader_fixtures.json`, `internal/store/testdata/citation_ids.json` and `marker_oracle_sweep.json`. +A Go change that disagrees with one is a CONTRACT change, argued in review. Comments that say +"the oracle does X" describe history; `internal/pytext`'s fixture is NOT frozen (it records the +interpreter, which is still here). ```bash -go vet ./... && go test ./... # the port's own guards -tests/conformance/run_go.sh # the P1 gate: the corpus against the Go server -python3 tests/conformance/suite.py run # …and against the oracle, which must stay 0 failures +go vet ./... && go test ./... # the Go packages' own guards +tests/conformance/run_go.sh # the HTTP contract gate: the corpus against the Go server ``` ⚠ **A GREEN `run_go.sh` AND A GREEN `go test` ARE DIFFERENT CLAIMS, AND NEITHER IMPLIES THE -OTHER.** The corpus measures the SERVED HTTP contract over the bodies `requests.json` -declares; `go test` measures the renderer against the oracle's bytes over shapes the corpus -never sends (see the reader fixture below) and the decoding differences the corpus is -structurally blind to. Read both. - -🔴 **A REFUSAL THAT IS "THE SAME" ON BOTH SERVERS MAY BE THE SAME FOR THE WRONG REASON** — -two responses that both fail their own golden still satisfy a relation BETWEEN them. So **a -relation with NO non-5xx member is a FAILURE**: the bar is **one** real answer and the floor -is **500, not 400**, because a 4xx refusal IS an answer and the uniformity of those refusals -is itself part of the contract, where every 5xx this server emits is uniform *by design*. -Why a printed caveat was rejected instead: `tests/conformance/README.md`. - -🔴 **A GREEN CORPUS IS NOT A GREEN PORT.** **When the corpus is green, the question left is "what -does it not send", and DECODING differences are the answer** — the two defects that shipped green in -the first Go commit, and how they were found, are in `tests/conformance/README.md`. - -🔴 **AND THE RENDERER'S OWN GATE IS A DIFFERENTIAL FIXTURE, BECAUSE THE CORPUS CANNOT SEND -MOST OF WHAT IT RENDERS.** `internal/report/testdata/reader_fixtures.json` holds the -**oracle's own rendered bytes** over a synthetic world, generated by -`tests/reader_fixtures.py` and replayed by `internal/report`'s tests. Three rules bind -anyone touching it: **regenerate and diff** rather than hand-edit (a stale fixture is a -failure, not a weaker comparison); the coverage ledger is keyed on strings only each branch -can produce, so **the covered set cannot shrink**; and it stays in `flake.nix`'s `onlyGo` -filter for the same reason `requests.json` is. - -🔴 **THE RENDERER IS A LIBRARY, NOT A HANDLER, BECAUSE P2 IMPORTS IT.** `internal/report` -holds `Recall`, `Search`, `RecallReport.RenderText`, `SearchReport.RenderText` and -`ExitFor` — plain values in, plain values out, no `net/http` type in any signature, no -server config (the instance is a plain string; `""` is the pod's), and every error -classifiable with `errors.As`/`errors.Is` -(`store.StoreMissingError`, `store.EntryUnreadableError`). `report.Reader` is the thin -`Renderer` the pod hands to `internal/api` and the ONLY type in the package that knows a -server exists. **That shape is no longer a promise about P2: `internal/client` is the second -consumer, and it calls `Recall`/`Search`/`RenderText`/`ExitFor` directly rather than through -`Reader`.** Pod and CLI run ONE renderer, which is what makes byte-identity a property -rather than a discipline. - -⚠ **TWO PLACES THE PORTED READER DELIBERATELY DIFFERS FROM THE ORACLE**, both in -`store.ScopeRevision`, both invisible to the corpus, neither a defect, and named here -because a reader comparing two audit streams has to know they are there: a `.git/HEAD` -that is not valid UTF-8 logs **one** `400` audit line here against **two** (`200` then -`400`) on the oracle; and a `ref:` naming `../…` cannot climb out of the git dir here, -where the oracle's `git / ref` can — a NARROWING, in the safe direction. Why each was -accepted: `tests/conformance/README.md`. - -🔴 **AND ONE DIVERGENCE IS OPEN RATHER THAN DELIBERATE: AN INTEGER QUERY PARAMETER WIDER -THAN `int64`.** `_int_param` is `int(v)`, which is arbitrary precision; `intParam` is -`strconv.Atoi`, which is not — so a 21-digit `?page=` or `?limit=` is answered **200 by the -oracle and 400 by Go**, measured live on both servers over one world. `tests/conformance/` -cannot see it: the runner builds its targets from `requests.json` and no row carries that -shape. ⚠ It is NOT fixed in the same change as the renderer, deliberately. **Closing -condition:** a `requests.json` row carrying a 21-digit `?page=`, regenerated against the -oracle, and `run_go.sh` exiting 0 with it present — which forces whoever lands it to decide -between matching `int()` and declaring the difference in `wire.NORMALIZATIONS`. The check is -mechanical; the decision is not, which is why it is a separate change. - -🔴 **THE GO SIDE CARRIES ITS OWN ROUTE LEDGER, BECAUSE THE SUITE CANNOT BUILD ONE FOR -IT.** `cases.declared_routes` reads the oracle's dispatch tables by AST and has no -equivalent for a compiled binary, so that blind spot is closed on the Go side by -`api.DeclaredRoutes()`, checked against `tests/conformance/requests.json` by -`TestTheRouteLedgerMatchesTheConformanceCorpus`, against the wiring at construction, and -against the ledger's own spelling by `checks.go-server-declares-its-routes` (which reads it -out of the RUNNING binary). Adding a row to a dispatch table is adding a public, -internet-reachable endpoint; all four of those have to move together. - -🔴 **THE GO TOOLCHAIN IS PINNED, NOT INHERITED** — the same discipline as the -interpreter, and for the same reason. `go.mod` says 1.25, `flake.nix` uses -`buildGo125Module` (nixpkgs' default `go` is **1.26** against the pinned lock), and CI -pins `go-version: "1.25"`. Move all three together or not at all. ⚠ `buildGoModule` -with the compiler in `nativeBuildInputs` is a NO-OP for the pin: it uses the `go` from -its own scope, so the build fetched 1.26 while the derivation advertised 1.25. +OTHER.** The corpus measures the SERVED HTTP contract over the bodies `requests.json` declares; +`go test` measures the renderer against the frozen reader fixture over shapes the corpus never +sends, and the decoding cases the corpus is structurally blind to. Read both. + +🔴 **A RELATION WITH NO NON-5xx MEMBER IS A FAILURE** — two responses that both fail their own +golden still satisfy a relation BETWEEN them, so the bar is **one** real answer and the floor is +**500, not 400** (a 4xx refusal IS an answer). Why a printed caveat was rejected: +`tests/conformance/README.md`. + +🔴 **A NEW GOLDEN IS RECORDED FROM GO AND HAND-REVIEWED** — `run_go.sh record ` stamps +`recorded_from: cmd/cairn-server` and refuses to overwrite any golden; a stamped golden is a +CHANGE DETECTOR, and its contract witness is a Go test with a literal expectation. + +🔴 **THE RENDERER IS A LIBRARY, NOT A HANDLER.** `internal/report` holds `Recall`, `Search`, +`RecallReport.RenderText`, `SearchReport.RenderText` and `ExitFor` — plain values in, plain +values out, no `net/http` type in any signature, every error classifiable with +`errors.As`/`errors.Is`. `report.Reader` is the thin `Renderer` the pod hands to +`internal/api`; `internal/client` calls the functions directly. Pod and CLI run ONE renderer, +which is what makes byte-identity between them a property rather than a discipline. + +🔴 **THE ROUTE SET IS A PUBLIC SURFACE AND IT HAS ONE DECLARATION: `api.DeclaredRoutes()`.** It +is checked against `tests/conformance/requests.json` in process +(`TestTheRouteLedgerMatchesTheConformanceCorpus`) and out of the built binary (`suite.py` +refuses to run without `--server-binary`), against the wiring at construction, against the +capability ledger by `tests/test_go_client_ledgers.py`, and against its own spelling by +`checks.go-server-declares-its-routes`. Adding a row to a dispatch table is adding an +internet-reachable endpoint; all of those move together. + +🔴 **THE GO TOOLCHAIN IS PINNED, NOT INHERITED.** `go.mod` says 1.25, `flake.nix` uses +`buildGo125Module` (nixpkgs' default `go` is **1.26** against the pinned lock), and CI pins +`go-version: "1.25"`. Move all three together or not at all. ⚠ `buildGoModule` with the +compiler in `nativeBuildInputs` is a NO-OP for the pin: it uses the `go` from its own scope. 🔴 **THE SERVING PATH IS STILL STDLIB-ONLY — the import BAN measures it, not `vendorHash = null`, which is gone. See the dependency section below.** -## 🔴 TWO CLIENTS ARE ALIVE, `cairn` IS THE ORACLE, AND `tests/parity/` IS THE GATE +## 🔴 THE CLIENT'S LEDGERS ARE READ OUT OF THE RUNNING BINARY -```bash -python3 tests/parity/harness.py # the P2 gate: both clients, one cache root -python3 tests/parity/harness.py --self-test # prove the differ can go RED -python3 tests/parity/harness.py --break-pod # prove the PRE-FLIGHT refuses to vouch -``` - -`cmd/cairn` is the Go client; `internal/report` is the one renderer, reached through -`report.Reader` by the pod and by direct `Recall`/`Search`/`RenderText`/`ExitFor` calls by the CLI. - -🔴 **THE PREMISE, AT THE SCOPE IT ACTUALLY CARRIES.** Rewriting the server alone left **two -renderers in two languages that must agree byte-for-byte forever**, drift arriving as "a different -order that reads as a stale cache" — no error, no missing entry. That entails **deleting the -PYTHON RENDERER**; it does **not** entail a full CLI port. What carries the port is the reason to -state instead: **a single binary, one language, and Python RETIRABLE at P8**. ⚠ And **"one -renderer" is a P8 property, not a P2 one, AND THE DEFAULT FLIP DID NOT MAKE IT ONE** — the Python -renderer still ships as `packages.cairn` until the oracle is deleted, so until then this gate IS -the comparison rather than the absence of one. - -🔴 **THE HEADLINE READS WIDER THAN THE GATE, SO KNOW WHICH ROWS ARE LOAD-BEARING BEFORE -TRUSTING ONE.** "134 cases, 138 PASS, 0 failures, 0 dead normalizations" is NOT 134 byte -diffs: 103 rows compare stdout, stderr AND the exit code; 23 compare the exit code ONLY; 8 -compare the exit code plus "both sides put something on stdout" — so **31 of 134 never -compare output text.** Declared per row; what the corpus covers is in `tests/parity/README.md`. - -🔴 **TWO CLIENTS FAILING IDENTICALLY COMPARE EQUAL** — its first full run reported 72 PASS / 0 -FAIL against a pod that refused every request. Three controls stand against that, they are three -different claims, and each refuses with exit **2** ("could not vouch", never "failed"): -`PREFLIGHT` (the POD answers a non-empty snapshot for this token), `CONTENT-FLOOR` (the CLIENTS -reached a live fetch and a rendered digest), and `--self-test` → `sabotaged=5 caught=5` (the differ -goes red on stdout, on stderr, on the exit code, on `exit+stdout` **and** on the read ledger). `--break-pod` is the -negative control on the first. Read all three; a green without them is a green about nothing. - -📄 **READ ON DEMAND RATHER THAN HERE, all in `tests/parity/README.md`:** the worked example behind -that green, what the gate FOUND (twelve divergences in nine findings), the MUTATION BATTERY over P2, -and the **P8 RETIREMENT LEDGER** — every file, guard and row that exists only while the Python -oracle does. Records of rounds, not decision input before acting. This file states the retirement -condition for the `lib/` rule and for nothing else; the ledger is a list of DECISIONS, not a delete -script. - -🔴 **SEVEN RESIDUALS ARE DECLARED IN `tests/parity/README.md` RATHER THAN NORMALISED AWAY, AND -THE RULING IS THE SAME EVERY TIME: declare it, never mirror it into the oracle.** Two are traps: - -- **the sub-microsecond mtime** is **measured unable to matter** — both sides collapse to the same - `float64`, which is what the index order is decided on, and `cache-mtime-parity` pins the doubles - equal AND the raw delta under one ULP. Do not "fix" it, and do not read it as unmeasured. -- **`cairn -verbs` / `cairn -exit-codes`** exit **0** with a table on stdout on the Go client and - **2** with argparse's `usage:` on the oracle — the Go client *succeeding* where the oracle - refuses, which is the dangerous direction. 🔴 **THAT WIDENING HAS HAPPENED — the default flipped, - so `nix run github:…/cairn -verbs`, refused at exit 2 before, answers 0 for anyone not naming - `#cairn`.** Announced in `README.md`. P8 still owns the DECISION (public surface, or gated), - never the moment. - -🔴 **THE GO CLIENT CARRIES TWO LEDGERS OF ITS OWN, BECAUSE THE PYTHON-SIDE GATES ARE BLIND TO A -COMPILED PROGRAM.** `capability_ledger.cli_verbs_from_parser` asks the PYTHON argparse parser -what subcommands it has; `tests/test_cairn_doctor.py`'s exit-code ledger walks the `cairn` -script's AST. Neither has an equivalent for a binary, so a Go-only verb, a Go client that -silently LOST one, or a Go exit code colliding with `doctor`'s 10 would each leave those gates -green. `cairn -verbs` and `cairn -exit-codes` print the tables the dispatcher and the exit -model are built from, and they are read out of the RUNNING binary in **two tiers**: -`tests/test_go_client_ledgers.py` (the `go` CI job, which REFUSES on a skip — the `tests` job -has no toolchain, and a skip nobody counts is a pass) and -`checks.go-client-declares-its-verbs` (the `nix` job). Same shape as -`api.DeclaredRoutes()`/`cairn-server -routes`, and for the same reason. +`cairn -verbs`, `cairn -exit-codes` and `cairn-server -routes` print the tables the +dispatchers are built from — PUBLIC surface, documented in `README.md`. They are read in +**two tiers**: `tests/test_go_client_ledgers.py` (the `go` CI job, which REFUSES on a skip — +the `tests` job has no toolchain, and a skip nobody counts is a pass), against +`testlib/capability_ledger.LEDGER`; and `checks.go-*-declares-its-*` (the `nix` job), against +hand lists `tests/test_capability_ledger.py` pins to the same ledger. 🔴 **THE EXIT-CODE MODEL IS A PRINTED CONTRACT AND THE `{0, 9}` OVERLAP IS DELIBERATE.** Read outcomes `0`/`3`/`4`/`5`, writes `6`/`7`/`8`/`9`, usage `2` — a third bucket, not a read — and -`doctor`'s own `0`/`9`/`10`. Both clients declare identical values, asserted from BOTH -discovered operand sets. Do not renumber the 9 to make it unique: it is unambiguous at every +`doctor`'s own `0`/`9`/`10`. Do not renumber the 9 to make it unique: it is unambiguous at every call site (`doctor` never creates an entry, `create` never runs diagnostics), and renumbering changes a contract the command PRINTS to remove a collision that was never a defect. -⚠ **THE GATE HAS A NAMED BLIND SET — concurrency, real network failures, a narrowed -credential, unreached `doctor` states, and multi-instance worlds beyond two.** It is enumerated -in `tests/parity/README.md` and NOT transcribed here: a copy of it went stale the first time the -list grew. - ## 🔴 A THIRD-PARTY DEPENDENCY EXISTS NOW, AND `vendorHash = null` IS GONE The refusal is `internal/depspolicy`: an allowlist failing on GROW *or* SHRINK, plus an @@ -324,120 +203,56 @@ session store's mechanics, and the two operator requirements that chose it). ## 🔴 SEVERAL INSTANCES: AN UNROUTED SCOPE REFUSES -Binding rules: **`lib/README.md`**. Read it before editing any routing path. +Binding rules: **`internal/client/ROUTING.md`**. Read it before editing any routing path. ## Installing and building with nix ```bash -nix run github:ZacxDev/cairn -- doctor # the DEFAULT client — the GO one — uninstalled -nix build github:ZacxDev/cairn#cairn # the PYTHON client and the oracle — NOT the default -nix build github:ZacxDev/cairn#cairn-go # the Go client by name — same store path as default -nix build github:ZacxDev/cairn#server-image # the PYTHON pod image, as a loadable tarball -nix build github:ZacxDev/cairn#server-image-go # the GO pod image — published, and DEPLOYED +nix run github:ZacxDev/cairn -- doctor # the client, uninstalled +nix build github:ZacxDev/cairn#cairn-go # the client by name — same store path as default +nix build github:ZacxDev/cairn#server-image-go # the pod image — published, and DEPLOYED ``` -Consumers pin this flake as an input; that is the supported way to get a `cairn` -whose version cannot disagree with the code in it, because **the version is the -git revision** and is never written down by hand. - -🔴 **EVERY CLAIM BELOW SAYS WHICH CLIENT IT IS ABOUT.** `cairn` (`packages.cairn`) is -the Python client and the ORACLE; `cmd/cairn` (`packages.cairn-go`, and now -`packages.default`/`apps.default` too) is the Go port. **The Python client, its `lib/` -and its packaging are not deleted here** — P8 retires Python, and the parity gate stays -the comparison until it does. 🔴 **THE DEFAULT FLIPPED ON AN OPERATOR DECISION, NOT ON A -GREEN GATE** — the record is `tests/parity/README.md` residual 7. - -🔴 **`lib/` MUST STAY BESIDE THE *PYTHON* CLIENT SCRIPT, AND `packages.cairn` IS -BUILT THAT WAY ON PURPOSE.** `cairn` finds its modules with -`Path(__file__).resolve().parent / "lib"`. `.resolve()` follows symlinks, so -what matters is the directory holding the REAL file — the package therefore -installs the script and `lib/` together under `libexec` and puts a wrapper in -`bin/`. Do not "simplify" this by exporting `PYTHONPATH`: that makes the modules -reachable by a second mechanism which shadows the first, leaving the file's own -stated one dead and the next layout change silently broken. -`packages.cairn` fails its own install check if the client cannot import its -own `lib/`, so a broken client cannot be built at all — and that check is what -catches a missing `lib/`, because the imports are at module scope and `--help` -therefore dies too. `checks.client-resolves-its-lib` earns its place on the -other side: it runs a real subcommand to completion against a real cache root, -which is behaviour the install check does not exercise. - -🔴 **NONE OF THAT PARAGRAPH APPLIES TO THE GO CLIENT, AND SAYING SO IS THE POINT -RATHER THAN LEAVING IT TO BE INFERRED.** A single binary has no sibling module -directory, so neither hazard the paragraph above exists for can arise there. -What `packages.cairn-go` has instead is a `gitMinimal` on its wrapper's `PATH`, -for exactly the reason `packages.cairn` has one: -`internal/client/reposcope.go` invokes `git` by BARE NAME to derive a repo's -scope, so a package that did not carry its own answer would make `cairn recall` -with no `--scope` fail differently on two machines. -⚠ **Do not read the `lib/` rule as retired.** It governs the client that is -still shipped and still the oracle; it stops governing anything on the day -`packages.cairn` does, which is P8. - -⚠ **A NIX SANDBOX PINS DIMENSIONS — ASK WHAT YOURS CANNOT HAVE BEFORE READING ITS -GREEN AS COVERAGE.** `checks.client-resolves-its-lib` has no cache root in its -HOME and therefore missed a crash on every host that HAD one; **every -`*-declares-its-*` check** has no store, token, network or cache-root HOME -either, so each exercises a LEDGER and nothing about behaviour. The worked -example, and why the parity harness is what measures behaviour instead, are in -`tests/parity/README.md`. - -🔴 **TWO WAYS TO BUILD THE *PYTHON* POD, THEY MUST NOT DIVERGE — AND ⚠ NEITHER IS -DEPLOYED** (the retraction, and the module-set detail, are in `server/README.md`). -`packages.server-image` is a second way to produce that pod, **not** a build of -`server/Dockerfile`. The runtime contract — env, port, uid, entrypoint — is -written in both, so `tests/test_flake_image_matches_dockerfile.py` pins them -against each other. Change one, change the other, in the same commit. 🔴 **AND -THAT FILE IS TWO GUARDS, ONLY ONE OF WHOSE PREMISES DIED — it also pins -`cmd/cairn-server/main.go`'s defaults against what a Deployment assumes, which is -the GO pod. That half is LIVE. P8 must SPLIT it, never delete it.** - -🔴 **AND THE AGREEMENT TEST IS NARROWER THAN "THE TWO IMAGES ARE THE SAME" — -KNOW WHAT IT DOES NOT SEE.** It pins env, uid, port and entrypoint, and it is -structurally blind to LAYER CONTENTS. That blindness has already shipped an -image that started, passed health checks and served while every documented -operation against it failed — the worked example is beside the guard that closed -it, in `tests/test_flake_go_image_runtime_contract.py`. So: **before swapping -the deployed image, diff the two for what the test cannot read.** - -📄 **THE MEASURED DIFFERENCES ARE IN `server/README.md`, NOT HERE** — the layer -table, the busybox applet surface (network **servers** and **clients**, including -`ssl_client`, beside a mounted credential), the setuid counts, and why that trade -is RECORDED RATHER THAN FIXED. 🔴 **THIS -SENTENCE CARRIES NO COUNT AND THE DELETION IS THE POINT — four drafts gave one -and all four undercounted. The set is whatever `busybox --list` on the built -image says; read it there, and do not supply a fifth number here.** Neither -image's tool surface is a subset of the other's, and nothing about it is settled. - -🔴 **AND THERE IS A THIRD IMAGE: `packages.server-image-go`, WHICH IS A THIRD -BUILD AND NOT A THIRD STATEMENT OF THE CONTRACT.** It wraps `cmd/cairn-server` -and DERIVES uid, port, exposed port and env from the same -`serverUid`/`serverPort`/`serverEnv` bindings the pin above reads, minus a named -`serverEnvPythonOnly` set. A COPY is the hazard; a subtraction is what makes a -variable added for one pod reach both. -`tests/test_flake_go_image_runtime_contract.py` pins that it stays derived, that -it carries busybox and a `PATH`, and that its CA bundle is NAMED rather than -merely present. 🔴 **IT IS PUBLISHED AND IT IS NOW THE DEPLOYED POD — THE -CUTOVER HAPPENED.** `.github/workflows/publish-image.yml` pushes BOTH pods, to -two ghcr packages (`cairn-store`, `cairn-store-go`) under one `sha-<40-hex>` -scheme, and the cluster pulls the second. ⚠ Both are -PUBLIC and anonymously pullable, verified against a negative control; the -retracted prediction about that is in `server/README.md`. - -🔴 **THE INTERPRETER IS PINNED, NOT INHERITED.** `flake.nix` uses -`pkgs.python312` because `server/Dockerfile` is `python:3.12-slim` and CI pins -`python-version: "3.12"`. Move all three together or not at all (📄 `server/README.md`). +Consumers pin this flake as an input; **the version is the git revision** and is never written +down by hand. ⚠ There is no `#cairn` attribute any more — it was the retired Python client. + +🔴 `packages.cairn-go` carries `gitMinimal` on its wrapper's `PATH`: +`internal/client/reposcope.go` invokes `git` by BARE NAME to derive a repo's scope, so a package +that did not carry its own answer would make `cairn recall` with no `--scope` fail differently on +two machines. + +⚠ **A NIX SANDBOX PINS DIMENSIONS — ASK WHAT YOURS CANNOT HAVE BEFORE READING ITS GREEN AS +COVERAGE.** Every `*-declares-its-*` check has no store, token, network or cache-root HOME, so +each exercises a LEDGER and nothing about behaviour. + +🔴 **THE POD IMAGE STATES NO CONTRACT OF ITS OWN.** `packages.server-image-go` DERIVES uid, port, +exposed port and env from `serverUid`/`serverPort`/`serverEnv`; a COPY is the hazard. +`tests/test_flake_go_image_runtime_contract.py` pins that it stays derived, that it carries +busybox and a `PATH` (`kubectl exec … tar` seeding and `kill -HUP 1` revocation need them), and +that its CA bundle is NAMED; `tests/test_server_deployment_defaults.py` pins the server's code +defaults against what a Deployment assumes, and the image env's absence of every name the rename +resolver reads. 🔴 **BOTH ARE STRUCTURAL CHECKS ON SOURCE AND BLIND TO LAYER CONTENTS** — that +blindness once shipped an image that started, passed health checks and served while every +documented operation against it failed. **Before swapping the deployed image, diff it for what +the tests cannot read.** The measured layer table and busybox applet surface are in +`server/README.md`; 🔴 **NO COUNT OF THE APPLET SET IS GIVEN HERE — four drafts gave one and all +four undercounted. Read it off `busybox --list` on the built image.** + +🔴 **THE INTERPRETER IS PINNED, NOT INHERITED.** `flake.nix` uses `pkgs.python312` (the devShell +and the Python-driven checks) and CI pins `python-version: "3.12"`. Move both together. ## Naming The project is **cairn**. 🔴 **THE ENVIRONMENT VARIABLES ARE RENAMED AND BOTH SPELLINGS WORK.** `CAIRN_*` is the name; every `SUBSYSTEM_STORE_*` still resolves, the new name WINS, -and an old name that is present warns **once per process naming its replacement** — sorted by -new name, because `tests/parity/` diffs the two clients' stderr byte-for-byte. It stops being -read when **`packages.cairn` is retired (P8)**: a milestone, never a date. The ledger, the -resolver and the warning text are `internal/envalias` and `lib/env_aliases.py` — two spellings -only because `packages.cairn` cannot import `internal/`, pinned against each other by -`tests/test_env_aliases.py`. **Never open-code a fallback at a call site.** +and an old name that is present warns **once per process naming its replacement**. The ledger, +the resolver and the warning text are `internal/envalias` — ONE spelling since the Python +client's twin was deleted — pinned against literals by `tests/test_env_aliases.py`. **Never +open-code a fallback at a call site.** 🔴 **THE OLD ANCHOR IS MET AND THE ALIASES STILL WORK, BY +DECISION:** they were to stop being read when `packages.cairn` was retired; that happened, and +removing them is a BREAKING change for every deployment still exporting an old name, so it is +its own change, announced in `CHANGELOG.md`. The warning now names that announcement as the +window; `internal/envalias`'s package doc states the next step. 🔴 **THE LEDGER IS ARBITRARY `(new, old)` PAIRS, NOT A PREFIX RULE, AND IT CARRIES TWO RENAMES.** The second is `CAIRN_SUPABASE_*` → `CAIRN_OIDC_*` over the JWT verifier's seven @@ -447,18 +262,17 @@ LEDGER, NEVER INFER A PAIR FROM A RULE** — the per-pair reasoning and the spel deliberately NOT paired (a GoTrue redirect URL; two RETIRED secrets, where a pair would turn a startup refusal into a working alias) are in `internal/envalias/envalias.go`'s package doc. -Other identifiers still read `subsystem_store` — the `lib/` module names, -`~/.config/subsystem-store/`, `/run/secrets/subsystem-store/`, the `subsystem-recall` CLI -alias. Those are **accepted aliases**, kept so existing deployments do not need a coordinated +Other identifiers still read `subsystem_store` — `~/.config/subsystem-store/`, +`/run/secrets/subsystem-store/`, the report banner's `subsystem-recall:` prefix. Those are **accepted aliases**, kept so existing deployments do not need a coordinated cutover; do not mass-rename them away without a migration path for people already running this. ## 🔴 CI runs on CI, not on this workstation -`.github/workflows/ci.yml` (leakscan, changes, tests, go, mutants, parity, dualrun, -nix, uiaudit, pgtest) is where a change is validated. Do **not** run the whole local +`.github/workflows/ci.yml` (leakscan, changes, tests, go, mutants, nix, uiaudit, pgtest) +is where a change is validated. Do **not** run the whole local mirror to "reproduce CI" — the box is shared by every agent and the operator's desktop, and a whole-suite run spins the disks and slows both. Whole-suite invocations are refused by the local agent tooling. **A change-scoped subset is the local loop** — `python3 tests/leakscan.py --self-test`, -one harness directly (`tests/control_mutants.py`, `tests/parity/harness.py`), or one +one harness directly (`tests/control_mutants.py`, `tests/conformance/run_go.sh`), or one test module. The full suite is CI's. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ee341cb..7068c4a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,8 @@ rounds of review found the opposite shape here and both were right. A change's reads; its *record* — the drafts retracted, the gate that did not license it, the precondition that closed first — belongs beside the thing it governs. When `0587ace` evicted that record from `AGENTS.md` its message said -`tests/parity/README.md` residual 7 already held every clause, so "no second -copy of the record now exists to keep true". Restating either one here would +`tests/parity/README.md` (since deleted with the Python oracle) residual 7 already held every +clause, so "no second copy of the record now exists to keep true". Restating either one here would recreate exactly that. 🔴 **Entries are anchored to a PR and a commit sha, never to a date.** A date @@ -29,6 +29,7 @@ claim to cover them; `git log` and the PR history are the record for those. | change | anchor | what you may have to do | why it was taken | |---|---|---|---| +| **The Python client and pod are retired: `packages.cairn`, `apps.cairn` and `packages.server-image` are gone, and the `cairn-store` ghcr package gets no new tags.** The Go client (`default`/`cairn-go`) and the Go pod (`server-image-go` → `cairn-store-go`) are unchanged. `cairn -verbs`/`-exit-codes` are documented public surface. The `SUBSYSTEM_STORE_*`/`CAIRN_SUPABASE_*` aliases still work; their deprecation warning now names a CHANGELOG-announced removal instead of this retirement. | [#327](https://github.com/ZacxDev/cairn/pull/327) → `` | replace `#cairn` / `cairn.packages.${system}.cairn` with `default`; nothing else — § [*The Python client and pod are retired*](README.md#the-python-client-and-pod-are-retired--there-is-no-cairn-any-more) | Phase 5 of `claudedocs/plan-cairn-v1-event-log.md`: every curated-layer change would otherwise be written twice; §6.3 records each retired item's disposition | | **Versioned JSON output: `cairn recall --json`, `cairn routes --json`, and new verbs `cairn associate --scope S --paths-from F` (`--json`, `--min-paths N`), `cairn refs` (ref collisions, by the reader's resolver; `--all-scopes` exits 11 on a cached scope with no route and prints a PARTIAL answer at 3 when an instance's cache is unreadable), `cairn parse --file F --json` (the reader's parse of an entry or a bullet body) and `cairn fold --file F --json` (the reader's ref fold of a JSON array of strings); `cairn validate --file F [--ref R]` checks one draft offline with the body predicate `create`/`put` apply and the store's 1 MiB body cap (with `--ref`, under the filename `create --ref R` would use).** Shapes carry `schema: 1` and are documented in `README.md` → *Machine-readable output*. | PR → `` | Nothing; every existing invocation prints what it did. A consumer parsing the new documents should refuse a `schema` it does not know. | The Python client's last consumers parsed its in-process report objects; these give the Go client the same answers as a stable contract, so the Python client can be retired (v1 plan Phase 5). | | **`cairn log list\|search` cover the CURRENT REPO's records by default, PER RECORD** — a search keeps the hits whose own record ran in a worktree of the repo `--repo` names (default: the working directory); a list, the sessions with any record there (showing that directory and its first prompt). New **`--all-repos`** widens to every record; `--cwd PREFIX` replaces the default and is now per record too; the two together, or neither outside a git repo, are exit 2. stderr names what was covered (`cairn: sessions=…`). The scoped request is a NEW `POST /client/v1/log/{list,search}` with a `cwd_under` form. **Index migration 5** adds `transcript_units.cwd` and `transcript_session_cwds` and zeroes every index cursor. `log query` is unchanged and unscoped | [#329](https://github.com/ZacxDev/cairn/pull/329) → `` | ⚠ **Deploy `cairn-ui` first**: migration 5 runs on start and the backfill re-reads every stream in place (rate-limited; scoped results grow as it goes, `--all-repos` is unaffected); then pin the client. An older listener answers the scoped POST 405, which exits 3 with nothing printed. ⚠ **A script that searched every repo** must add `--all-repos`; one run outside a git repo must add `--all-repos` or `--cwd`; one using `--cwd` now gets per-record hits. [`README.md`](README.md) § *`cairn log` covers the current repo* | `--repo` only picked the instance, and the index kept ONE cwd per session (its first), so a search printed other repos' (and clients') records into the caller's own captured transcript: [`internal/client/log.go`](internal/client/log.go)'s header | | **`cairn-capture` no longer HOLDS a session for a scope the routing table does not name** (on a host with more than one instance): it ships to the DEFAULT instance OWNER-ONLY (`*` declared), as a `*` session does. A session already bound to the DEFAULT instance is no longer withdrawn for it; one bound to ANOTHER instance is withdrawn from there and re-shipped whole to the default, owner-only — the `*` path (before, it was withdrawn and HELD). A scope the table EXPLICITLY routes to an instance this host does not configure is still held — the only routing hold left — and its `held_reason` now says so (`scope X is routed by the table to instance Y, which this host does not configure`). New mode **`--reevaluate-held [-apply]`** recovers the holds the old rule made | [#330](https://github.com/ZacxDev/cairn/pull/330) → `` | ⚠ **Sessions previously held stay held** until you run `--reevaluate-held` (read-only listing), then, with `-host`/`-worker`/`-capture-token-file`, `-apply`: it clears only holds whose destination answered the position probe; a 410 is listed `needs-server-restore` and left held — restore it by the server journal. The `routed back to …, which deleted this session's transcript` holds are never touched. ⚠ **If you match `held_reason` text**, the unconfigured-alias hold's wording changed. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *`--reevaluate-held`* | `scopeuse` reads header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a scope read, so a fixture name in a grep result held — and withdrew — whole sessions: measured on a two-instance host, 15 held this way, 14 on fixture names. An unnamed scope is a claim about no instance, so there is no leak to stop: [`internal/capture/route.go`](internal/capture/route.go)'s `Decide` | diff --git a/README.md b/README.md index 657456b6..ae46c8de 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ to write to concurrently, this is what it does. | piece | what it is | documented in | |---|---|---| | **the store** — `cairn-server` | scoped markdown entries over HTTP: per-token scope allowlists, attributed appends, `If-Match` replaces, and a snapshot route each host syncs a **read-through cache** from | [*The server*](#the-server); [`server/README.md`](server/README.md) | -| **the client** — `cairn` | one Go binary: sync, recall, search, attributed writes, diagnostics. A Python client (`#cairn`) still ships as the **oracle** the Go one is diffed against | [*The client*](#the-client--cairn) | +| **the client** — `cairn` | one Go binary: sync, recall, search, attributed writes, diagnostics | [*The client*](#the-client--cairn) | | **scope memos** | short notices an agent sends to a scope, which every agent session on that scope sees once, fenced as untrusted data | [*Scope memos*](#scope-memos--messages-between-agent-sessions) | | **the browser surface** — `cairn-ui` | browse and search entries, sign in (credential form, or GitHub through the operator's GoTrue), share scopes, team links, the memos tab, sessions and arcs | [*The browser surface*](#the-browser-surface--cairn-ui); [`internal/ui/README.md`](internal/ui/README.md) | | **transcripts** — `cairn-capture` | opt-in, redacted capture of agent session transcripts, uploaded to `cairn-ui` and read there or with `cairn transcript`; unarmed until the operator arms it | [*Transcripts, capture and plugins*](#transcripts-capture-and-plugins) | @@ -29,7 +29,7 @@ to write to concurrently, this is what it does. ⚠ **"One binary" is true per role, not for the project.** The flake packages six Go programs — `cairn`, `cairn-server`, `cairn-ui`, `cairn-capture`, and the two example plugins -`cairn-summary` and `cairn-clickup` — plus the Python oracle client and pod. An agent host +`cairn-summary` and `cairn-clickup`. An agent host needs only `cairn` (and `cairn-capture` if it uploads transcripts). ## Why a swarm needs more than a shared file @@ -44,8 +44,8 @@ bucket, a git repo or an NFS mount: is still shared, and it is the reason this is not tenant isolation:** `X-Store-Snapshot` and the freshness line that opens every body carry a **store-wide** `entry-files=` count, over scopes the caller cannot name. Two - parties on one pod can each watch the other's count move. Stated in - `server/server.py`, and repeated here rather than left to be found. + parties on one pod can each watch the other's count move. Stated beside the + snapshot handler in `internal/api`, and repeated here rather than left to be found. - **Attributed — a record of who wrote what, not a security boundary.** `cairn append` requires `--session` (no default, no env fallback) and renders `- YYYY-MM-DD: [cairn: /]`, so a swarm's memory @@ -61,7 +61,7 @@ bucket, a git repo or an NFS mount: enumerate them), so they are not secrets either; - `put` and `create` write your bytes **verbatim**, trailer included, and the server does not check it. Enforcing that was considered and declined - (`server/server.py`). + (`internal/write`). 🔴 **And there is no append-only credential to close the gap with.** The verb set is closed at three — `read`, `write`, `admin` — with `append` deliberately @@ -126,11 +126,9 @@ supervising process. ## Installing and building with nix ```bash -nix run github:ZacxDev/cairn -- doctor # the default client — the GO one — uninstalled -nix build github:ZacxDev/cairn#cairn-go # the Go client, by name -nix build github:ZacxDev/cairn#cairn # the PYTHON client — the oracle, not the default -nix build github:ZacxDev/cairn#server-image # the PYTHON pod image — built, published, NOT deployed -nix build github:ZacxDev/cairn#server-image-go # the GO pod image — this is what the cluster runs +nix run github:ZacxDev/cairn -- doctor # the client, uninstalled +nix build github:ZacxDev/cairn#cairn-go # the client, by name +nix build github:ZacxDev/cairn#server-image-go # the pod image — this is what the cluster runs nix build github:ZacxDev/cairn#cairn-ui # the BROWSER surface — published, and DEPLOYED ``` @@ -140,7 +138,7 @@ in it. Moving a pin forward? [*Upgrading from an older pin*](#upgrading-from-an- holds every migration notice, and [`CHANGELOG.md`](CHANGELOG.md) indexes each contract change by PR and sha: -- the default client became the **Go** one — § [*The default client is now the Go one*](#the-default-client-is-now-the-go-one); +- the default client became the **Go** one, and the Python client and pod were later retired — § [*The Python client and pod are retired*](#the-python-client-and-pod-are-retired--there-is-no-cairn-any-more); - the environment variables were renamed to **`CAIRN_*`**, and both spellings work — § [*The environment variables are now `CAIRN_*`*](#the-environment-variables-are-now-cairn_); - `tags:` stopped being an ignored front-matter key — § [*`tags:` is no longer an ignored key*](#tags-is-no-longer-an-ignored-key). @@ -206,14 +204,15 @@ bullet go" is a question about a durable record, asked later, by someone who no longer has the terminal — and a table entry naming an alias this host has no config for still refuses. ⚠ **If you parse `cairn: appended scope=… ref=…` positionally, that field is new — it sits between the status and `scope=`.** The binding rules for -anyone editing a routing path are in [`lib/README.md`](lib/README.md). +anyone editing a routing path are in [`internal/client/ROUTING.md`](internal/client/ROUTING.md). ## The client — `cairn` `cairn -h` prints this list from the dispatcher, and `cairn -verbs` prints it as a -` reads|writes` ledger; **read it there rather than trusting a copy**. The -Python oracle (`#cairn`) has the first ten rows; every verb marked *Go* exists only on -the Go client. +` reads|writes` ledger; **read it there rather than trusting a copy**. (A verb +marked *Go* was added after the retired Python client stopped being extended.) +`cairn -verbs` and `cairn -exit-codes` are PUBLIC surface: each exits `0` with its table on +stdout, and `tests/test_go_client_ledgers.py` reads both out of the running binary. | verb | what it does | | |---|---|---| @@ -1006,7 +1005,7 @@ read's bytes; `--list` is unchanged) has no home beside the code, so it stays th - Not every bullet-ish line carries an id. Prose, blanks, an *indented* dash (a continuation), a dash inside a code fence and text before a section's first bullet print in full with **no** token — **a missing id is never evidence that a bullet was not printed.** -- **Echoing a recalled bullet VERBATIM into a write** is safe: both pods strip a TRAILING token +- **Echoing a recalled bullet VERBATIM into a write** is safe: the pod strips a TRAILING token before hashing, so it still answers `duplicate`. The token counts against the 2,000-character cap. - 🔴 **A token quoted INSIDE new prose is PERMANENT**, and a line can then carry two: @@ -1185,11 +1184,8 @@ its `test.sh`. [`charts/cairn/README.md`](charts/cairn/README.md). | path | what | |---|---| -| `cairn` | the Python client CLI, and the ORACLE the Go one is measured against | -| `lib/` | the Python reader: cache resolution, recall rendering, scope/ref resolution, doctor | -| `server/` | the ORACLE pod: `server.py`, `Dockerfile`, `seed.sh`, `verify-byte-identity.sh` — no longer what runs | -| `cmd/cairn-server`, `internal/api` | the Go port of the server — passes the corpus, and **the deployed pod** | -| `cmd/cairn`, `internal/client` | the Go port of the CLIENT, and **the default** — diffed against the Python one by `tests/parity/` | +| `cmd/cairn-server`, `internal/api` | the server — passes the corpus, and **the deployed pod** | +| `cmd/cairn`, `internal/client` | the CLIENT, and **the default** | | `internal/report`, `internal/store` | the ONE renderer and the store loader, shared by the pod and the CLI | | `internal/control`, `internal/identity` | the control plane's model and authz predicate; the one `Authenticator` | | `cmd/cairn-ui`, `internal/ui` | the BROWSER surface — published, and **DEPLOYED** | @@ -1198,47 +1194,41 @@ its `test.sh`. [`charts/cairn/README.md`](charts/cairn/README.md). | `plugins/` | the example plugins — a nested, stdlib-only module | | `charts/cairn` | the Helm chart | | `internal/depspolicy` | the allowlist and import ban that keep the serving path stdlib-only | -| `tests/` | the suites, plus `leakscan.py`, the HTTP conformance corpus, the server dual-run gate and the client parity gate | -| `flake.nix` | both clients (`default` is the **Go** one, `#cairn` the Python one), the pod images, the UI, and the checks | - -## How the agreement is measured, and why two of everything is alive - -`server/server.py` is the **oracle**; `cmd/cairn-server` is a stdlib-only Go port of -it, **and it is what the cluster runs**. Rewriting the server alone would have left two -renderers in two languages that must agree byte-for-byte forever, with drift arriving as "a -different order that reads as a stale cache" — no error, no missing entry. So both land on -the same `internal/report`: one renderer, two consumers — the pod and the CLI. ⚠ **The -browser surface is not one of them.** `internal/ui` reads `internal/store` and renders HTML -through its own code, so the page is a *second* renderer producing a different medium, and -nothing compares the two. ⚠ And one-renderer becomes a *property* only when the Python -renderer is deleted at P8; until then it is a discipline, and these three instruments -enforce it: - -| instrument | what it compares | read it | +| `server/` | operating the pod: `seed.sh` and its runbook | +| `tests/` | the Python-run suites, plus `leakscan.py` and the HTTP conformance corpus | +| `flake.nix` | the client (`default`), the pod and UI images, and the checks | + +## How the contract is measured + +The server and client were ported from a Python implementation that served as the ORACLE until +it was retired (Phase 5 of [`claudedocs/plan-cairn-v1-event-log.md`](claudedocs/plan-cairn-v1-event-log.md); +§6.3 there is the item-by-item record). Pod and CLI land on the same `internal/report`: one +renderer, two consumers. ⚠ **The browser surface is not one of them.** `internal/ui` reads +`internal/store` and renders HTML through its own code, so the page is a *second* renderer +producing a different medium, and nothing compares the two. + +What the oracle RECORDED outlives it as FROZEN contracts — recorded at the last commit that had +it, pinned by digest, never re-recorded from Go: + +| instrument | what it pins | read it | |---|---|---| -| [`tests/conformance/`](tests/conformance/README.md) | the served HTTP contract, as golden fixtures generated from the oracle, replayed against either server | the corpus and its declared blind spots | -| [`tests/dualrun/`](tests/dualrun/README.md) | both servers over **one** store — every route, scope, entry and principal, and the snapshot's **uncompressed** tar byte for byte | why gzip identity is unattainable, and the PAX-header divergences a tree comparison cannot see | -| [`tests/parity/`](tests/parity/README.md) | both **clients**, one pod, one cache root, identical argv, across every verb they share | the declared residuals, the P8 retirement ledger, and **which rows compare only the exit code** | - -⚠ **Counts are deliberately not quoted here.** Every one of them went stale in this -file at least once while the gates moved; the numbers live beside the gates that produce -them, and the CI floors in [`.github/workflows/ci.yml`](.github/workflows/ci.yml). -⚠ **And a green gate is not evidence until its controls have been watched to work.** The -parity gate's first full run reported 72 PASS / 0 FAIL while every request was refused — -two clients failing identically compare equal. Both harnesses now refuse to vouch (exit -**2**, which is not "failed") unless a pre-flight succeeds, and both ship a `--self-test` -that proves the differ can go red. +| [`tests/conformance/`](tests/conformance/README.md) | the served HTTP contract: golden fixtures replayed against the Go server — frozen at the oracle's answers, plus Go-recorded goldens for routes added later | the corpus, the freeze, and its declared blind spots | +| `internal/report/testdata/reader_fixtures.json` | the renderer's bytes over shapes the HTTP corpus cannot send | `internal/report/reader_fixtures_test.go` | +| `internal/store/testdata/citation_ids.json` | the citation-id derivation, so every id ever printed keeps resolving | `internal/store/citationid_test.go` | + +⚠ **Counts are deliberately not quoted here.** Every one of them went stale in this file at +least once while the gates moved; the numbers live beside the gates that produce them, and the +CI floors in [`.github/workflows/ci.yml`](.github/workflows/ci.yml). ⚠ **And a green gate is not +evidence until its controls have been watched to work** — CI runs the conformance replay against +a deliberately broken golden too, and requires exactly that case to fail. ## Development ```bash -pytest tests/ # the Python suite -go vet ./... && go test ./... # the Go port's own guards +pytest tests/.py # one Python-run suite (the whole suite is CI's) +go test ./internal// # one package's guards tests/conformance/run_go.sh # the corpus against the Go server -python3 tests/conformance/suite.py run # …and against the oracle: must stay at 0 failures -python3 tests/parity/harness.py # both CLIENTS over one cache root: the P2 gate -python3 tests/parity/harness.py --self-test # prove the differ can go RED -python3 tests/reader_fixtures.py generate # re-record the renderer's bytes FROM the oracle +tests/conformance/run_go.sh record # record a NEW row's golden from Go — then review it python3 tests/leakscan.py # the leak gate — runs in CI on every commit python3 tests/leakscan.py --self-test # prove the gate is an instrument ``` @@ -1261,32 +1251,31 @@ security boundary. ### Changing the tag vocabulary -**Widening or narrowing the set is a change in SIX files — two declarations and four -expectations — and the count is measured rather than counted by eye**, by adding a fourth term -to both declarations and reading what went red: +**Widening or narrowing the set is a change in FIVE files — one declaration and four +expectations — and the count was measured rather than counted by eye**, by adding a fourth term +to the declaration and reading what went red (it was SIX while the retired Python oracle carried +a second declaration): | # | file | what is in it | which gate reds | |---|---|---|---| | 1 | `internal/write/tagvocab.go` | `tagVocabulary` — the **deployed** Go pod's declaration | — (this is the change) | -| 2 | `lib/entry_shape.py` | `TAG_VOCABULARY` — the Python oracle's | — (this is the change) | -| 3 | `internal/write/tagvocab_test.go` | **two** literals: the refusal sentence and the term list | `go test ./internal/write/` | -| 4 | `internal/api/tagvocab_test.go` | the 422 body as served, including its `unprocessable: ` prefix | `go test ./internal/api/` | -| 5 | `tests/test_tag_vocabulary.py` | **two** literals: `DECLARED` and `DECLARED_REFUSAL` | `pytest` | -| 6 | `tests/conformance/golden/put-*-tag-*-the-vocabulary.json` | the recorded refusal bytes — regenerate with `python3 tests/conformance/suite.py generate`, never hand-edit | `tests/conformance/run_go.sh`, `python3 tests/conformance/suite.py run`, and `pytest tests/test_conformance_suite.py` | +| 2 | `internal/write/tagvocab_test.go` | **two** literals: the refusal sentence and the term list | `go test ./internal/write/` | +| 3 | `internal/api/tagvocab_test.go` | the 422 body as served, including its `unprocessable: ` prefix | `go test ./internal/api/` | +| 4 | `tests/test_tag_vocabulary.py` | **two** literals: `DECLARED` and `DECLARED_REFUSAL` | `pytest` | +| 5 | `tests/conformance/golden/put-*-tag-*-the-vocabulary.json` | the recorded refusal bytes — FROZEN goldens: a vocabulary change is a contract change that has to be argued against them in review, never re-recorded | `tests/conformance/run_go.sh` | Every one is a literal on purpose — a test deriving its expectation from the declaration would assert `x == x` and stay green through exactly this edit. ⚠ **Two more files carry the terms as PROSE, which no gate covers**: this README's § [*Tags*](#tags) and `CHANGELOG.md`'s #160 row. Edit them in the same commit. ⚠ An earlier draft of this count said "four places" — wrong in the -direction that makes the change look cheap, the same mistake `lib/entry_shape.py` records about -its own sentence. Re-derive rather than trust: add a term to both declarations, then run -`go test ./... ; python3 -m pytest tests -q`. +direction that makes the change look cheap. Re-derive rather than trust: add a term to the +declaration and read what goes red in CI. ## Naming The project is **cairn**. Identifiers that are not environment variables still read -`subsystem_store` — the `lib/` module names, `~/.config/subsystem-store/`, -`/run/secrets/subsystem-store/`, the `subsystem-recall` CLI alias. Those are accepted +`subsystem_store` — `~/.config/subsystem-store/`, `/run/secrets/subsystem-store/`, the +report banner's `subsystem-recall:` prefix. Those are accepted aliases, kept so existing deployments don't need a coordinated cutover. The environment variables have been renamed; see § [*The environment variables are now `CAIRN_*`*](#the-environment-variables-are-now-cairn_). @@ -1298,43 +1287,20 @@ revision is the reader who needs them and a reader setting up fresh does not. Ea break and what to do; [`CHANGELOG.md`](CHANGELOG.md) is the index — one row per contract change, anchored to a PR and a sha, so `git log ..` tells you which apply. -### The default client is now the Go one - -`packages.default` and `apps.default` were the **Python** client; since -**[#50](https://github.com/ZacxDev/cairn/pull/50)** they are the **Go** one, so -`nix run github:ZacxDev/cairn` and `nix profile install github:ZacxDev/cairn` execute -`cmd/cairn`. - -Two behaviours change: **`cairn -verbs` and `cairn -exit-codes` now answer** — exit `0` with -a table on stdout, where the Python client exits `2` with argparse's `usage:` — a single-dash -token *succeeding* where the default previously refused; and **argparse's exact wording is -gone** from `--help` and usage errors, so anything parsing that prose needs re-reading. The -exit codes themselves are identical and gated. ⚠ **Whether `-verbs`/`-exit-codes` become -documented public surface or move behind a gate is a P8 decision that has not been taken.** - -**Nothing was deleted, and `cairn` is the opt-out — in BOTH consumption modes.** From the CLI it -is a `#fragment` (`nix run github:ZacxDev/cairn#cairn -- doctor`); a consumer that pins this -flake as an **input** reaches an *attribute* instead: - -```nix -{ - inputs.cairn.url = "github:ZacxDev/cairn"; # or pin a rev/ref - - outputs = { self, nixpkgs, cairn, ... }: - let system = "x86_64-linux"; in { - # `cairn.packages.${system}.default` is now the GO client. - # Take the PYTHON client by name instead: - packages.${system}.my-cairn = cairn.packages.${system}.cairn; - # …and its runnable form, if you re-export an app: - apps.${system}.my-cairn = cairn.apps.${system}.cairn; - }; -} -``` +### The Python client and pod are retired — there is no `#cairn` any more + +`packages.default` and `apps.default` were the **Python** client until +**[#50](https://github.com/ZacxDev/cairn/pull/50)** made them the **Go** one (`cmd/cairn`). The +Python client stayed reachable as `#cairn` (and `packages.cairn`/`apps.cairn` for a flake input) +until it was **deleted** together with the Python pod (`packages.server-image`, published as +`cairn-store`): see the `CHANGELOG.md` row. A consumer that still names `cairn.packages.${system}.cairn` +or `#cairn` gets an evaluation error — use `default` (or `cairn-go`, the same store path). -Both spellings are gated: `checks.default-is-the-go-client` pins the flip and both opt-outs at -evaluation time, and its description beside the code in `flake.nix` is the one worth trusting. -**Why the flip was taken on an operator decision rather than on a green gate** is -[`tests/parity/README.md`](tests/parity/README.md) residual 7, and nowhere else on purpose. +What changed for anyone who moved with the default at #50: **`cairn -verbs` and +`cairn -exit-codes` answer** (exit `0` with a table on stdout — public surface now), and +**argparse's exact wording is gone** from `--help` and usage errors. The exit codes themselves +are identical and gated. The `cairn-store` ghcr package keeps its existing tags but receives no +new ones; the deployed pod is `cairn-store-go`. ### The environment variables are now `CAIRN_*` @@ -1342,9 +1308,11 @@ Every `SUBSYSTEM_STORE_*` variable has a `CAIRN_*` name, and the pod-side JWT ve `CAIRN_SUPABASE_*` settings are `CAIRN_OIDC_*`. **Both spellings work.** Within one source the new name wins: the old one is read only when the new one is unset or blank *there*. An old name that is *present* — including when the new one shadows it — prints one line per process on -stderr naming its replacement. The window closes when `packages.cairn` is retired (P8) — a -milestone, not a date: `flake.nix` sets `version = self.shortRev`, so there is no semver to hang -one on. +stderr naming its replacement. The window was to close when `packages.cairn` was retired; that +has happened, and the old names **still work**, by decision — removing them breaks every +deployment still exporting one, so it will be its own change, announced in `CHANGELOG.md`, and +the warning names that announcement. A milestone, not a date: `flake.nix` sets +`version = self.shortRev`, so there is no semver to hang one on. | set this | instead of | what it is | |---|---|---| @@ -1384,8 +1352,8 @@ are not in it. same three values; and migrating to `CAIRN_*` now silences the warnings. ⚠ `docker inspect` no longer shows them: the startup line `listening on : store= token-ids=…` replaces the port and store root, and the token PATH appears only in `cairn-server -h`'s - default. `tests/test_flake_image_matches_dockerfile.py` pins the three against both - implementations' code defaults. + default. `tests/test_server_deployment_defaults.py` pins the three against the server's code + defaults. - ⚠ **One `CAIRN_OIDC_*` behaviour differs**: a whitespace-only new value beside a real old one is refused at 78 rather than falling through (the CHANGELOG row for #176). diff --git a/cairn b/cairn deleted file mode 100755 index ceb4ae57..00000000 --- a/cairn +++ /dev/null @@ -1,2950 +0,0 @@ -#!/usr/bin/env python3 -"""`cairn` — the read-through client for the hosted subsystem store (phase 2). - -WHAT THIS IS FOR. The pod serves a read-only API; for a long time every request -it logged came from the session that built it, because **no client was ever -written**. This is that client. - -🔴 THE READER KEEPS ITS NO-NETWORK PROPERTY; THIS WRAPPER OWNS THE NETWORK. -`subsystem_recall.py` documents itself "READ-ONLY. No clock, no network, no git, -no prompt" and runs on the `/resume` hot path. Proposal §2d is explicit that a -recall must not become a live HTTP call: a DNS blip, a suspended laptop or a -cluster reconcile would turn "orient me" into an error, or — worse — into an -empty screen that reads like "nothing recorded". So `cairn` syncs the store into -a local cache and runs the **unmodified** reader against it. Nothing in -`lib/` is imported-and-patched, monkeypatched or forked here. - -🔴 WHY A STATE LINE IS PRINTED BEFORE EVERY REPORT, AND WHY IT IS NOT OPTIONAL. -The server prepends a provenance banner to every response for a measured reason -(`server.py::snapshot_freshness`): the public endpoint answered -`ALL 5 entries in alpha-toolkit/, none omitted` while the source held 9, and one served -entry was a 40-day-old copy of a file edited that morning. Nothing was wrong; -nothing was current either. Running the reader locally against a cache would -DROP that banner and reintroduce exactly that confusion, because the reader's -"none omitted" is a truthful claim about whatever bytes it was pointed at. So -this client states, in the output itself, which of four states produced it: - - live fetched just now exit 0 - cached (stale ) pod unreachable, served from cache exit 0 - scope-empty reached the store, genuinely nothing exit 0 - store-unreachable, no cache nothing was read at all exit 3 - -🔴 The fourth is the one that must never be collapsed into the third. `scope-empty` -and `store-unreachable` both "print no entries", and one of them is a lie. That is -the silent-zero class `obs-read` and `drift-check.sh` exist to defend against. - -Two codes sit outside that table because they are not READ outcomes: -`sync` returns 4 when it could not refresh though a cache survived (a refresh -that exits 0 on an outage is how a timer reports success forever), and any -command returns 5 when the server's archive is REFUSED — a link, a traversal -member, a duplicate, or a count disagreeing with the server's own header. 5 is -never absorbed into "served from cache"; an outage is benign and that is not. -Beyond those, a report exits with the READER's own code, so a scope whose -entries are all malformed still exits non-zero as it always did. - -🔴 AND THE WRITE VERBS ARE THE MIRROR IMAGE — `append`, `put` and `create` DO -NOT DEGRADE. The table above exists because a read must never report an outage as -an empty store. A write has the opposite obligation: there is no cache to answer -from and no such thing as a stale write, so an unreachable store is a REFUSED -write at exit 7, never a queued one and never a local one. Codes 6/7/8/9 -(refused / unreachable / precondition-failed / already-exists) are disjoint from -every read code precisely so a caller cannot read "nothing was displayed" as "the -bullet landed". The pod is the authority; this cache has none. See the WRITE PATH -block below the readers. - -🔴 `create` IS THE VERB THAT MAKES A NEW ENTRY, AND IT WAS ADDED LATE. -`append` and `put` both resolve an EXISTING ref, so the store had no -create primitive at all and the write protocol told sessions to write a -brand-new entry into the local `~/.claude//` tree. That was -correct while that tree WAS the store; after the read path moved to the pod -cache it meant the entry was dark to every reader. Measured: five -whole entries existed only on one host. `create` sends `If-None-Match: *`, so it -creates only if absent and REFUSES (exit 9) rather than overwriting. - -CONFIG: `~/.config/subsystem-store/env` (mode 0600) — `CAIRN_URL`, `CAIRN_TOKEN` -(`ENV_URL`/`ENV_TOKEN` below). Environment variables of the same name win, so a -test can point this at a throwaway server without touching the file. See -SECRETS.md. - -🔴 THE `SUBSYSTEM_STORE_*` SPELLINGS STILL WORK, IN BOTH PLACES. `env_aliases` -resolves `SUBSYSTEM_STORE_URL`/`SUBSYSTEM_STORE_TOKEN` as deprecated aliases — -as exported variables AND as keys of the file above — with the NEW name winning -and one stderr warning per process naming the replacement. The ledger, the -precedence rule and the removal anchor (`packages.cairn` retiring, at P8) are -`lib/env_aliases.py`; do not open-code a fallback here. - -🔴 MORE THAN ONE INSTANCE, AND NOTHING CHANGES UNTIL THERE IS ONE. The file -above is the `personal` instance; additional instances are ADDITIVE files at -`~/.config/subsystem-store/instances/.env`, each with its own cache root -and its own `.sync-stamp`. A scope is routed to an instance by a table the -OPERATOR supplies (`~/.config/subsystem-store/routes.json`, or `$CAIRN_ROUTES`) -— never by anything checked in here, because this program knows how to route -and nothing about who routes where. - -🔴 AN UNREGISTERED SCOPE REFUSES AT EXIT 11, NAMING THE SCOPE, ONCE THERE IS -MORE THAN ONE INSTANCE. It never falls back to one of several. A default would -silently recreate the failure this whole tool exists to close — a write landing -in a store nobody reads — and that one is found days later, by accident, if at -all. With ONE instance configured there is no second place a scope could go, so -nothing is labelled and every byte of output is what it was before any of this -existed — a routing TABLE being present does not change that, because a table -says where scopes live and not how many stores this host can reach. - -🔴 ONE EXCEPTION AT EVERY INSTANCE COUNT: a table entry naming an alias this -host has no config for REFUSES. That entry is a statement that the scope lives -somewhere this machine cannot reach, so resolving it to the sole instance would -be the misroute in its purest form. See `cairn_instances.Routing.alias_for`. -""" - -from __future__ import annotations - -import argparse -import fcntl -import hashlib -import io -import json -import os -import shutil -import sys -import tarfile -import tempfile -import time -import urllib.error -import urllib.request -import zlib -from pathlib import Path -from typing import Sequence -from urllib.parse import quote - -sys.path.insert(0, str(Path(__file__).resolve().parent / "lib")) - -from timeouts import unbounded_timeout_reason # noqa: E402 - - -def _mirror_root() -> "Path | None": - """The frozen pre-cutover store, if this deployment has one. - - 🔴 UNSET IS THE DEFAULT, and `doctor` reports NOT-OBSERVABLE rather than OK - for it. A deployment that migrated from a local store points this at the old - root so `doctor` can confirm its entry files are read-only; one that never - had a local store has nothing to name, and claiming "it does not exist" - about a path nobody configured would be a statement about the operator's - disk that this code cannot support. - """ - raw = os.environ.get("CAIRN_MIRROR_ROOT", "").strip() - return Path(raw).expanduser() if raw else None -import subsystem_recall as rc # noqa: E402 -import entry_shape # noqa: E402 -from entry_shape import scope_for_repo # noqa: E402 - -# 🔴 THE CACHE PATH AND THE STAMP NAME ARE IMPORTED, NOT DECLARED. They used to -# live here, which made this file the only thing that knew where a host reads the -# store from — and the readers (`subsystem_recall.py`'s CLI, `service_recon.py`) -# went on pointing at the FROZEN pre-cutover mirror for a day because nothing -# they imported could tell them otherwise. One definition, in -# `subsystem_read_store`; the writer and every reader now move together. -# 🔴 THE MODULE, NOT `from … import DEFAULT_CACHE_ROOT`. That spelling is the one -# `read_store_root`'s own docstring names as defeating a test's repointing: it -# binds the value at IMPORT, so a later `monkeypatch.setattr(rs, -# "DEFAULT_CACHE_ROOT", …)` moves the reader and leaves this WRITER pointed at -# the operator's real cache. Nothing depended on that yet — which is exactly when -# it is cheap to fix. `build_parser` calls the accessor instead. -import subsystem_read_store as _read_store # noqa: E402 -import subsystem_resolver # noqa: E402 -from subsystem_read_store import SYNC_STAMP # noqa: E402 -# 🔴 THE MODULE, FOR THE SAME REASON AS `_read_store` ABOVE. `cairn_instances` -# resolves paths from `Path.home()` and the environment at CALL time, so a -# `from … import config_path` here would bind the function but a -# `from … import DEFAULT_*` would bind a value — and the config path is exactly -# the kind of fact a test repoints. One import style for both. -import cairn_instances # noqa: E402 -import env_aliases # noqa: E402 -import read_ledger # noqa: E402 - -# The two names that configure the default instance, in their current spelling. Each -# reads from an exported variable OR from a key of the config file, and each has a -# deprecated `SUBSYSTEM_STORE_*` alias `env_aliases` resolves. They are constants rather -# than literals because the "config incomplete" refusal interpolates them, and that -# refusal is compared byte-for-byte against the GO client by `tests/parity/harness.py`. -ENV_URL = "CAIRN_URL" -ENV_TOKEN = "CAIRN_TOKEN" -DEFAULT_TIMEOUT = 20 -# Ceiling on what a snapshot may unpack to. The whole store measured ~63 KB of -# markdown across 305 entries in 2026-08; 256 MB is ~4000x that, so it bounds a -# decompression bomb without being reachable by real growth for years. -MAX_UNPACKED_BYTES = 256 * 1024 * 1024 -# Companion ceiling on MEMBER COUNT. The live store held 305 entries in 2026-08; -# 50,000 is ~160x that and bounds an inode bomb, which the byte ceiling alone -# cannot see because empty members declare size 0. -MAX_MEMBERS = 50_000 - -# Whether this interpreter's `TarFile.extract` takes `filter=`. -# -# 🔴 FEATURE-DETECTED, NEVER A VERSION COMPARISON. The extraction filters landed -# in 3.12 and were BACKPORTED to 3.11.4, 3.10.12, 3.9.17 and 3.8.17, so the -# predicate "has filters" is not an interval on version_info and any `>=` spelling -# of it is wrong for some supported interpreter. `hasattr(tarfile, "data_filter")` -# is what CPython's own documentation tells a caller to branch on, and it is true -# exactly when the kwarg exists. -# -# 🔴 THIS EXISTS BECAUSE THE CLIENT CARRIED AN UNDECLARED 3.12 FLOOR AND NOTHING -# SAID SO. `tar.extract(..., filter="data")` is a TypeError on 3.11.2 — not a -# degraded extraction, a crash on the sync path, so `recall` dies with a traceback -# rather than any of this client's exit codes. It went unseen because every host -# that runs the client interactively is on 3.12; it surfaces the moment the client -# is installed into an image that is not. A client whose whole job is to be fetched -# by sha and run on someone else's interpreter must not assume the newest one. -HAS_TAR_FILTERS = hasattr(tarfile, "data_filter") - -# Exit codes. 0/3 are the contract §3 pins; the reader's own non-zero codes pass -# through unchanged so a malformed entry still reports what it always did. -EXIT_OK = 0 -EXIT_UNREACHABLE_NO_CACHE = 3 -EXIT_USAGE = 2 -# `sync` only: the store was not reached, but a usable cache survived. Distinct -# from 3 so a caller can tell "stale but serviceable" from "nothing at all". -EXIT_REFRESH_FAILED = 4 -# The server answered with something we refuse to install. Distinct from every -# other code so it can never be read as an outage or as a clean run. -EXIT_CORRUPT = 5 - -# --- WRITE codes. Deliberately distinct from every READ code above. ---------- -# -# 🔴 A WRITE HAS NO CACHE TO FALL BACK ON, AND THAT ASYMMETRY IS THE CONTRACT. -# `recall`'s job is to answer, so an outage degrades to a stale answer that says -# it is stale, at exit 0. A write's job is to make a durable record; there is no -# such thing as a stale write, and a queued one is a write the caller believes -# landed. So `append`/`put`/`create` FAIL LOUDLY when the store cannot be reached — the -# accepted cost of decision 8 in `claudedocs/plan-cairn-integration.md`, stated -# there and stated again here so a future reader cannot mistake it for an -# oversight and "fix" it by adding a spool. -# -# 6 = the STORE refused the request and the caller must change it (4xx that is -# not a precondition failure): a malformed bullet, an unknown ref, a scope -# this credential may not see. Retrying byte-for-byte cannot help. -EXIT_WRITE_REFUSED = 6 -# 7 = the write did NOT happen and the reason is not the caller's request — the -# host was unreachable, or the server could not read its own store (503). -# Distinct from 6 because a retry is exactly the right response to this one -# and exactly the wrong response to that one. -EXIT_WRITE_UNREACHABLE = 7 -# 8 = the precondition failed (412): the entry moved under the revision this -# write was based on. Its own code because the remedy is unique — re-sync, -# re-derive the revision, re-apply the edit — and because collapsing it into -# 6 would invite a blind retry that either 412s forever or, with `If-Match` -# dropped, silently overwrites somebody else's change. -EXIT_WRITE_PRECONDITION = 8 -# 9 = `create` only: the entry ALREADY EXISTS, so nothing was created and -# nothing was overwritten. 🔴 ITS OWN CODE EVEN THOUGH THE SERVER ANSWERS -# THE SAME 412 AS 8, because the two remedies are opposites: 8 means "the -# entry moved under you — re-sync, re-derive, re-apply, put again", and a -# retry is right; 9 means "you asked to create something that is there — -# use `append` or `put`", and the identical retry loops forever. They are -# told apart by `X-Store-Status` (`precondition-failed` vs `already-exists`), -# which is the only place on the wire the difference exists. -EXIT_WRITE_EXISTS = 9 - -# --- ROUTING. Neither a read code nor a write code, deliberately. --------- -# 11 = this client could not decide WHICH INSTANCE a scope belongs to, so it did -# nothing. Either the routing table does not name the scope, or the table -# itself cannot be read. 🔴 ITS OWN CODE, AND IT IS A READ/WRITE-NEUTRAL -# ONE: the refusal happens BEFORE either path, and collapsing it into 3 -# ("nothing was displayed") or 7 ("the write did not happen") would tell a -# caller the store was unreachable when the store was never chosen. The -# remedy is a line in a table, not a retry. -EXIT_UNROUTED = 11 - -STATE_LIVE = "live" -STATE_CACHED = "cached" -STATE_EMPTY = "scope-empty" -STATE_NO_CACHE = "store-unreachable, no cache" - - -class StoreUnreachable(Exception): - """The pod could not be read. Carries the reason, never a bare failure. - - 🔴 The reason is mandatory: criterion 5 of the card this implements is that - an unreachable host is reported as UNMEASURED **with a reason**, never as a - silent success or a zero. - - 🔴 `http_status` IS THE STRUCTURAL DISCRIMINATOR, AND IT EXISTS BECAUSE THE - MESSAGE IS NOT ONE. "the host never answered" and "the host answered 401" - are both raised here — deliberately, since a read degrades to the cache - either way — but they are NOT the same fact to a human: one is an outage and - the other is a credential that has to be replaced. The only thing that told - them apart was the phrasing of `str(exc)`, and a caller that greps a message - for `HTTP 401` has pinned an f-string. `None` means there was no answer at - all; an int is the status the server sent. `resolve_state` reads neither, so - nothing about the read path changes. - """ - - def __init__(self, *args: object, http_status: int | None = None) -> None: - super().__init__(*args) - self.http_status = http_status - - -class StoreCorrupt(Exception): - """The server answered, and what it sent is not a store we will accept. - - 🔴 DELIBERATELY NOT A SUBCLASS OF `StoreUnreachable`. An outage is absorbed - into "serving from cache" at exit 0, which is right for an outage and wrong - for this: a server shipping a traversal member, a link, a duplicate, or a - count that disagrees with its own header is the one case that has to be - LOUD. Collapsing the two would let a hostile or broken archive render as a - reassuring `⚠ SERVED FROM CACHE`. - """ - - -def _warn_deprecations(lines: list[str]) -> None: - """Emit `env_aliases` warnings on stderr, at most once per process per line. - - 🔴 THE PREFIX AND THE STREAM ARE PART OF THE CONTRACT, NOT A PRESENTATION CHOICE. - `tests/parity/harness.py` diffs this client's stderr against the Go client's - BYTE-FOR-BYTE, so `cairn: ` and `file=sys.stderr` here have to match - `internal/client.Run`'s sink exactly. `env_aliases.warn_once` owns the "at most - once" rule for both languages, so neither side counts for itself. - """ - env_aliases.warn_once(lines, lambda line: print(f"cairn: {line}", file=sys.stderr)) - - -def load_config(path: Path | None = None, *, instance: str | None = None) -> tuple[str, str]: - """`(url, token)` from the env file, with real environment taking priority. - - A missing file is not fatal on its own — the caller may have exported both - values — but a missing VALUE is, and it says which one. "No token" must not - degrade into an unauthenticated request that comes back 401 and gets read as - "the store is down". - - 🔴 THE ENVIRONMENT OVERRIDES THE DEFAULT INSTANCE ONLY, AND THE ASYMMETRY IS - THE WHOLE REASON A SECOND INSTANCE IS SAFE TO ADD. `SUBSYSTEM_STORE_URL` has - always pointed this client at a throwaway server, and letting it win for - EVERY alias would point them all at one store: a `doctor` that walks three - instances would then measure one three times and report agreement it never - observed, and a routed write would land somewhere the table did not name. - A non-default alias reads its own file and nothing else. - """ - alias = instance or _read_store.DEFAULT_ALIAS - is_default = alias == _read_store.DEFAULT_ALIAS - if path is None: - path = ( - cairn_instances.config_path() - if is_default - else cairn_instances.instance_dir() - / f"{alias}{cairn_instances.INSTANCE_SUFFIX}" - ) - from_file: dict[str, str] = {} - try: - for line in path.read_text(encoding="utf-8").splitlines(): - line = line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - key, _, value = line.partition("=") - from_file[key.strip()] = value.strip() - except OSError: - pass - - # 🔴 THE FILE IS AS MUCH AN ALIAS SURFACE AS THE ENVIRONMENT IS. `SUBSYSTEM_STORE_URL=` - # is a KEY inside `~/.config/subsystem-store/env` as well as an exported variable, and - # an operator who renamed only one of the two would get a silent half-migration — the - # file key ignored, the environment honoured. Its warning NAMES THE FILE rather than - # `$VAR`, because the string lives somewhere they have to edit. - _warn_deprecations(env_aliases.file_deprecations(from_file, str(path))) - - if is_default: - url = env_aliases.value(os.environ, ENV_URL) or env_aliases.value(from_file, ENV_URL) - token = env_aliases.value(os.environ, ENV_TOKEN) or env_aliases.value( - from_file, ENV_TOKEN - ) - where = f"(looked in {path} and the environment)" - else: - url = env_aliases.value(from_file, ENV_URL) - token = env_aliases.value(from_file, ENV_TOKEN) - where = ( - f"(looked in {path}; the environment is NOT consulted for a " - f"non-default instance, so a `{alias}` instance is configured by " - f"that file alone)" - ) - missing = [ - n - for n, v in ((ENV_URL, url), (ENV_TOKEN, token)) - if not v - ] - if missing: - raise StoreUnreachable( - f"config incomplete: {', '.join(missing)} not set {where}" - ) - return url.rstrip("/"), token # type: ignore[union-attr,return-value] - - -# --- INSTANCES AND ROUTING -------------------------------------------------- -# -# 🔴 TWO PREDICATES, NOT ONE, AND KNOWING WHICH YOU WANT IS THE WHOLE TRAP. -# -# * `Routing.multi_instance` — "is there more than one PLACE on this host?". -# Every site that LABELS output asks this and nothing else: the banner -# label, the write label, `doctor`'s per-instance sections, `ls-entries`' -# prefix, the search fan-out and the caveat's extra clause. Six copies of -# `len(instances) > 1` would be six chances to disagree, and the symptom of -# disagreeing is output that names an instance the next line does not. -# * `Routing.alias_for` — "WHERE does this scope live?". It consults the -# routing TABLE first, so a one-instance host with a table still refuses a -# scope routed to an alias it has no config for. -# -# 🔴 THEY WERE ONE BOOLEAN AND THAT WAS A DEFECT, recorded here because the -# collapse is the obvious simplification and it is wrong in both directions. -# `active = routes is not None or len(instances) > 1` made a table's PRESENCE -# switch labelling on, so the first operator to write a table on a one-instance -# host got "with more than one instance configured …" on every recall — false on -# that host — and every scope not yet in the table refused at exit 11. Deleting -# the `routes is not None` disjunct fixes those and opens a SILENT MISROUTE: a -# table entry naming an unconfigured alias would then resolve to the sole -# instance. The three-row table in `cairn_instances.Routing.alias_for` is the -# measurement; do not re-collapse these. - - -def _routing() -> "cairn_instances.Routing": - """What is configured, read fresh. NOT cached in a module global. - - A cache would be read once per process and then be wrong for any test that - repoints `$HOME` between calls — and it would buy a few `stat`s on a command - that is about to open a socket. - """ - return cairn_instances.discover() - - -def _instance_cache(args: argparse.Namespace, alias: str) -> Path: - """The cache root for `alias`, honouring an explicit `--cache`. - - 🔴 AN EXPLICIT `--cache` WINS, AND THE DEFAULT IS RESOLVED PER INSTANCE. The - parser's default is still the DEFAULT instance's root — unchanged, printed - in `--help`, and what a single-instance host uses — but a second instance - must not share one directory with the first: two stores unpacked over each - other would interleave scopes, and `.sync-stamp` would date whichever synced - last while the entries came from both. - """ - if getattr(args, "cache_explicit", False): - return args.cache - return _read_store.cache_root_for(alias) - - -def _instance_for(args: argparse.Namespace, scope: str) -> tuple[str, str | None, Path]: - """`(alias, label, cache)` for a scope. Raises `UnroutedScope` — never guesses. - - `label` is the alias when this host has MORE THAN ONE INSTANCE and `None` - when it has one. 🔴 THAT `None` IS THE COMPATIBILITY GUARANTEE, not a - formatting nicety: it is what keeps a one-instance host's output - byte-for-byte what it was, so the LABELLING half of the routing machinery - can ship and be proven inert before any data moves. - - ⚠ THE *ROUTING* HALF IS NOT INERT AT ONE INSTANCE, AND THIS SENTENCE USED - TO BE READ AS COVERING BOTH. `routing.alias_for` is consulted whatever - `multi_instance` says, and its row 3 — a table routing this scope to an - alias the host has no config for — REFUSES at exit 11 with one instance - exactly as with many. Measured on a one-instance host with - `routes.json = {"alpha-notes": "nowhere"}`: `recall`, `search` and - `validate` all exit 11 here, and the Go client agrees (it answered 0 with - a digest at `d8b858a`, before its reads routed). `sync`, `ls-entries` and - `doctor` are untouched — they ROUTE NOTHING. - - 🔴 "THEY TAKE NO SCOPE" IS WHAT THAT LAST CLAUSE USED TO SAY, AND `--help` - FALSIFIES IT FOR TWO OF THE THREE. `cairn sync` and `cairn ls-entries` both - declare `--scope`; only `doctor` has no such flag. What makes them untouched - is that they pass `scope=None`/`""` regardless and walk EVERY instance — see - `cmd_sync` for the measured reason this cache may never be narrowed. The - conclusion is unchanged and re-measured on the same world: `sync --scope - alpha-notes` exits 4 and `ls-entries --scope alpha-notes` exits 0, on both - clients, byte-identical to the unscoped runs. 🔴 THE REASON IS LOAD-BEARING - RATHER THAN PEDANTIC: a later change that routed `ls-entries --scope` - through `alias_for` would falsify the conclusion while the old reason still - read as covering it. - - 🔴 AND IT IS GATED ON THE INSTANCE COUNT, NEVER ON THE TABLE. A one-instance - host that has written a routing table is still a host with one place an - answer can come from, so it is still unlabelled — while `alias_for` above - has already consulted that table and may have refused. The two questions are - separate; see the header comment. - """ - routing = _routing() - alias = routing.alias_for(scope) - return alias, (alias if routing.multi_instance else None), _instance_cache(args, alias) - - -def _repo_scope(args: argparse.Namespace) -> str: - """The scope `--repo` derives, or `""` when it cannot be derived. - - Swallows the error ON PURPOSE and only where the CALLER has a real answer - for the empty case — `validate` falls back to the default instance, because - "which cache am I checking" has one sensible answer outside a repo and - "where does this write land" does not. - """ - try: - return scope_for_repo(args.repo) or "" - except Exception: # GitError and anything else the resolver raises - return "" - - -def _default_instance(args: argparse.Namespace) -> tuple[str, str | None, Path]: - """The default instance, LABELLED when this host has more than one. - - Used where there is no scope to route. The label still appears, because - "which of my instances did that read" is exactly as pressing when the - command picked one as when a table did. - """ - routing = _routing() - alias = _read_store.DEFAULT_ALIAS - return alias, (alias if routing.multi_instance else None), _instance_cache(args, alias) - - -def _refuse_shared_cache( - args: argparse.Namespace, routing: "cairn_instances.Routing", verb: str -) -> int | None: - """Refuse an explicit `--cache` that would make N instances share one directory. - - 🔴 THE DAMAGE IS SILENT AND IT IS TO THE CACHE, NOT TO THE OUTPUT. Two - snapshots unpacked into one root interleave their scopes, and `.sync-stamp` - then dates whichever synced last while the entries beneath it came from - both — a store that can neither say what it holds nor how old it is. The - refusal costs an error message; the alternative is a cache nobody can - trust and no way to notice. - """ - if len(routing.instances) > 1 and getattr(args, "cache_explicit", False): - print( - f"cairn: `{verb}` walks all {len(routing.instances)} configured " - f"instances ({', '.join(routing.aliases)}), so an explicit --cache " - f"would make them share one directory and overwrite each other. " - f"Drop --cache, or name one instance's scope.", - file=sys.stderr, - ) - return EXIT_USAGE - return None - - -def _search_every_instance( - args: argparse.Namespace, routing: "cairn_instances.Routing", query: str -) -> int: - """`search --all-scopes` across every configured instance. - - 🔴 A PARTIAL RESULT IS A LIE, SO AN UNREAD INSTANCE IS LOUD AND NON-ZERO. - "No matches" from a fan-out that silently skipped a store is the same - silent zero this client was built to prevent, one layer up: the caller - concludes the thing is not recorded anywhere. Hits that WERE found are - still printed — throwing away real answers to report a defect is its own - harm — but the run exits non-zero and names the instance it could not read. - - 🔴 AND EACH SECTION NAMES ITS INSTANCE. Without that, two hits with the - same ref from two stores are indistinguishable, which is the question a - second instance creates. - """ - refusal = _refuse_shared_cache(args, routing, "search --all-scopes") - if refusal is not None: - return refusal - worst = EXIT_OK - unread: list[str] = [] - for instance in routing.instances: - cache = _instance_cache(args, instance.alias) - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=instance.alias, - ) - if hint is not None: - print(banner(state, detail, instance.alias), file=sys.stderr) - unread.append(instance.alias) - worst = max(worst, hint) - continue - report = rc.search( - str(cache), - "", - query, - context=rc.CONTEXT_BULLET, - threshold=rc.DEFAULT_SEARCH_THRESHOLD, - max_hits=rc.DEFAULT_MAX_HITS, - all_scopes=True, - ) - read_ledger.record(instance.alias, read_ledger.ALL_SCOPES) - print(banner(state, detail, instance.alias)) - print() - print(rc.render_search(report, instance=instance.alias)) - print() - worst = max(worst, rc._exit_for(report.status, report.label, report.malformed)) - if unread: - print( - f"🔴 cairn: PARTIAL — {len(unread)} of {len(routing.instances)} " - f"instance(s) could not be read ({', '.join(unread)}). Anything " - f"printed above is what the instances that ANSWERED hold; it is NOT " - f"an answer about the ones that did not, and 'no matches' above does " - f"not mean the query matches nothing.", - file=sys.stderr, - ) - return worst - - -def _unrouted(exc: "cairn_instances.UnroutedScope") -> int: - """Print the refusal and return its code. ONE spelling, four call sites.""" - print(f"🔴 cairn: REFUSING — {exc.detail}", file=sys.stderr) - return EXIT_UNROUTED - - -def _apply_standard_headers(req: "urllib.request.Request", token: str) -> None: - """The two headers EVERY request to this host must carry, in ONE place. - - 🔴 A User-Agent IS REQUIRED, and urllib's default is actively refused. - MEASURED against the live host, same token, same path, three - requests differing ONLY in this header: - curl's default UA -> 200 - `Python-urllib/3.12` -> 403 <-- urllib's default - empty UA -> 200 - The 403 comes from the edge, not the app, so it is NOT a token rejection and - NOT the store being down — but it arrives looking like both. - - 🔴 THIS EXISTS AS A FUNCTION BECAUSE THE WRITE PATH WOULD OTHERWISE HAVE TO - RE-LEARN IT. When `fetch_snapshot` was the only caller the header was a line - inside it; adding `append`/`put` made that line a rule with two more sites, - and a rule at three sites is the shape `claude/RULES.md` says regenerates - the same bug at N-1 of them. - - 🔴 THE GUARD IS `test_cairn_write.py::TestTheRequestItself:: - test_no_request_builder_ANYWHERE_bypasses_this_helper` — an AST scan over - this file AND `cairn-cutover.py`, asserting every function that constructs a - `urllib.request.Request` also calls this helper. An earlier version of this - sentence named a test that **did not exist**, which is worse than naming - none: it reads as coverage and stops anyone looking. It was written while - the only real check was a behavioural one on the append path, so a new read - verb building its own request was unguarded by the very line claiming to - guard it. - """ - req.add_header("Authorization", f"Bearer {token}") - req.add_header("User-Agent", "subsystem-store-client/1") - - -SYNC_ETAG = ".sync-etag" - -#: An entity-tag longer than this is already pathological. The cap is here so a -#: hostile server cannot make this client write an unbounded file or emit an -#: unbounded request header. -MAX_ETAG_BYTES = 128 - - -def storable_etag(value: str | None) -> str: - """`value` if it is safe to write to disk and send back, else `""`. - - 🔴 THE VALIDATOR COMES FROM THE SERVER, WHICH IS THE PARTY THIS CLIENT - ALREADY DOES NOT FULLY TRUST — the same threat model as the link, traversal, - duplicate and size guards in `install_snapshot`. The rule is the RFC 9110 - `etagc` character set plus the quotes: every byte printable ASCII and none of - them a space. That is exactly what makes the value round-trip as ONE line of - a file and as ONE header, so a server cannot use it to inject a second - header or a second stamp field. - - ⚠ IT IS A FILTER, NOT A REFUSAL. An unusable tag means "this cache has no - validator", never "this response is corrupt": the content arrived fine and - the only cost is that the next sync cannot be conditional. Refusing here - would let a malformed header break a sync that otherwise worked. - """ - if not value or len(value) > MAX_ETAG_BYTES: - return "" - return value if all("\x21" <= ch <= "\x7e" for ch in value) else "" - - -def stored_etag(cache: Path) -> str: - """The validator recorded beside `cache`, or `""` for "there is none". - - 🔴 IT DOES **NOT** FILTER, AND THE FILTER IS AT THE POINT OF USE INSTEAD — - `fetch_snapshot`, which is where the value becomes a header. A filter here - as WELL was written first and then deleted: it was a second copy of one - predicate, and a mutation sweep measured the consequence — removing it - changed nothing observable, because the surviving copy caught the same - value, so the guard could not be watched to fail and read as coverage it - did not provide. One rule, one place, at the boundary that is actually - crossed. - """ - try: - return (cache / SYNC_ETAG).read_text(encoding="utf-8").rstrip("\n") - except (OSError, UnicodeDecodeError): - return "" - - -def fetch_snapshot( - url: str, token: str, *, scope: str | None, timeout: int, etag: str = "" -) -> tuple[bytes | None, dict[str, str], bool]: - """GET the tar. Every failure becomes a StoreUnreachable NAMING the host. - - 🔴 THE THIRD ELEMENT IS `not_modified`, AND IT IS A RETURN VALUE RATHER THAN - AN EXCEPTION SO NO CALLER CAN FORGET IT. A 304 is a SUCCESS with no body, - and the shape that loses it is the one where it travels as a - `StoreUnreachable`: every caller here already has an arm that degrades to - the cache on that exception, so a 304 raised would have rendered as an - OUTAGE on the one path whose whole purpose is to say the cache is CURRENT. - As a widened tuple it breaks any caller that has not been updated, loudly, - at the unpack. - - `etag` is the validator this host already holds, or `""` for "ask for the - whole thing". When it is sent and matches, `body` is `None`. - """ - # 🔴 `timeout=None` REACHES `urlopen` AS *NO* TIMEOUT, NOT AS A DEFAULT, so - # this refuses it rather than trusting the annotation above — `timeout: int` - # is a type hint, and a hint is not a code path. The sibling `who` side of - # this CLI has refused it for a long time; the store side did not, - # and mutating either `fetch_snapshot`'s or `urlopen`'s argument to `None` - # survived the whole suite. The asymmetry was the defect: one half of one - # program failing closed. - bad = unbounded_timeout_reason(timeout) - if bad: - raise StoreUnreachable(f"refusing to fetch {url}: {bad}") - target = f"{url}/api/v1/snapshot" + (f"?scope={scope}" if scope else "") - req = urllib.request.Request(target, method="GET") - # Auth + the mandatory User-Agent. See `_apply_standard_headers` for the - # measurement that makes the UA load-bearing; without it every Python client - # of this host is blocked, which is exactly the shape of bug that gets - # diagnosed as "the store is broken". - _apply_standard_headers(req, token) - # 🔴 THE ONE PLACE THE VALUE IS FILTERED ON ITS WAY OUT, and it is here - # because here is where it becomes a header. `etag` reaches this function - # from a FILE — which anything can edit — so it is not the same trust - # boundary as the response that produced it, and without this line a stored - # value carrying a newline makes `http.client` raise `ValueError` out of - # every handler in this program: an unusable validator taking down a sync - # that would otherwise have worked. - validator = storable_etag(etag) - if validator: - req.add_header("If-None-Match", validator) - try: - with urllib.request.urlopen(req, timeout=timeout) as resp: - # 🔴 RETURN THE MESSAGE, NEVER A DICT BUILT FROM IT. - # `resp.headers` is an `email.message.Message` and its `.get()` is - # already case-insensitive; `dict(resp.headers)` throws that away. - # HTTP/2 lowercases every header name and this host is behind - # Cloudflare, so in PRODUCTION the keys arrive lowercased while the - # code asked for the mixed-case spelling. MEASURED against the live - # pod on the first real call after deploying 0.4.0: - # dict(resp.headers).get("X-Store-Entries") -> None - # dict(resp.headers).get("x-store-entries") -> 75 - # Silent consequences: `snapshot=UNSTAMPED`, `revision=unknown`, and - # — worst — the count cross-check against `X-Store-Entries` NEVER - # FIRED, so the guard against a truncated transfer was inert in the - # only environment that matters. 358 tests and seven audit rounds - # missed it: the test shim reproduced production's TOPOLOGY but not - # its NORMALISATION. - # - # ⚠ A `{k.lower(): v}` comprehension fixes the case and introduces a - # SECOND bug: on a duplicated header a dict keeps the LAST value - # where `Message.get` returns the FIRST (measured: 1 vs 99). This - # repo has `sole_header` (server.py:422) precisely because "a bare - # .get() silently takes the FIRST value" was a real smuggling bug, - # and its rule is REFUSE a duplicate, not quietly pick the other - # end. Handing back the Message keeps ONE semantics rather than - # inventing a second — caught in review, not shipped. - return resp.read(), resp.headers, False - except urllib.error.HTTPError as exc: - # 🔴 CHECKED BEFORE THE REASON IS BUILT, BECAUSE `urllib` ROUTES A 304 - # HERE. `HTTPErrorProcessor` raises for everything outside 2xx, so the - # one non-200 on this route that means the fetch SUCCEEDED arrives as an - # exception — and the arm below would turn it into "answered HTTP 304", - # degrading a healthy, confirmed-current cache into `⚠ SERVED FROM - # CACHE` with a scary reason attached. `exc.headers` is the same - # `email.message.Message` the success path returns, so the caller reads - # `ETag` and `X-Store-Snapshot` off it identically. - if exc.code == 304: - return None, exc.headers, True - # 🔴 CARRY THE BODY. The server's 503 names WHICH scope it could not - # read; reporting only "answered HTTP 503" throws that away and leaves - # the operator with a code and no cause — the opposite of "UNMEASURED - # with a reason". Truncated because this is a one-line reason, not a page. - try: - detail = exc.read().decode("utf-8", "replace").strip().replace("\n", "; ") - except Exception: - detail = "" - detail = f" — {detail[:300]}" if detail else "" - raise StoreUnreachable( - f"{url} answered HTTP {exc.code}{detail}", http_status=exc.code - ) from exc - except urllib.error.URLError as exc: - raise StoreUnreachable(f"{url} unreachable: {exc.reason}") from exc - except OSError as exc: # socket timeouts and friends - raise StoreUnreachable(f"{url} unreachable: {exc}") from exc - - -def _safe_member_name(name: str) -> bool: - """True when `name` stays inside the extraction root. - - 🔴 NOT `".." in name`. That was the first version and it is over-broad: a - legitimate entry called `widget-cfg/a..b.md` contains `..` as a SUBSTRING - and aborted the entire sync, which then rendered as an outage. The server - puts no constraint on entry filenames, so this is reachable with an ordinary - file. Decide on path COMPONENTS, which is the actual property. - """ - if not name or name.startswith("/") or os.path.isabs(name): - return False - parts = Path(name).parts - return bool(parts) and not any(p in ("..", "") for p in parts) - - -ORPHAN_GRACE_SECONDS = 3600 - - -def _reap_orphans(cache: Path) -> int: - """Remove stale `.new-*` / `.old-*` trees. Returns how many. - - 🔴 THE PER-RUN STAGING NAME TRADED ONE BUG FOR A LEAK. The pre-fix version - used a FIXED staging name and `rmtree`d it at the top of every run, which - raced (that was the truncation bug) but was self-healing. Unique names fixed - the race and removed the healing: an audit SIGKILLed three syncs mid-run and - the orphaned trees were still there afterwards, with a later clean sync - leaving them alone. `finally` covers exceptions; it does not cover SIGKILL, - a power cut, or an OOM — and with the planned sync timer these accumulate in - `~/.cache` without bound. - - The grace period is why this is safe to run at the START of a sync: a - directory younger than an hour may belong to a CONCURRENT sync, and deleting - it would reintroduce the very race the unique names removed. Anything older - than that cannot be live — the whole operation takes well under a second. - """ - cutoff = time.time() - ORPHAN_GRACE_SECONDS - reaped = 0 - for prefix in (f"{cache.name}.new-", f"{cache.name}.old-"): - for path in cache.parent.glob(f"{prefix}*"): - try: - # `lstat`, not `stat`: a SYMLINK named like a staging dir - # dereferences under `is_dir()`/`stat()`, and `rmtree` on a - # symlink is a silent no-op — so it would be counted as reaped - # while never being removed, and the miscount is invisible - # because the count is the only evidence. - if path.lstat().st_mtime >= cutoff: - continue - if path.is_symlink(): - path.unlink() - elif path.is_dir(): - shutil.rmtree(path, ignore_errors=True) - else: - continue - reaped += 1 - except OSError: - continue # someone else's, or vanished under us; not our problem - return reaped - - -def install_snapshot(body: bytes, cache: Path, headers: dict[str, str]) -> int: - """Replace the cache with the tar's contents. - - 🔴 CONCURRENT SYNCS USED TO SILENTLY TRUNCATE THIS CACHE, and the previous - docstring claimed the opposite. The staging directory had a FIXED name and - was `rmtree`d at the top of every run, so two syncs shared it: measured over - 10 trials on a 305-entry store, 3 left a SHORT cache (183, 256, 292 entries) - with no error, and further runs died with `FileExistsError` / - `Directory not empty`. The reader then rendered that partial tree under its - own "none omitted" header — the completeness lie, arriving by the one route - this function exists to close. This repo's AGENTS.md says concurrent - sessions are normal, and a timer is planned, so it was not a corner case. - - Two changes make it safe: a PER-RUN staging directory (so runs cannot share - one), and an exclusive LOCK around the swap (so the rename pair cannot - interleave). The lock is advisory and held only for the swap, so a slow - download never blocks another reader. - """ - cache.parent.mkdir(parents=True, exist_ok=True) - _reap_orphans(cache) - staging = Path(tempfile.mkdtemp(dir=cache.parent, prefix=f"{cache.name}.new-")) - - try: - count = 0 - seen: set[str] = set() - with tarfile.open(fileobj=io.BytesIO(body), mode="r") as tar: - members = tar.getmembers() - # 🔴 A DECOMPRESSED-SIZE CAP. Gzip removed the natural bound: before - # it, the response body limited what could be extracted. An audit - # MEASURED a 203,934-byte body expanding to 209,715,200 bytes on - # disk — 1028x — and the client reported `live … 1 entries`, exit 0. - # Every other hostile-archive guard here (links, traversal, - # duplicates, count mismatch) exists for a server we do not fully - # trust; a size bomb is the same threat model and was the one hole. - # 🔴 TWO CEILINGS, BECAUSE BYTES ALONE BOUND NOTHING. `m.size` is 0 - # for an empty member, so a byte ceiling never fires on an INODE - # bomb: measured against the previous commit, a 282,282-byte body - # carrying 60,000 zero-length `*.md` members wrote 60,000 files into - # the cache in 3.7 s and reported `live … 60000 entries`, exit 0. - # Same threat model as the byte bomb closed last round, one axis - # over — and `X-Store-Entries` cannot help, since the same hostile - # server sets it. - # - # `sum`, not `max`: a `max`-based ceiling passes a 1000 x 250 MB - # archive, and the single-member bomb fixture cannot tell the two - # apart (that mutant survived the previous round's suite). - declared_bytes = sum(m.size for m in members) - if declared_bytes > MAX_UNPACKED_BYTES: - raise StoreCorrupt( - f"archive unpacks to {declared_bytes} bytes, over the " - f"{MAX_UNPACKED_BYTES}-byte ceiling " - f"({len(body)} bytes on the wire)" - ) - if len(members) > MAX_MEMBERS: - raise StoreCorrupt( - f"archive holds {len(members)} members, over the " - f"{MAX_MEMBERS}-member ceiling " - f"({len(body)} bytes on the wire)" - ) - for member in members: - name = member.name - # 🔴 A HOSTILE OR CORRUPT ARCHIVE IS NOT AN OUTAGE. This raises - # StoreCorrupt, not StoreUnreachable, so it can never be quietly - # absorbed into "serving from cache" — a server shipping a - # traversal member is the one case that must be loud. - if member.issym() or member.islnk(): - raise StoreCorrupt(f"tar member is a link: {name!r}") - if not member.isfile(): - raise StoreCorrupt(f"tar member is not a regular file: {name!r}") - if not _safe_member_name(name): - raise StoreCorrupt(f"tar member escapes the root: {name!r}") - if name in seen: - raise StoreCorrupt(f"duplicate tar member: {name!r}") - seen.add(name) - # `filter="data"` is the safe extractor AND silences the - # DeprecationWarning that 3.14 prints on every unfiltered extract - # — which would otherwise land on stderr on the /resume hot path. - # - # 🔴 THE FALLBACK IS NOT "THE SAME CALL WITHOUT THE GUARD", AND - # SAYING SO WOULD BE THE COMMENT THIS FILE WARNS ABOUT. By the time - # a member reaches here the four guards above have already refused - # every link, every non-regular member, every traversal name and - # every duplicate — which is most of what the data filter rejects, - # and all of it refused LOUDER (StoreCorrupt, not a silent skip). - # What the filter still contributes on this path is MODE: it drops - # setuid/setgid/sticky and clamps the permission bits, so a hostile - # archive cannot land a setuid-bit file in the cache. The fallback - # therefore sets the mode itself rather than trusting the - # archive's. 0o644 is not a clamp of `member.mode` but a - # replacement for it: every member here is a regular file in a - # read-through cache, nothing in the tree is executed, and a - # constant cannot be walked by a crafted mode the way a mask can. - if HAS_TAR_FILTERS: - tar.extract(member, staging, filter="data") - else: - member.mode = 0o644 - tar.extract(member, staging) - if name.endswith(".md"): - count += 1 - - # 🔴 The server's own count, checked. The header comment on the server - # side claims a truncated transfer is "visible as a disagreement"; it is - # only visible if somebody compares, so this is that comparison. - declared = headers.get("x-store-entries") - if declared is not None and declared.isdigit() and int(declared) != count: - raise StoreCorrupt( - f"server declared {declared} entries, archive held {count}" - ) - - (staging / SYNC_STAMP).write_text( - "\n".join( - [ - f"synced={int(time.time())}", - f"revision={headers.get('x-store-revision', 'unknown')}", - f"snapshot={headers.get('x-store-snapshot', 'UNSTAMPED')}", - f"entries={count}", - # Recorded so a filtered cache can never be mistaken for a - # complete one. Today the CLI only ever writes ALL. - "coverage=ALL", - ] - ) - + "\n", - encoding="utf-8", - ) - - # 🔴 ITS OWN FILE, BESIDE `.sync-stamp` RATHER THAN A LINE INSIDE IT, AND - # THE REASON IS THE READER. Every non-blank line of `.sync-stamp` is - # RENDERED, as ` stamp: `, in the header of every report both - # clients print — so an `etag=` field there would put a 78-character - # digest on every recall, search and validate a human or an agent ever - # reads, for a value neither of them can act on. The two files cannot - # disagree: both are written into this staging directory and installed - # by the same atomic swap below, so a cache has both or has neither. - # - # ⚠ AND ITS ABSENCE IS NOT AN ERROR. A cache written by an older client, - # or by a pod that sends no `ETag`, simply has no validator: the next - # sync sends no `If-None-Match` and is answered the full 200 it always - # was. - validator = storable_etag(headers.get("etag")) - if validator: - (staging / SYNC_ETAG).write_text(validator + "\n", encoding="utf-8") - - lock_path = cache.parent / f"{cache.name}.lock" - with open(lock_path, "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - retired = None - try: - if cache.exists(): - retired = Path( - tempfile.mkdtemp(dir=cache.parent, prefix=f"{cache.name}.old-") - ) - retired.rmdir() # mkdtemp reserved the name; rename needs it free - cache.rename(retired) - staging.rename(cache) - staging = None # type: ignore[assignment] # ownership transferred - finally: - fcntl.flock(lock, fcntl.LOCK_UN) - if retired is not None: - shutil.rmtree(retired, ignore_errors=True) - return count - finally: - if staging is not None: - shutil.rmtree(staging, ignore_errors=True) - - -def cache_age(cache: Path) -> tuple[int | None, dict[str, str]]: - """`(age_seconds, stamp_fields)`; age is None when the stamp is unreadable. - - An unreadable stamp is NOT reported as age 0. "Fresh" is the one answer a - broken clock must never produce here. - """ - fields: dict[str, str] = {} - try: - for line in (cache / SYNC_STAMP).read_text(encoding="utf-8").splitlines(): - key, _, value = line.partition("=") - fields[key.strip()] = value.strip() - age = int(time.time()) - int(fields["synced"]) - # 🔴 A FUTURE-DATED STAMP IS UNKNOWN, NOT FRESH. The previous `max(0, …)` - # clamped it to `0s`, i.e. "just synced" — which is precisely the answer - # this function's docstring says a broken clock must never produce, and - # a suspending laptop (the case §2d is written for) is where clock jumps - # actually happen. - return (age if age >= 0 else None), fields - except (OSError, KeyError, ValueError): - return None, fields - - -def _age_phrase(seconds: int | None) -> str: - """"cache 3h old" / "cache age UNKNOWN" — never "cache age UNKNOWN old".""" - return "cache age UNKNOWN" if seconds is None else f"cache {human_age(seconds)} old" - - -def human_age(seconds: int | None) -> str: - if seconds is None: - return "age UNKNOWN" # callers phrase this as "cache old" - if seconds < 90: - return f"{seconds}s" - if seconds < 5400: - return f"{seconds // 60}m" - if seconds < 172800: - return f"{seconds // 3600}h" - return f"{seconds // 86400}d" - - -def resolve_state( - cache: Path, - *, - no_sync: bool, - scope: str | None, - timeout: int, - instance: str | None = None, -) -> tuple[str, str, int | None]: - """`(state, detail, exit_hint)` — the four-state decision, in ONE place. - - Every caller reads its state from here so the four cannot drift apart per - subcommand, which is how three of them end up rendering alike. - - `instance` names which configured instance to read. `None` is the default - instance, which is what a single-instance host has and is the only path the - environment override applies to — see `load_config`. - """ - if no_sync: - age, fields = cache_age(cache) - if not (cache / SYNC_STAMP).exists(): - return STATE_NO_CACHE, "--no-sync given and no cache exists", ( - EXIT_UNREACHABLE_NO_CACHE - ) - return ( - STATE_CACHED, - f"--no-sync given; cache {_age_phrase(age)}, " - f"revision {fields.get('revision', 'unknown')}", - None, - ) - - try: - url, token = load_config(instance=instance) - # 🔴 THE VALIDATOR IS OFFERED ONLY WHEN THERE IS A CACHE TO VALIDATE. A - # 304 answered to a host holding nothing would be a confirmation of an - # absence, and this client would have no content and no error — the one - # outcome the four-state design exists to make impossible. The file is - # written into the cache by the install that produced it, so it cannot - # outlive its tree; the stamp check is the belt to that braces, covering - # a cache root half-deleted by hand. - validator = stored_etag(cache) if (cache / SYNC_STAMP).exists() else "" - body, headers, not_modified = fetch_snapshot( - url, token, scope=scope, timeout=timeout, etag=validator - ) - if not_modified: - # 🔴 A 304 IS A FOURTH THING AND IT SAYS SO. The cache is not merely - # being served — it has just been CONFIRMED CURRENT against the pod, - # which is a stronger claim than `⚠ cached` (the pod could not be - # reached) and a different one from `live — fetched … just now` - # (bytes arrived). Both are `live` because every consumer of that - # name is asking "did we reach the store", and the answer is yes; - # the DETAIL is where what happened lives, exactly as it already - # distinguishes `--no-sync given` from `SERVED FROM CACHE` within - # `cached`. A fifth state name would have to be handled at each of - # the call sites that compare against STATE_LIVE, and the one missed - # would report a successful sync as a failure. - # - # ⚠ NOTHING IS WRITTEN. The cache is not touched, so `synced=` still - # dates the last DOWNLOAD rather than this confirmation — which - # makes a later offline banner say the cache is older than it has - # been proven to be. That is the safe direction (freshness may never - # be OVER-claimed here) and it is stated rather than fixed, because - # re-stamping means writing into a live cache that a concurrent sync - # may be renaming out from under it. - return ( - STATE_LIVE, - f"already current at {url} — not modified, " - f"snapshot {headers.get('x-store-snapshot', 'UNSTAMPED')}", - None, - ) - try: - count = install_snapshot(body, cache, headers) - except (EOFError, zlib.error) as exc: - # 🔴 THE GZIP SWITCH REOPENED THIS IN A NEW SHAPE. Before gzip a - # short body raised `tarfile.ReadError`, handled below. Compressed, - # a truncated body raises `EOFError: Compressed file ended before - # the end-of-stream marker was reached` — which was NOT caught, so - # it escaped as a traceback at exit 1 with a healthy cache unused: - # exactly the defect the ReadError arm was added to fix, one - # exception type over. Measured by an audit against this client. - raise StoreUnreachable(f"{url} sent a truncated archive: {exc}") from exc - except tarfile.ReadError as exc: - # 🔴 A 200 THAT IS NOT A TAR. Realistic in production precisely - # because this host's edge answers 200 with HTML for some clients - # (see `fetch_snapshot`'s User-Agent note). Previously this escaped - # every handler as an unhandled traceback at exit 1 — with a healthy - # cache sitting right there, unused. It is "we did not receive a - # store", i.e. the unreachable family, so the cache is served. - raise StoreUnreachable(f"{url} did not return an archive: {exc}") from exc - except OSError as exc: - # Disk full / permission denied while extracting. Same family: we - # have no new store, and the old one is still good. - raise StoreUnreachable(f"could not write the cache: {exc}") from exc - return ( - STATE_LIVE, - f"fetched from {url} just now — {count} entries, " - f"snapshot {headers.get('x-store-snapshot', 'UNSTAMPED')}", - None, - ) - except StoreUnreachable as exc: - age, fields = cache_age(cache) - if not (cache / SYNC_STAMP).exists(): - # 🔴 NOTHING WAS READ. Not an empty digest, not "nothing recorded". - return STATE_NO_CACHE, str(exc), EXIT_UNREACHABLE_NO_CACHE - return ( - STATE_CACHED, - f"{exc} — SERVED FROM CACHE, {_age_phrase(age)}, " - f"revision {fields.get('revision', 'unknown')}", - None, - ) - - -def banner(state: str, detail: str, instance: str | None = None) -> str: - """The state line. 🔴 NAMES THE INSTANCE WHENEVER THERE IS MORE THAN ONE. - - `instance=None` is the single-instance host and renders exactly what this - client has always rendered — which is what makes the multi-instance - machinery's LABELLING half provably inert before an operator configures a - second store. ⚠ Its ROUTING half is not: see `_instance_for`. - Given an alias, every state line carries it, because "where did that come - from" is the question a second instance creates and a banner is the only - line every read prints. - """ - marker = "🔴" if state == STATE_NO_CACHE else ("⚠" if state == STATE_CACHED else "") - name = "cairn" if instance is None else f"cairn[{instance}]" - return f"{marker} {name}: {state} — {detail}".strip() - - -def cmd_sync(args: argparse.Namespace) -> int: - """🔴 `sync` FAILS when it could not refresh, even though a cache survives. - - This is deliberately different from `recall`, and the difference is the - whole contract. `recall`'s job is to answer, so a stale answer is a success - that says it is stale (exit 0). `sync`'s job is to REFRESH, so "I did not - reach the store" is a failed operation no matter how good the cache is — - exit non-zero, naming the host. A `sync` that exited 0 on an outage is how a - timer reports success forever while the cache silently ages out. - """ - # 🔴 `scope=None`, ALWAYS. `--scope` used to be threaded through here, which - # REPLACED THE SHARED CACHE with a one-scope copy: measured, `validate - # --scope widget-cfg` took the cache from 305 entries to 2, after which an - # offline recall of any other scope printed "the store has no - # 'other-scope/' directory" at exit 0 — a claim about the STORE derived from - # a filtered cache. `_report` carried a comment warning about exactly this - # and the fix had been applied at ONE of three call sites. One rule, one - # place: the CLI's shared cache is now always the whole store, and - # `.sync-stamp` records `coverage=ALL` so a future filtered mode cannot - # silently inherit the completeness claim. The server keeps `?scope=` — it - # is a legitimate API capability with its own tests; it is just not - # something that may narrow this cache. - # 🔴 EVERY CONFIGURED INSTANCE, NOT THE ROUTED ONE. `sync` DOES declare - # `--scope` and passes `scope=None` regardless (see above), so it has - # nothing to route — and refreshing one of two instances while - # reporting success would leave the other silently ageing, which is the - # failure this command's own docstring exists to prevent, one instance over. - routing = _routing() - refusal = _refuse_shared_cache(args, routing, "sync") - if refusal is not None: - return refusal - worst = EXIT_OK - for instance in routing.instances: - label = instance.alias if routing.multi_instance else None - state, detail, hint = resolve_state( - _instance_cache(args, instance.alias), - no_sync=False, - scope=None, - timeout=_store_timeout(args), - instance=instance.alias, - ) - if state == STATE_LIVE: - print(banner(state, detail, label)) - continue - print(banner(state, detail, label), file=sys.stderr) - worst = max(worst, hint if hint is not None else EXIT_REFRESH_FAILED) - return worst - - -def cmd_ls_entries(args: argparse.Namespace) -> int: - """One `/.md` per line — per instance when there is more than one. - - 🔴 THE INSTANCE PREFIX IS A `[alias] ` ON THE LINE, NOT A THIRD PATH - SEGMENT. A consumer splits these on `/` expecting exactly two parts; making - it `alias/scope/entry.md` would silently re-point every such split at the - wrong field. The prefix is absent entirely on a single-instance host. - """ - routing = _routing() - refusal = _refuse_shared_cache(args, routing, "ls-entries") - if refusal is not None: - return refusal - worst = EXIT_OK - for instance in routing.instances: - label = instance.alias if routing.multi_instance else None - cache = _instance_cache(args, instance.alias) - state, detail, hint = resolve_state( - cache, - no_sync=args.no_sync, - scope=None, - timeout=_store_timeout(args), - instance=instance.alias, - ) - print(banner(state, detail, label), file=sys.stderr) - if hint is not None: - worst = max(worst, hint) - continue - prefix = "" if label is None else f"[{label}] " - listed: list[str] = [] - scopes: set[str] = set() - # ⚠ THIS `glob` SWALLOWS `EACCES` ON A SCOPE DIRECTORY, AND IS NOT CHANGED - # HERE — SAID PLAINLY SO IT IS NOT MISTAKEN FOR COVERED. `Path.glob("*/*.md")` - # skips a mode-000 child and lists its siblings, so this verb answers **0** - # and says nothing for a directory `recall`, `search` and `validate` each - # answer **3** on with `index entry unreadable`. Both clients AGREE at 0 — - # `internal/client.LsEntries` discards the same error on purpose — so it is an - # inconsistency inside each client, not a divergence between them. NOT closed: - # it would move a verb's stdout and exit code on both clients, and - # `ls-entries` fans out over every configured instance, so failing closed - # first has to decide whether one unreadable scope refuses the whole listing - # or only that instance's. - for path in sorted(cache.glob("*/*.md")): - # 🔴 A SCOPE'S `README.md` IS ITS POLICY SHEET, NOT AN ENTRY — AND - # THIS VERB IS THE ONE THAT ADVERTISES ITSELF AS "what the cache - # actually holds". The glob above is the bare `*.md` walk `load_index` - # deliberately does NOT use, so until this line existed `ls-entries` - # listed every scope's sheet as `/README.md` — measured twelve - # of them on a populated cache, under a banner naming the store they - # came from. The predicate is the LOADER'S, imported rather than - # respelled, because respelling it is how the two answers came apart. - # - # ⚠ FILTERED AFTER THE GLOB RATHER THAN BY WALKING SCOPE DIRECTORIES, - # AND THE ORDER IS THE REASON — BUT NOT THE ONE AN EARLIER FORM OF - # THIS COMMENT GAVE, WHICH HAD IT BACKWARDS. `sorted()` over `Path` - # OBJECTS compares component by component, so this client prints - # `a/y.md` BEFORE `a-b/x.md`; a per-scope walk whose joined - # `scope/name` strings are sorted compares BYTES, where `-` (0x2d) - # sorts below `/` (0x2f), and would print `a-b/x.md` first. So the - # glob IS load-bearing here — it just orders the opposite way round - # from what was written. MEASURED end to end on this client. - # - # ⚠ THE VISITED SET IS NOT A REASON: measured over a cache holding a - # dot-named scope directory and a symlinked one, `cache.glob("*/*.md")` - # and a per-scope `iterdir()`+`is_dir()` walk return the SAME files. - # - # 🔴 AND THE GO CLIENT PRINTS THE OTHER ORDER ON SOME PREFIXED SCOPE - # NAMES — BUT NOT ON ALL OF THEM, AND THIS COMMENT SAID "any cache - # where one scope name is a prefix of another", WHICH IS MEASURABLY - # FALSE. The mechanism is BYTE-WISE vs COMPONENT-WISE: the Go client - # sorts the joined `scope/name` byte by byte, while `sorted()` here - # compares `Path._parts_normcase`, a tuple, component by component - # (CPython 3.12.14). Where scope `S` is a proper prefix of scope `T`, - # this client always puts all of `S`'s files first (`S` < `T` as - # strings); Go compares `/` (0x2f) against `T`'s first byte PAST the - # prefix, so it AGREES when that byte sorts above `/` and DIVERGES - # when it sorts below. MEASURED end to end on both clients over a - # two-scope cache: `a`/`a0` (`0`, 0x30), `a`/`a_b` (`_`, 0x5f) and - # `a`/`aZ` (`Z`, 0x5a) AGREE; `a`/`a-b` (`-`, 0x2d), `a`/`a.b` (`.`, - # 0x2e) and `a`/`a+b` (`+`, 0x2b) DIVERGE. A non-prefixed pair cannot - # diverge at all — the first differing byte then lies inside both - # scope names, where the two comparisons agree. Seeding `a`/`a0`, - # which the old sentence invites, yields a GREEN and leaves the gate - # exactly as blind. No parity-corpus scope name is a prefix of - # another, so the gate has never been handed the discriminating - # input. PRE-EXISTING (both sorts predate this change) and - # deliberately NOT fixed here: it needs a corpus pair and a decided - # direction, which is a behaviour change to a verb's stdout. - if not subsystem_resolver.is_entry_filename(path.name): - continue - listed.append(f"{prefix}{path.parent.name}/{path.name}") - scopes.add(path.parent.name) - # The read ledger: one record per scope LISTED, sorted — the Go client's `listedScopes`. - read_ledger.record_all(instance.alias, sorted(scopes)) - for line in listed: - print(line) - return worst - - -def _report(args: argparse.Namespace, *, search: str | None) -> int: - routing = _routing() - # 🔴 `--all-scopes` NAMES NO SCOPE, SO IT IS NOT ROUTED — IT FANS OUT. Asking - # the routing table about this repo's scope here would refuse a fleet-wide - # search because the scope the caller did not name is unregistered, which is - # a refusal about a question nobody asked. - if search is not None and getattr(args, "all_scopes", False) and routing.multi_instance: - return _search_every_instance(args, routing, search) - - # 🔴 THE SCOPE IS DERIVED BEFORE THE SYNC, BECAUSE IT DECIDES WHICH STORE TO - # SYNC. The failure ORDER is preserved deliberately: a store that cannot be - # read is still reported before a scope that cannot be derived, because that - # is what this command has always done and the two are independent. - scope: str | None = None - scope_error: str | None = None - try: - # `scope_for_repo` raises GitError outside a git repo — previously - # uncaught, so `cairn recall` in a plain directory exited 1 with a - # traceback and the EXIT_USAGE path below was unreachable for the - # commonest way to hit it. - scope = args.scope or scope_for_repo(args.repo) - except Exception as exc: # GitError and anything else the resolver raises - scope_error = ( - f"cairn: could not derive a scope from {args.repo!r}: {exc}\n" - f" pass --scope explicitly." - ) - if scope_error is None and not scope: - scope_error = "cairn: --scope is required (no scope could be derived)" - - if scope_error is None: - try: - alias, label, cache = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - # 🔴 BEFORE THE NETWORK. Nothing is fetched, nothing is written, and - # no cache is touched: the client does not know where this scope - # lives, so any store it contacted would be a guess. - return _unrouted(exc) - else: - # No scope means nothing to route; the default instance is the one this - # host has always read, and the usage error below is the real answer. - alias, label, cache = _read_store.DEFAULT_ALIAS, None, args.cache - - # 🔴 SYNC THE WHOLE STORE, NEVER `scope=args.scope`. A scope-filtered cache - # makes the reader answer `scope-absent` for every scope that was simply not - # fetched — indistinguishable, in the output, from a scope the store has - # never held. That is the silent-zero this file exists to prevent, and the - # first draft of this function had it. - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=alias, - ) - if hint is not None: - print(banner(state, detail, label), file=sys.stderr) - return hint - if scope_error is not None: - print(scope_error, file=sys.stderr) - return EXIT_USAGE - - if search is not None: - # 🔴 WRAPPED FOR THE REASON THE RECALL BRANCH'S OWN `try` GIVES, AND IT BECAME - # REACHABLE WITH `--ref-to`. Every other operand this branch passes is a module - # constant, so `rc.search` could not raise `ValueError` here and the bare call was - # correct; `--ref-to` is the first caller-supplied one, and a malformed operand - # would traceback at rc 1 where the recall branch answers 2 with the message - # alone. A wrapper that tracebacks where the module it wraps explains itself is - # worse than not offering the flag. - try: - report = rc.search( - str(cache), - scope, - search, - context=rc.CONTEXT_BULLET, - threshold=rc.DEFAULT_SEARCH_THRESHOLD, - max_hits=rc.DEFAULT_MAX_HITS, - all_scopes=args.all_scopes, - ref_to=args.ref_to, - tag=args.tag, - ) - except ValueError as exc: - print(f"cairn: {exc}", file=sys.stderr) - return EXIT_USAGE - read_ledger.record(alias, read_ledger.ALL_SCOPES if args.all_scopes else scope) - read_ledger.record_named(alias, report) - text = rc.render_search(report, instance=label) - else: - # 🔴 THE DIGEST'S OWN FOOTER PRESCRIBES THESE FLAGS, so the client has to - # have them. It told readers "`--ref ` prints any one of them in - # full; `--limit N` prints them all" while this subcommand exited 2 on - # both — documentation naming a drill-down the shipped binary lacked, - # which sends a reader to a dead end and then to the raw module. - # The mapping and the refusals are `rc`'s, NOT re-derived here: a second - # copy of either is the shape that ends up wrong on one side. - refusal = rc.reject_recall_flags( - ref=args.ref, listing=args.listing, limit=args.limit, page=args.page - ) - if refusal is not None: - print(f"cairn: {refusal}", file=sys.stderr) - return EXIT_USAGE - selection = rc.recall_selection( - listing=args.listing, limit=args.limit, page=args.page - ) - # `--mode` stays authoritative when the caller passed it explicitly: - # it predates these flags and something may already drive it. - mode = args.mode if args.mode != rc.DEFAULT_MODE else selection.mode - # 🔴 THE FEATURED-ENTRY PICK NEEDS A FOCUS WINDOW, AND THIS CLIENT NEVER - # BUILT ONE — so the digest it printed could ONLY ever say - # `most-recent fallback`, whatever was actually relevant. Measured on a - # real store, same repo and same moment: - # client -> "most-recent fallback ... (no handoff doc to read a - # path window from)" - # the module -> "resolved via claudedocs/handoff-.md — 11 of - # 48 quoted path(s) name it" - # The parenthetical was the tell and it was WRONG about the world: there - # was a handoff doc, this client just never looked. That inverted the - # advice everything gives — the wrapper readers are told to run was - # strictly worse than the raw module they are told not to. - # The condition mirrors the module's own: a window is a claim about - # THIS repo's newest handoff doc, so it is meaningless once the caller - # names a scope directly or asks for a non-default mode. - window = ( - rc.focus_window(args.repo) - if mode == rc.DEFAULT_MODE and args.scope is None - else rc.FocusWindow() - ) - # 🔴 REACHABLE ONLY BECAUSE THIS COMMIT EXPOSED `--limit`/`--page`, and - # it was watched: before this guard, `cairn recall --limit 0` raised - # `ValueError: limit must be an int >= 1` as an UNCAUGHT traceback at - # rc 1. The module's own CLI entrypoint has always caught it and - # answered 2 with the message alone; a wrapper that tracebacks where - # the module it wraps explains itself is worse than not offering the - # flag. (Spelled without the callee's name on purpose: a ledger in - # `tests/test_subsystem_read_store.py` greps this file's TEXT to prove - # the client reaches the library and never that entrypoint, and a - # comment quoting it is indistinguishable from a call.) - try: - report = rc.recall( - str(cache), - scope, - ref=args.ref, - ref_to=args.ref_to, - tag=args.tag, - limit=selection.limit, - mode=mode, - page=selection.page, - focus_paths=window.paths, - focus_source=window.source, - ) - except ValueError as exc: - print(f"cairn: {exc}", file=sys.stderr) - return EXIT_USAGE - read_ledger.record(alias, scope) - read_ledger.record_named(alias, report) - text = rc.render_text(report, instance=label) - - # An empty scope reached through a LIVE fetch is `scope-empty`; the same - # emptiness behind a cache stays `cached`, because we did not reach the - # store and cannot claim the emptiness is the store's. - if state == STATE_LIVE and getattr(report, "status", "") in ( - "scope-empty", - "scope-absent", - ): - # 🔴 KEEP `detail`, DO NOT REPLACE IT. The previous version overwrote it - # wholesale, which threw away the server's freshness stamp exactly when - # it mattered most: if the pod could not read a scope, that stamp is - # where `newest=UNREADABLE` appears, and discarding it turned an - # unreadable scope into a confident "nothing recorded". The server now - # 503s on an unreadable scope so this should be unreachable for THAT - # cause — but the evidence stays attached regardless, because "should be - # unreachable" is not a property to bet the silent-zero on. - state = STATE_EMPTY - detail = f"reached the store; nothing recorded for this scope — {detail}" - - print(banner(state, detail, label)) - print() - print(text) - # 🔴 THE READER'S OWN EXIT CODE, PASSED THROUGH. The module docstring - # promised this ("the reader's own non-zero codes pass through unchanged so - # a malformed entry still reports what it always did") while the code - # hardcoded 0. Measured on an all-malformed scope: `subsystem_recall.py` - # exited 3, `cairn recall` exited 0. The stdout text was loud either way, so - # a human was not deceived — but `/resume` step 4 branches on the CODE, and - # a machine consumer was. `_exit_for` is the reader's own decision, reused - # rather than re-derived, exactly as the server does in `_serve_report`. - # `label` is DERIVED, not an attribute — `RecallReport` has no `.label`, and - # assuming it did was an AttributeError that took every recall to exit 1. - # Derived exactly as the server does in `_recall`, so the two agree. - # 🔴 SEARCH USES ITS OWN LABEL. `SearchReport.label` is a property naming the - # scopes SEARCHED; passing the query instead made the reader's failure - # sentence say "`lease` holds 1 entry file" — naming the search term as if it - # were a scope path. The server passes `report.label` for search and derives - # `f"{scope}/"` only for recall; this now matches both. - label = report.label if search is not None else f"{report.scope}/" - return rc._exit_for(report.status, label, report.malformed) - - -def cmd_recall(args: argparse.Namespace) -> int: - return _report(args, search=None) - - -def cmd_search(args: argparse.Namespace) -> int: - return _report(args, search=args.query) - - -def cmd_validate(args: argparse.Namespace) -> int: - """Validate the CACHE with the writer's own parser. - - 🔴 THIS COMMAND NEVER WORKED. It shelled `subsystem_recall.main` with - `--validate`, which is a WRITER-half flag — the reader has no such - option, so every invocation exited 2 with `unrecognized arguments: - --validate`. Worse, the test written to close the "no validate coverage" - gap asserted only that the cache directory was unchanged, so it passed - green over a command that failed on every input. A test that cannot - distinguish "worked" from "exited 2" is not coverage. - - The docstring also claimed "`subsystem_recall.py --validate` already answers - that one", which was the same false belief stated as justification. - """ - # 🔴 ONE INSTANCE, ROUTED BY `--scope`/`--repo` LIKE A READ. Validation is a - # claim about the bytes of a particular cache, so it names which one rather - # than merging several — a merged verdict could not say where the malformed - # file is. - scope = args.scope or _repo_scope(args) - try: - alias, label, cache = ( - _instance_for(args, scope) if scope else _default_instance(args) - ) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - # `scope=None` — see the note in `cmd_sync`. `--scope` still narrows what is - # VALIDATED (below); it must never narrow what is CACHED. - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=alias, - ) - if hint is not None: - print(banner(state, detail, label), file=sys.stderr) - return hint - print(banner(state, detail, label), file=sys.stderr) - # 🔴 THE CACHE IS A MULTI-SCOPE STORE; `--validate` IS SCOPE-BOUND. With no - # `--scope` the writer derives one from the REPO, so `cairn validate` in any - # checkout validated a scope the cache does not hold and printed "NOTHING - # WAS CHECKED — a zero here is NOT a clean bill of health" while exiting 0. - # That is the silent zero this command exists to detect, committed by the - # command itself. With no --scope we validate EVERY scope in the cache. - # - # ⚠ THIS READ OF THE CACHE ROOT IS UNWRAPPED, AND THAT IS NOT CLOSED HERE — - # STATED SO A READER DOES NOT TAKE THE TWO CASES BELOW AS COVERING IT. It is the - # cache ROOT, one level above the scope directories `load_store` walks, so its - # `OSError` is not the `EntryUnreadableError` `main()`'s reader-error arm - # catches. MEASURED at `8ddbb6f`, `--no-sync`, one cache holding one readable - # scope, `chmod` on the ROOT: at mode 0111 (searchable, not readable — the stamp - # `stat` in `resolve_state` succeeds, so execution reaches here) this verb exits - # **1** with a `PermissionError` traceback while the Go client exits **3** - # printing its own raw `open : permission denied`; at 0000/0444 the stamp - # `stat` raises first and every verb is 1 against 3. Both are the cache-ROOT - # depth of `tests/parity/README.md` row 4, which carries them with a closing - # condition. UNGATED. - held = sorted(p.name for p in cache.iterdir() if p.is_dir()) - if args.scope: - # 🔴 THE SILENT ZERO THIS FUNCTION WAS REWRITTEN TO CLOSE, STILL OPEN ON - # THIS BRANCH. The no-scope path was fixed to enumerate the cache; the - # explicit `--scope` path passed the value straight through, so - # `cairn validate --scope no-such-scope` printed the writer's own - # "NOTHING WAS CHECKED — a zero here is NOT a clean bill of health" and - # exited 0. The docstring above names that failure mode verbatim while - # the branch that commits it went unguarded — the fix covered the case - # it was looking at, not the predicate. - if args.scope not in held: - if held: - # The refusal LISTS every scope the cache holds: `*` (Go: `Validate`). - read_ledger.record(alias, read_ledger.ALL_SCOPES) - print( - f"cairn: cache holds no scope {args.scope!r} — " - f"nothing was validated. Held: {', '.join(held) or '(none)'}", - file=sys.stderr, - ) - return EXIT_USAGE - scopes = [args.scope] - else: - scopes = held - if not scopes: - print( - f"cairn: nothing to validate — {cache} holds no scopes", - file=sys.stderr, - ) - return EXIT_UNREACHABLE_NO_CACHE - worst = EXIT_OK - for scope in scopes: - # 🔴 THE RESOLVER IS THE PARSER, so `validate` and `recall` cannot - # disagree about what "malformed" means. This used to shell into a - # separate authoring tool's `--validate`, which was a second - # implementation of the same predicate — exactly the shape that lets a - # file validate clean and then fail to render. - # - # 🔴 AND IT READS THROUGH `load_store`, NOT `load_index` DIRECTLY — A POLICY - # SITE, NOT A SPELLING. `load_index`'s RESIDUAL LEDGER says a `TAKE` kind - # whose `read_text` raises "fails closed into a store-wide - # `EntryUnreadableError`"; that wrap lives in `load_store`, and this line - # used to bypass it, so the ledger's sentence was simply not true of this - # verb. A `chmod 000` entry left a raw `PermissionError` escaping - # `cmd_validate` as a TRACEBACK at exit 1. MEASURED over one scope holding - # one mode-000 entry: `subsystem_recall.py --store ` → 3 with the - # named sentence, `cairn validate` → 1 with a stack trace, the Go client → - # 3. Reading through the ONE function that owns the policy is what makes - # the ledger true here too, instead of a second `except OSError` at this - # site. #111. - _store, index = rc.load_store( - cache, - verb="validated", - visible_scopes=[scope], - ) - read_ledger.record(alias, scope) - malformed = index.malformed - for entry in malformed: - print(f"cairn: {scope}: malformed: {entry}", file=sys.stderr) - # 🔴 REPORT WHAT WAS CHECKED, NOT ONLY WHAT WAS WRONG. Until this line - # a CLEAN scope printed NOTHING and exited 0, which is byte-identical - # to a validate that parsed no files at all — and this command is the - # post-write check the index-write protocol MANDATES, so that zero was - # being read as "the entry I just wrote is fine". The docstring above - # says this command was rewritten to close "the silent zero"; it then - # committed a different one, on the success path instead of the empty - # one. A count that MOVES with the store is what makes the zero mean - # something: parse one entry and it says 1, parse none and it says 0 - # and you can see that it did nothing. - # - # 🔴 `cache`, NOT `args.cache` — AND THIS IS AN AUTHORISED CHANGE TO THE ORACLE. - # P1's rule is that `server/server.py` and this client are the golden source and are - # not edited to make the port agree; the standing exception is a defect the contract - # cannot contain, and it is granted by the OPERATOR, per site, in writing. The - # precedent is `seeded=UNREADABLE` — recorded because "a contract cannot include - # 'sometimes truncate the response mid-stream'". The same sentence applies here: a - # contract cannot include "sometimes print a NEGATIVE count". - # - # `_instance_for` above, `cache.iterdir()` and `load_index(cache, …)` all read the - # ROUTED instance; this one line globbed `args.cache`, the DEFAULT instance's root. - # On a host where `--scope` routes elsewhere the numerator and the denominator came - # from two different stores, so the command whose entire job is to make a zero mean - # something printed `0 of 0 entry file(s) parse, 0 malformed` over a scope holding a - # readable entry — and, with a malformed file in the routed store, `-1 of 0 … 1 - # malformed`, a count below zero. Measured against the Go client over one world: - # `0 of 0` vs `1 of 1` at exit 0, and `-1 of 0` vs `1 of 2` at exit 5. - # - # ⚠ THE EXCEPTION IS THIS LINE AND NOTHING ELSE. It does not license changing the - # oracle to match the port anywhere else, and the scope of it is written down in - # `tests/parity/README.md` beside the `seeded=UNREADABLE` precedent. - # - # 🔴 AND AN EXIT-CODE-ONLY PARITY ROW WOULD HAVE SEEN NEITHER SYMPTOM: both clients - # exit 0 on the clean store and 5 on the malformed one. The count lives on stdout, so - # `validate-routed-to-a-NON-DEFAULT-instance` compares stdout, stderr AND the code. - # - # 🔴 `README.md` IS NOT AN ENTRY, AND THE NUMERATOR ALREADY KNEW THAT. The - # rejections come from `load_index`, which skips `README.md` in every scope - # ("each scope dir carries one as its store-policy sheet"); this count came - # from a bare `*.md` glob that did not. Two walks, one line — and `/snapshot` - # ships those READMEs, so this fired against the real store: a scope holding - # two entries beside its policy sheet printed `3 of 3`, a scope holding ONLY - # a policy sheet printed `1 of 1`, and — the direction that misleads — one - # BROKEN entry beside a README printed `1 of 2 … 1 malformed`, asserting that - # a file parsed when none had. This is the command whose whole job is making - # a zero mean something. - # - # 🔴 THE DENOMINATOR NOW APPLIES THE LOADER'S OWN RULE FOR WHAT AN ENTRY IS, - # THROUGH THE LOADER'S OWN WALK FUNCTION — AND THAT IS ALL IT IS. The first - # fix filtered a `*.md` glob with an open-coded `p.name != "README.md"`, - # which closed the symptom and left the mechanism — two spellings of one - # rule behind one line — intact. `entry_files_in` is the function - # `load_index` enumerates with, so the numerator and the denominator cannot - # come to disagree about what an ENTRY is. - # - # 🔴 THEY CAN STILL DISAGREE ABOUT WHICH DIRECTORIES TO COUNT, AND AN EARLIER - # FORM OF THIS COMMENT CLAIMED OTHERWISE — IT SAID "THE DENOMINATOR IS NOW - # THE LOADER'S OWN WALK", WHICH IS FALSE. It is the loader's RULE over a - # DIFFERENT DIRECTORY SET: `load_index` selects scope directories through - # `visible_scope_set`, which compares `normalize_ref(name)` — FOLDED — so - # every directory whose name normalizes to `--scope`'s value feeds the - # numerator, while this line walks the ONE LITERAL `/` - # directory. MEASURED at this commit on both clients over a cache holding - # `kelp-forest/a.md` and `Kelp_Forest/b.md`, both unparseable: - # - # cairn --cache validate --scope kelp-forest --no-sync - # → cairn: kelp-forest: -1 of 1 entry file(s) parse, 2 malformed (exit 5) - # - # A NEGATIVE count — exactly what the block above calls the thing a contract - # cannot include. PRE-EXISTING and IDENTICAL in both clients, so the parity - # gate is structurally blind to it. Deliberately NOT closed here: deciding - # whether `--scope kelp-forest` means the folded set or the literal directory - # changes a verb's stdout and needs its own change. CLOSING CONDITION — a - # merged PR carrying a test per client that seeds those two directories and - # asserts the printed line, shown RED at this commit; mechanically, - # `python3 -m pytest tests -q -p no:randomly -k fold_vs_literal` and - # `go test ./internal/client/ -run FoldVsLiteral -count=1 -v` each SELECT at - # least one test and exit 0. - # - # ⚠ THIS IS THE SECOND READ OF THE SCOPE DIRECTORY IN THIS LOOP, AND IT IS - # OUTSIDE EVERY WRAP — NOT CLOSED, SO SAID HERE. `load_store` above already - # walked the same directory INSIDE the wrap that produces the named - # `index entry unreadable` sentence, which is why no `chmod` and no static - # world reaches this line: an unreadable or absent directory fails that first - # walk closed and this one is never evaluated. What DOES reach it is the world - # changing mid-run — a concurrent `cairn sync` whose `install_snapshot` - # renames the cache root aside and `rmtree`s the retired one. `entry_files_in` - # now walks with `iterdir()`, so that raises `FileNotFoundError` past - # `main()`'s `(StoreMissingError, ResolverError)` arm as a TRACEBACK at exit - # 1, where the Go client's `EntryFileNames` error is discarded and it prints - # `0 of 0 entry file(s) parse, 0 malformed` at exit 0 (MEASURED at `e162746` - # over one cache holding two scopes, the second removed after the first - # scope's line was printed). UNGATED, and declared in - # `tests/parity/README.md` → "What the gate structurally cannot see". - entry_paths = subsystem_resolver.entry_files_in(cache / scope) - checked = len(entry_paths) - print( - f"cairn: {scope}: {checked - len(malformed)} of {checked} " - f"entry file(s) parse, {len(malformed)} malformed" - ) - # 🔴 THE PARSE COUNT IS NOT THE WRITE-PROTOCOL CHECK, AND UNTIL THESE - # BLOCKS IT WAS THE WHOLE OF WHAT THIS COMMAND REPORTED. "Would the loader - # accept this file?" is answered by the line above; an entry can pass it - # while holding text NO reader will ever surface. `dropped lines:` is the - # half that means content is ALREADY LOST — the file holds it, the store - # holds it, and `--ref`, `--search`, the digest and every openness count - # skip it. A post-write check that cannot see that is checking the parser, - # not the write. - # - # 🔴 THEY SCAN THE MALFORMED FILES TOO, and that is not an oversight: every - # scanner is tolerant by construction (an unreadable file or a missing - # nuance section contributes nothing), and a file the loader rejected can - # still hold lost content that a later fix to its front matter would not - # restore. The rejection above is still the finding that matters, which is - # why these print BELOW it and change no verdict. - # - # 🔴 NEITHER MOVES `worst`. The write protocol branches on this command's - # EXIT CODE to mean "write NOTHING", so failing here would stop a session - # recording anything into an entry whose only defect is that an OLDER - # write lost a line — which makes the store lossier, not safer. A gate an - # author cannot turn green by fixing the file they are writing is worse - # than no gate. - # 🔴 THE ADVISORIES' DENOMINATOR IS `scanned_entry_count`, NOT `checked`, - # AND THAT IS A THIRD SET. `checked` is the LISTING — every `*.md` name in - # the scope directory — which is right for the parse line above, because - # the loader tries every one of them. The scanners do not: they read only - # the kinds the loader's table TAKES, refusing a FIFO, a device, a - # directory or a dangling link before `open()`. Handing them `checked` - # printed a zero over files nothing opened — MEASURED on a scope holding - # one entry beside a FIFO: `dropped lines: 0 across 2 entry file(s)`, one - # of them never read. The FIFO is not lost from the output; the line above - # reports it malformed and drives the exit to 5. - # - # 🔴 FOUR BLOCKS, AND `entry shape:` PRINTS FIRST FOR A REASON THE OTHER - # THREE CANNOT STATE FOR THEMSELVES. All three of the others read only - # `## Nuance / work-history`, so an entry whose heading is RENAMED - # contributes zero to every one of them — `open actions: 0 declared` over a - # section no parser ever reached. The shape block is the one that says why, - # and it has to be ABOVE them to be read as the reason rather than as an - # afterthought. None of the four moves `worst`. - for line in entry_shape.validation_advisory_lines( - n_scanned=entry_shape.scanned_entry_count(entry_paths), - shape=entry_shape.scan_entry_shape(entry_paths), - dropped=entry_shape.scan_dropped_lines(entry_paths), - open_actions=entry_shape.scan_open_actions(entry_paths), - unreachable=entry_shape.scan_unreachable_markers(entry_paths), - ): - # A blank separator stays blank — prefixing it would print a trailing - # `cairn: : ` with nothing after it, and the parity gate would - # then pin that noise in both clients forever. - print(f"cairn: {scope}: {line}" if line else "") - worst = max(worst, EXIT_CORRUPT if malformed else EXIT_OK) - return worst - - -# ============================================================================= -# THE WRITE PATH (criterion 9). Everything above this line reads. -# ============================================================================= -# -# 🔴 WRITE-THROUGH, NO SPOOL, NO CACHE FALLBACK. The pod is the authority; the -# local cache is a read-through copy with no authority of its own. A write that -# cannot reach the pod is REFUSED, loudly, at a non-zero exit — it is never -# queued, never written to the cache, and never reported as done. `/resume` and -# every other READ keeps working offline off the cache; only writes stop. That -# asymmetry is decision 8 in `claudedocs/plan-cairn-integration.md` and the -# reason it is acceptable is that a refused write costs one retry while a -# silently-local write costs the bullet the next `seed.sh` overwrites. -# -# 🔴 THE ACTOR IS NOT SENT AND CANNOT BE. `server._append_bullet` derives it -# from the token that authenticated and DISCARDS any `actor` key in the body. -# This client therefore does not have an `--actor` flag: offering one would -# imply a control the caller does not have. - - -class WriteRefused(Exception): - """The store answered, and the answer is a refusal. Carries its own code. - - 🔴 SEPARATE FROM `StoreUnreachable` FOR THE SAME REASON `StoreCorrupt` IS. - "I could not ask" and "I asked and was told no" have different remedies — - retry vs change the request — and a client that collapses them turns a - permanently-malformed bullet into an infinite retry, or a transient outage - into "the store rejected this, give up". - """ - - def __init__(self, exit_code: int, status: str, detail: str) -> None: - super().__init__(detail) - self.exit_code = exit_code - self.status = status - self.detail = detail - - -# HTTP status -> (our exit code, whether the caller should retry unchanged). -# 🔴 A TABLE, NOT AN `if` LADDER, so `test_every_documented_server_status_maps` -# can walk it against the statuses `server.py` actually emits on a write route. -# An unmapped code is NOT silently treated as success: `_classify` falls through -# to EXIT_WRITE_REFUSED and says the code was unrecognised, which is loud and -# wrong-in-the-safe-direction (the caller is told the write did not land). -_WRITE_STATUS_EXITS: dict[int, int] = { - 400: EXIT_WRITE_REFUSED, # malformed body / ambiguous ref - 401: EXIT_WRITE_REFUSED, # no or bad credential - 403: EXIT_WRITE_REFUSED, # edge refusal (see the User-Agent note) - 404: EXIT_WRITE_REFUSED, # scope-unknown or ref-unknown - 405: EXIT_WRITE_REFUSED, # read-only image: the write path is NOT deployed - 412: EXIT_WRITE_PRECONDITION, # If-Match named a revision the entry no longer has - 422: EXIT_WRITE_REFUSED, # entry-shape: no `## Nuance / work-history` - 428: EXIT_WRITE_REFUSED, # precondition required (a PUT with no If-Match) - 429: EXIT_WRITE_UNREACHABLE, # rate limited — a retry IS the right response - # 🔴 500 IS A RETRY, NOT A "FIX YOUR REQUEST". `server._backstop` turns any - # unhandled handler exception into a 500, so it IS reachable on a write - # route. It was absent here and fell through to `_classify`'s "unrecognised" - # arm, which is EXIT_WRITE_REFUSED — telling the caller to change a - # byte-identical request that would very likely succeed on a retry. The - # fallthrough was labelled "wrong-in-the-safe-direction", and that is true - # for landed/not-landed and FALSE for retry/don't-retry, which is the exact - # distinction 6 and 7 exist to carry. - 500: EXIT_WRITE_UNREACHABLE, - 502: EXIT_WRITE_UNREACHABLE, # a bad gateway is the edge, not the request - 503: EXIT_WRITE_UNREACHABLE, # the server could not read its own store - 504: EXIT_WRITE_UNREACHABLE, -} - - -# 🔴 A SECOND TABLE, KEYED ON THE SERVER'S `X-Store-Status` TOKEN, CONSULTED -# FIRST. It exists because one HTTP status can carry two outcomes with opposite -# remedies: `412` is `precondition-failed` (the entry moved — retry after a -# re-sync) on a `put`, and `already-exists` (it is there — do not retry) on a -# `create`. The code table above cannot express that, and collapsing the two -# would give a `create` caller an exit that says "re-derive and try again" for a -# condition no retry can change. -# -# 🔴 A TOKEN NOT IN THIS TABLE FALLS THROUGH TO THE CODE TABLE, never to a pass. -# The token is advisory routing, not the verdict. -_WRITE_STATUS_TOKEN_EXITS: dict[str, int] = { - "already-exists": EXIT_WRITE_EXISTS, -} - - -def _classify(code: int, status: str, detail: str) -> WriteRefused: - by_token = _WRITE_STATUS_TOKEN_EXITS.get(status) - if by_token is not None: - return WriteRefused(by_token, status, detail) - exit_code = _WRITE_STATUS_EXITS.get(code) - if exit_code is None: - return WriteRefused( - EXIT_WRITE_REFUSED, - status or f"http-{code}", - f"unrecognised HTTP {code} on a write route — treating the write as " - f"NOT LANDED: {detail}", - ) - return WriteRefused(exit_code, status or f"http-{code}", detail) - - -def send_write( - url: str, - token: str, - *, - method: str, - path: str, - body: bytes, - timeout: int, - extra_headers: dict[str, str] | None = None, -) -> tuple[dict[str, str], bytes]: - """One request against a write route. Returns `(headers, body)` on 200. - - Raises `WriteRefused` on any non-200 the server produced, and - `StoreUnreachable` when there was no answer at all. Nothing else escapes. - """ - bad = unbounded_timeout_reason(timeout) - if bad: - # 🔴 THE SAME REFUSAL THE READ PATH MAKES, FOR THE SAME REASON. A - # `timeout=None` reaches `urlopen` as NO timeout, and an unbounded WRITE - # is strictly worse than an unbounded read: the request may already have - # been applied, so a caller that eventually gives up cannot tell whether - # it landed. - raise StoreUnreachable(f"refusing to write to {url}: {bad}") - target = f"{url}{path}" - req = urllib.request.Request(target, data=body, method=method) - _apply_standard_headers(req, token) - req.add_header("Content-Type", "application/json") - for name, value in (extra_headers or {}).items(): - req.add_header(name, value) - try: - with urllib.request.urlopen(req, timeout=timeout) as resp: - # `resp.headers` returned as the Message, never `dict(...)` — see - # `fetch_snapshot` for the measured case-folding incident. - return resp.headers, resp.read() - except urllib.error.HTTPError as exc: - try: - detail = exc.read().decode("utf-8", "replace").strip().replace("\n", "; ") - except Exception: - detail = "" - status = exc.headers.get("X-Store-Status", "") if exc.headers else "" - raise _classify(exc.code, status, detail[:400] or f"HTTP {exc.code}") from exc - except urllib.error.URLError as exc: - raise StoreUnreachable(f"{url} unreachable: {exc.reason}") from exc - except OSError as exc: - raise StoreUnreachable(f"{url} unreachable: {exc}") from exc - - -def _write_scope(args: argparse.Namespace) -> str | None: - """The scope a write targets, or None having already printed why.""" - try: - scope = args.scope or scope_for_repo(args.repo) - except Exception as exc: - print( - f"cairn: could not derive a scope from {args.repo!r}: {exc}\n" - f" pass --scope explicitly.", - file=sys.stderr, - ) - return None - if not scope: - print("cairn: --scope is required (no scope could be derived)", file=sys.stderr) - return None - return scope - - -def cmd_append(args: argparse.Namespace) -> int: - """`POST /api/v1/entry///bullets` — append ONE dated bullet. - - 🔴 THIS IS THE VERB CRITERION 9 ROUTES `subsystem-index` THROUGH. Before it - existed the skill's append was an `Edit` against `~/.claude/analyze-service- - index//.md`, which is local-only: the bullet lived on one host - and the next `seed.sh` from any host replaced the served copy with a file - that never had it. This makes the append land where the authority is. - - 🔴 DO NOT DATE-PREFIX `--text`. The server prepends `- : ` itself; the - first production append through this route reads `- 2026-08-29: 2026-08-29: - …` because a caller did. - """ - scope = _write_scope(args) - if scope is None: - return EXIT_USAGE - # 🔴 REFUSE LOCALLY, BEFORE THE NETWORK, AND SAY THE OVERAGE. The server - # enforces this cap and always did; what it could not do is tell a caller the - # limit before they had composed something over it. Measured cost of that - # asymmetry: one bullet took three full recompose-and-retry cycles because - # the only way to learn the bound was to exceed it, and nothing was written - # on any of the three. - # - # 🔴 SAME CONSTANT AS THE SERVER'S, IMPORTED — not a second 2000 typed here. - # A client-side copy that drifted LOW would refuse writes the store would - # have accepted, which is worse than the round trip it saves, and it would - # fail exactly the way this repo's other two-copy hazards do: silently, with - # both numbers looking deliberate. - # - # ⚠ THIS IS A CONVENIENCE, NOT AN AUTHORITY. The server re-checks; a client - # that skipped the check could not widen what the store accepts. Do not let a - # later refactor read this as the enforcement point. - if len(args.text) > entry_shape.BULLET_TEXT_MAX: - over = len(args.text) - entry_shape.BULLET_TEXT_MAX - print( - f"cairn: refusing to send — `--text` is {len(args.text)} characters, " - f"max {entry_shape.BULLET_TEXT_MAX} — {over} over. Nothing was " - f"written, and the store was not contacted.", - file=sys.stderr, - ) - return EXIT_USAGE - try: - alias, _, _ = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - url, token = load_config(instance=alias) - payload = json.dumps({"text": args.text, "session": args.session}).encode("utf-8") - quoted = f"/api/v1/entry/{quote(scope, safe='')}/{quote(args.ref, safe='')}/bullets" - headers, body = send_write( - url, token, method="POST", path=quoted, body=payload, - timeout=_store_timeout(args), - ) - read_ledger.record(alias, scope) - status = headers.get("X-Store-Status", "unknown") - revision = (headers.get("ETag") or "").strip('"') - # 🔴 `duplicate` IS PRINTED, NOT SWALLOWED, and it exits 0. The server - # recognises a bullet by CONTENT HASH, so a re-POST after a timeout is - # idempotent — which is the property that makes a retry safe. But a caller - # told nothing would read "appended" into a run that wrote nothing, and the - # store's own idempotency note says a genuinely new bullet whose text is - # byte-identical to an existing one is silently NOT appended. Saying which - # of the two happened is the whole difference. - # 🔴 A WRITE ALWAYS NAMES THE INSTANCE IT LANDED ON — unconditionally, where - # a READ names it only when there is more than one. The asymmetry is the - # same one this file already makes everywhere else: a read that degrades is - # recoverable by reading again, while "where did that bullet go" is a - # question about a DURABLE record, asked later, by someone who no longer has - # this terminal. It costs one field and it is the cheap permanent answer. - print( - f"cairn: {status} instance={alias} scope={scope} ref={args.ref} " - f"revision={revision or 'unknown'}" - ) - sys.stdout.write(body.decode("utf-8", "replace")) - return EXIT_OK - - -def cmd_put(args: argparse.Namespace) -> int: - """`PUT /api/v1/entry//` — whole-file replace behind `If-Match`. - - 🔴 WHY A WHOLE-FILE VERB EXISTS AT ALL, given that `append` is the safe one: - the `subsystem-index` protocol also mandates rewriting an existing bullet's - `OPEN:` marker to `RESOLVED :` **in the same edit**, and updating - `## Pointers`. Neither is an append. Without this verb, freezing the local - store read-only would make those two operations impossible rather than - merely relocated — the cutover would REGRESS a documented protocol step. - - 🔴 THE REVISION IS DERIVED FROM A **LIVE** SYNC, NEVER FROM `--no-sync`. - `server.entry_revision` is `sha256(file bytes)[:16]`, so the cache can - compute it offline — which is exactly what makes a stale cache dangerous - here in a way it is not for a read: an edit based on bytes that moved is a - lost update, and the `If-Match` is what turns that into a 412 instead of a - silent overwrite. Deriving it from a cache we did not just refresh would - still be *correct* (the server compares against its own copy) but it wastes - the operator's edit on a guaranteed 412. `--if-match` is accepted for the - case where the caller already holds the value. - """ - scope = _write_scope(args) - if scope is None: - return EXIT_USAGE - # 🔴 READ THE FILE BEFORE THE NETWORK — AND "BEFORE THE NETWORK" MEANS ABOVE - # `resolve_state`, NOT ABOVE `load_config`. The first attempt at this fix - # moved the read up only as far as the config load, which is a local file - # read, so the full snapshot download still ran first: a missing `--file` - # went on reporting the STORE AS UNREACHABLE (rc 7) instead of "cannot read - # --file" (rc 2). The comment claimed the ordering, and the test that - # asserted it did so in its NAME while its body checked only the exit code - # and the sentence — both of which held with the read left where it was. A - # guard's description claiming coverage its body does not provide is the - # shape that stops anyone looking. - try: - payload = args.file.read_bytes() - except OSError as exc: - print(f"cairn: cannot read --file {args.file}: {exc}", file=sys.stderr) - return EXIT_USAGE - revision = args.if_match - try: - alias, _, cache = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - if not revision: - state, detail, hint = resolve_state( - cache, no_sync=False, scope=None, timeout=_store_timeout(args), - instance=alias, - ) - if state != STATE_LIVE: - # 🔴 NOT "served from cache". A read may degrade; deriving a - # precondition from bytes we could not confirm is the one case where - # the cache is worse than nothing. - # - # 🔴 AND NOT `hint`. This returned `hint if hint is not None else - # EXIT_WRITE_UNREACHABLE`, and `resolve_state` sets `hint` to - # EXIT_UNREACHABLE_NO_CACHE (3) exactly when there is NO cache — - # which is the FIRST run on a fresh host, i.e. the commonest way to - # get here. So the one code this whole file insists a write must - # never return was returned by a write, on its likeliest path, while - # four separate comments and the design doc said it could not - # happen. `hint` is a READ verdict — "this is what a reader should - # exit with" — and it has no meaning for a write. Measured before - # the fix: put with no cache -> 3, put with a cache -> 7, append - # with no cache -> 7. - print( - f"🔴 cairn: refusing to PUT — could not refresh the cache, so the " - f"revision would be derived from bytes that may have moved " - f"({detail}). Nothing was queued and nothing was written locally. " - f"Pass --if-match explicitly if you already hold it.", - file=sys.stderr, - ) - return EXIT_WRITE_UNREACHABLE - matches = sorted(cache.glob(f"{scope}/{args.ref}.md")) or sorted( - cache.glob(f"{scope}/{args.ref}.*.md") - ) - if len(matches) != 1: - print( - f"cairn: cannot derive a revision — {len(matches)} cached file(s) " - f"match {scope}/{args.ref}. Pass --if-match, or use the entry's " - f"exact filename stem as --ref.", - file=sys.stderr, - ) - return EXIT_USAGE - revision = hashlib.sha256(matches[0].read_bytes()).hexdigest()[:16] - print(f"cairn: derived If-Match {revision} from the live snapshot", file=sys.stderr) - url, token = load_config(instance=alias) - quoted = f"/api/v1/entry/{quote(scope, safe='')}/{quote(args.ref, safe='')}" - headers, body = send_write( - url, token, method="PUT", path=quoted, body=payload, - timeout=_store_timeout(args), - extra_headers={"If-Match": f'"{revision}"'}, - ) - read_ledger.record(alias, scope) - new_rev = (headers.get("ETag") or "").strip('"') - # The instance is named unconditionally — see `cmd_append`. - print( - f"cairn: {headers.get('X-Store-Status', 'unknown')} instance={alias} " - f"scope={scope} ref={args.ref} revision={new_rev or 'unknown'}" - ) - sys.stdout.write(body.decode("utf-8", "replace")) - return EXIT_OK - - -def cmd_create(args: argparse.Namespace) -> int: - """`PUT /api/v1/entry//` with `If-None-Match: *` — a NEW entry. - - 🔴 WHY THIS VERB EXISTS, since `append` and `put` already write. Neither can - make an entry that is not there: both resolve an EXISTING ref and 404 when it - is absent. So the protocol told a session to write a brand-new entry into - `~/.claude//` directly — which was true and safe while - that tree WAS the store, and became content loss the moment reads moved to - the pod cache: measured, five whole entries existed only on one - host and were dark to every reader. This is the verb that closes it. - - 🔴 NO `--if-match`, AND NO SYNC. `put` derives a precondition from a LIVE - snapshot because it is editing bytes that may have moved; a create has no - prior bytes, and its precondition is the constant `*`. The server decides - absence under its own lock, so there is nothing a local cache read could add - except a stale answer and a wasted round trip. - - 🔴 EXIT 9 IS NOT A FAILURE TO RETRY. It means the entry already exists and - NOTHING was written — the remedy is `cairn append` (a bullet) or `cairn put` - (a rewrite), never the same `create` again. - """ - scope = _write_scope(args) - if scope is None: - return EXIT_USAGE - # 🔴 READ THE FILE BEFORE THE NETWORK, for the reason `cmd_put`'s comment - # gives at length: an unreadable `--file` must report itself (rc 2) and not - # be reported as the store being unreachable. - try: - payload = args.file.read_bytes() - except OSError as exc: - print(f"cairn: cannot read --file {args.file}: {exc}", file=sys.stderr) - return EXIT_USAGE - try: - alias, _, _ = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - url, token = load_config(instance=alias) - quoted = f"/api/v1/entry/{quote(scope, safe='')}/{quote(args.ref, safe='')}" - headers, body = send_write( - url, token, method="PUT", path=quoted, body=payload, - timeout=_store_timeout(args), - extra_headers={"If-None-Match": "*"}, - ) - read_ledger.record(alias, scope) - revision = (headers.get("ETag") or "").strip('"') - # The instance is named unconditionally — see `cmd_append`. - print( - f"cairn: {headers.get('X-Store-Status', 'unknown')} instance={alias} " - f"scope={scope} ref={args.ref} revision={revision or 'unknown'}" - ) - sys.stdout.write(body.decode("utf-8", "replace")) - return EXIT_OK -# ============================================================================= -# DOCTOR. Reads everything, installs nothing. -# ============================================================================= - - -def _cairn_doctor(): - """The `doctor` module, imported inside a function — see `_doctor_epilog`. - - ⚠ NOT "lazily", in effect. `build_parser` calls `_doctor_epilog()` to build - the help text, so this runs on EVERY invocation of every subcommand. Saying - otherwise is a cost model a maintainer would reason from and be wrong. - """ - lib = str(Path(__file__).resolve().parent / "lib") - if lib not in sys.path: - sys.path.insert(0, lib) - import cairn_doctor # noqa: PLC0415 - - return cairn_doctor - - -#: How an operator reads the identity and the DECLARED allowlist behind a token. -#: Spelled once, printed by `doctor`, and pinned by -#: `test_cairn_doctor.py::test_the_identity_remedy_names_the_pods_own_token_file` -#: against `server.DEFAULT_TOKEN_FILE`, so it cannot drift from the path the pod -#: actually mounts. 🔴 It is a REMEDY, not a step this command takes: `doctor` -#: never reads a secret and never shells `kubectl`. -IDENTITY_REMEDY = ( - "`kubectl -n subsystem-store exec deploy/subsystem-store-api -- " - "cut -d' ' -f2,3 /run/secrets/subsystem-store/token` " - "(fields 2 and 3 are the identity and the allowlist; field 1 is the secret)" -) - - -def probe_store(url: str, token: str, *, timeout: int): - """ONE snapshot fetch, read for facts and THROWN AWAY. Never installed. - - 🔴 IT REUSES `fetch_snapshot` RATHER THAN BUILDING A SECOND REQUEST. That - keeps `_apply_standard_headers` — and the measured User-Agent requirement - behind it — on this path without a second site to forget it at, and it is - what `test_cairn_write.py::test_no_request_builder_ANYWHERE_bypasses_this_ - helper` would otherwise have to grow a case for. - - 🔴 IT NEVER CALLS `install_snapshot`. A diagnostic that repaired the cache - would destroy the staleness it was run to measure. - """ - doctor = _cairn_doctor() - try: - # 🔴 IT SENDS NO VALIDATOR, AND THE OMISSION IS THE WHOLE STATEMENT. A - # conditional probe could be answered 304, and this function's entire - # job is to COUNT WHAT THE POD WOULD SEND — visible scopes and visible - # entries, read out of the archive itself. A diagnostic that accepted - # "nothing changed" would report the cache's contents as the pod's and - # call the two in agreement by construction, which is the shape of check - # that agrees with itself. - body, headers, _not_modified = fetch_snapshot( - url, token, scope=None, timeout=timeout - ) - except StoreUnreachable as exc: - return doctor.PodFacts( - reached=False, reason=str(exc), http_status=exc.http_status - ) - - visible = headers.get("x-store-entries") - snapshot = headers.get("x-store-snapshot", "") - scopes: set[str] = set() - try: - with tarfile.open(fileobj=io.BytesIO(body), mode="r") as tar: - for member in tar.getmembers(): - if not member.isfile(): - continue - parts = Path(member.name).parts - if len(parts) == 2 and parts[1].endswith(".md"): - scopes.add(parts[0]) - except (tarfile.ReadError, EOFError, zlib.error) as exc: - return doctor.PodFacts( - reached=False, - reason=f"{url} answered, but the archive could not be read: {exc}", - ) - - # 🔴 `entry-files=` OUT OF THE STORE-WIDE HEADER, and the store-wide-ness is - # the point. `server.snapshot_freshness` counts the WHOLE served store, not - # the caller's slice — a documented, deliberate residual count leak — so the - # gap between it and `X-Store-Entries` is the only client-side evidence that - # entries exist which this credential cannot reach. - store_wide = None - for field in snapshot.split(): - key, _, value = field.partition("=") - if key == "entry-files" and value.isdigit(): - store_wide = int(value) - - # 🔴 NO FALLBACK TO THE ARCHIVE'S OWN COUNT. Without `X-Store-Entries` the - # only number available is how many members ARRIVED, which is exactly the - # side of the comparison a truncated transfer moves — substituting it would - # make the cache-vs-pod check agree with itself and report OK over a short - # answer. `install_snapshot` cross-checks against this header for the same - # reason. Absent header => the count is UNMEASURED, with that as the stated - # reason. - return doctor.PodFacts( - reached=True, - visible_entries=int(visible) if visible and visible.isdigit() else None, - store_wide_entries=store_wide, - visible_scopes=tuple(sorted(scopes)), - snapshot_header=snapshot, - ) - - -def cmd_doctor(args: argparse.Namespace) -> int: - """One call for every fact a reader otherwise assembles by hand. - - 🔴 EVERY CONFIGURED INSTANCE, CHECKED SEPARATELY, SO A HEALTHY ONE CANNOT - MASK A BROKEN ONE. The checks are per-instance rows rather than a merged - verdict, and the exit code is the WORST of them: one reachable store must - never make a second one that is down look measured. On a host with one - instance the rows are exactly what they always were — no prefix, no extra - section — because there is nothing to disambiguate. - """ - doctor = _cairn_doctor() - routing = _routing() - refusal = _refuse_shared_cache(args, routing, "doctor") - if refusal is not None: - return refusal - # `*`: per-scope visibility and counts name every scope (decision 3a). - read_ledger.record("", read_ledger.ALL_SCOPES) - checks: list = [] - for instance in routing.instances: - checks.extend(_doctor_instance(args, doctor, routing, instance)) - if args.json: - print(json.dumps(doctor.to_dict(checks), indent=2)) - else: - print(doctor.render(checks)) - return doctor.exit_code(checks) - - -def _doctor_instance(args, doctor, routing, instance) -> list: - """The checks for ONE instance, named after it when this host is routing. - - 🔴 THE NAME CARRIES THE ALIAS, NOT THE DETAIL TEXT. `doctor --json` is - consumed by machine and `render` aligns on the name column, so an alias - buried in prose would be unreadable to both. `/` keeps every - row addressable and sorts together. - """ - resolved = _read_store.resolve_read_store( - None if instance.is_default else _read_store.cache_root_for(instance.alias) - ) - - # 🔴 THE CONFIG LOAD HAPPENS EVEN UNDER `--no-sync`, AND THAT IS A FIX. It is - # a local file read, so "is a credential configured on this host" is - # answerable with the network switched off — and the first version skipped it, - # which made `doctor --no-sync` report `token PROBLEM: no token is configured` - # on a host whose token was sitting in `~/.config/subsystem-store/env` - # unread. A check that says PROBLEM about something it never looked at is the - # same defect as one that says OK about it. - token: str | None = None - token_reason = "" - try: - url, token = load_config(instance=instance.alias) - except StoreUnreachable as exc: - token_reason = str(exc) - config_error: str | None = str(exc) - else: - config_error = None - - if args.no_sync: - pod = doctor.PodFacts( - reached=False, - reason="--no-sync was given, so the store was never contacted", - ) - elif config_error is not None: - pod = doctor.PodFacts(reached=False, reason=config_error) - else: - pod = probe_store(url, token, timeout=_store_timeout(args)) - - checks = doctor.collect( - resolved_root=resolved.root, - stamp_lines=resolved.stamp, - stamp_reason=resolved.reason, - cache_root=_instance_cache(args, instance.alias), - # 🔴 THE FROZEN MIRROR BELONGS TO THE DEFAULT INSTANCE ALONE. It is the - # pre-cutover local store this host migrated FROM, so there is exactly - # one of it however many instances are configured; reporting it under - # each would state one fact N times and make N-1 of the rows a claim - # about a directory that instance has nothing to do with. - mirror_root=_mirror_root() if instance.is_default else None, - pod=pod, - token=token, - token_reason=token_reason, - identity_remedy=IDENTITY_REMEDY, - ) - if not routing.multi_instance: - return checks - return [ - type(check)(f"{instance.alias}/{check.name}", check.state, check.detail) - for check in checks - ] - - - - -def _store_timeout(args: argparse.Namespace) -> int: - """The store commands' bound, resolved in ONE place. - - 🔴 THE SENTINEL CREATED FOUR CHANCES TO FORGET. Making the top-level - `--timeout` default to `None` (so `who` can tell "not given" from an - explicit value) meant every store call site had to resolve it, and mutating - all four to pass the raw `None` through kept the whole suite green — a - `None` reaches `urllib` as NO timeout, the same unbounded wait `_run` - already refuses on the other side of this file. One resolver, four callers, - and `test_no_call_site_passes_the_RAW_sentinel_attribute` pins that no - fifth caller open-codes it, while - `test_every_STORE_subcommand_reaches_the_network_with_a_POSITIVE_bound` - covers the spellings an AST scan cannot see. `fetch_snapshot` refuses a - non-positive bound outright, so a future caller that bypasses both - fails closed rather than waiting forever. - """ - return int(args.timeout) if getattr(args, "timeout", None) is not None else DEFAULT_TIMEOUT - - - - - - - - -def _doctor_epilog() -> str: - """`doctor --help`'s exit-code legend, read from the module that owns it. - - 🔴 READ, NEVER RESTATED. A second copy of the legend in this file — or in a - SKILL.md — is a second thing to keep true, and the numbers are the part a - caller branches on. `cairn_doctor.EXIT_LEGEND` is the one definition; both - `--help` and every run's own output render it from there. - - ⚠ CALLED EAGERLY FROM `build_parser`, AND THE COMMENT THAT SAID OTHERWISE WAS - FALSE IN EFFECT. `argparse` wants `epilog` as a string, so `cairn_doctor` is - imported on EVERY invocation — the same trap the lazy-import docstring - records for `_who_default_timeout`. The import stays function-scoped for - honesty about what this file needs to START, not as an optimisation. - - 🔴 AND IT FAILS SOFT — FOR AN `ImportError`, WHICH IS NOT THE SAME AS "FOR A - BROKEN `cairn_doctor`". With `cairn_doctor.py` missing, an eager unguarded - import took `cairn ls-entries` — a subcommand that has nothing to do with - doctor — down with `ModuleNotFoundError` at exit 1, traceback and all. - `cmd_doctor` still fails LOUDLY, because that is the caller who asked for it; - an unrelated verb must not inherit the blast radius of a help string. - - ⚠ AND THE GUARANTEE STOPS AT THE `except` CLAUSE BELOW, so do not read the - paragraph above as "any broken doctor module is contained". A module that is - PRESENT but UNPARSEABLE raises `SyntaxError`, which is not an `ImportError`: - nothing here catches it, it propagates out of `build_parser`, and every verb - dies with it. Measured on a tree with `lib/cairn_doctor.py` replaced by - `def broken(` — `cairn doctor`, `cairn ls-entries`, `cairn ls-entries --help` - and `cairn --help` are ALL exit 1 with `SyntaxError`. Control on the - `ImportError` path, same tree with the file merely absent: the same four are - 1 / 3 / 0 / 0, and that 3 is the ordinary no-cache read outcome an untouched - tree gives for `ls-entries`, so the soft-fail is real — it is just narrower - than "fails soft". The epilog STRING below is accurate about this because it - only ever renders on the `ImportError` path; on the `SyntaxError` path there - is no parser to attach an epilog to. - - 🔴 WIDENING THIS `except` IS NOT THE OBVIOUS FIX. Catching `SyntaxError` here - would make `--help` render for every verb over a module that `cmd_doctor` is - about to die on, and the loud failure is the point of the design. This is - recorded, deliberately, rather than closed. - """ - try: - doctor = _cairn_doctor() - except ImportError as exc: - return ( - f"exit codes: UNAVAILABLE — `cairn_doctor` could not be imported " - f"({exc}). `cairn doctor` itself will fail with this; every other " - f"subcommand is unaffected." - ) - lines = ["exit codes:"] - lines += [f" {code} {why}" for code, why in doctor.EXIT_LEGEND] - lines.append("") - lines.append( - "check states: " - + ", ".join(doctor.STATES) - + " — UNMEASURED means the check could not look and says why; " - "NOT-OBSERVABLE means no client can answer it at all and names who can." - ) - return "\n".join(lines) - - -def cmd_routes(args: argparse.Namespace) -> int: - """Print the routing table, and grade it against what is actually there. - - 🔴 THE TABLE IS AN INPUT, NOT A CONSTANT IN THIS REPOSITORY, AND THAT IS A - DELIBERATE SEPARATION. A client that shipped somebody's scope->instance map - would be publishing their taxonomy; this program knows how to route and - nothing about who routes where. So the mechanism lives here and the table - lives wherever the operator keeps it — which makes THIS command the only - place the two meet, and the reason it grades rather than merely prints. - - 🔴 IT GRADES IN BOTH DIRECTIONS. A scope with no entry refuses its next - write — loud. An entry naming a scope that exists nowhere is the silent one: - it reads as coverage and survives a rename. See `Routing.check`, which asks - `Routing.alias_for` for the third direction rather than re-deriving it. - """ - routing = _routing() - # `*`: the table names every routed scope (decision 3a). - read_ledger.record("", read_ledger.ALL_SCOPES) - print(f"instances: {', '.join(routing.aliases)}") - if routing.routes is None: - print( - "routes: NONE configured — every scope resolves to " - f"`{_read_store.DEFAULT_ALIAS}`" - if not routing.multi_instance - else "routes: NONE configured, and this host has more than one " - "instance, so EVERY scope refuses until a table exists" - ) - if not args.check: - return EXIT_OK - return EXIT_OK if not routing.multi_instance else EXIT_UNROUTED - print(f"routes: {routing.routes_source}") - for scope in sorted(routing.routes): - print(f" {scope} -> {routing.routes[scope]}") - if not args.check: - return EXIT_OK - - refusal = _refuse_shared_cache(args, routing, "routes --check") - if refusal is not None: - return refusal - # 🔴 THE SCOPE SET IS READ FROM THE INSTANCES THEMSELVES, REFRESHED FIRST. - # Grading a table against a stale cache invents both kinds of finding: a - # scope added elsewhere reads as "the table does not name it", and a scope - # deleted elsewhere reads as "the table names a scope that does not exist". - # An instance that cannot be refreshed is therefore named, and the check - # REFUSES rather than grading against what happens to be on this disk. - # - # 🔴 AND THE BANNER IS LABELLED ONLY WHEN THERE IS MORE THAN ONE INSTANCE, - # like every other read in this file. This loop used to pass the alias - # unconditionally, which made `routes --check` the ONE command that printed - # `cairn[personal]:` on a host with a single store — found by diffing this - # verb against its Go port rather than by any test, because no test asserted - # the banner here at all. - scopes: set[str] = set() - for instance in routing.instances: - label = instance.alias if routing.multi_instance else None - cache = _instance_cache(args, instance.alias) - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=instance.alias, - ) - print(banner(state, detail, label), file=sys.stderr) - if hint is not None or state != STATE_LIVE: - print( - f"🔴 cairn: REFUSING to grade the table — instance " - f"`{instance.alias}` was not read LIVE, and a table graded " - f"against a stale or absent cache reports findings in both " - f"directions that are facts about this disk rather than about " - f"the table.", - file=sys.stderr, - ) - return EXIT_UNROUTED - # ⚠ THIS CACHE-ROOT LISTING IS UNWRAPPED, like `cmd_validate`'s `held` — its - # `OSError` escapes `main()`'s `(StoreMissingError, ResolverError)` arm as a - # traceback rather than the reader's named sentence. `--no-sync` cannot reach it - # (the `state != STATE_LIVE` guard above returns first), but a **304 Not - # Modified** does: `resolve_state` returns `STATE_LIVE` and writes nothing, so - # the root listed here is the pre-existing one, mode bits and all. MEASURED - # against a stub pod answering 304, cache root at 0111: this client exits **1** - # with a `PermissionError` traceback, the Go client **3** with its own raw - # `open : permission denied`. UNGATED, and the cache-ROOT depth of - # `tests/parity/README.md` row 4. - scopes.update(p.name for p in cache.iterdir() if p.is_dir()) - problems, notes = routing.check(scopes) - for problem in problems: - print(f"🔴 cairn: {problem}", file=sys.stderr) - # ⚠ NOTES CARRY A DIFFERENT MARKER AND DO NOT MOVE THE EXIT CODE. A finding - # the available evidence cannot decide must not fail a gate: `Routing.check` - # names the one direction that is undecidable from a snapshot, and printing - # it at 🔴 exit 11 is what made `routes --check` refuse every table that - # pre-registered a scope — which is the two-way registry this verb exists - # for. Printed AFTER the problems so a real finding is never buried. - for note in notes: - print(f"⚠ cairn: {note}", file=sys.stderr) - print( - f"routes: {len(routing.routes)} entr" - f"{'y' if len(routing.routes) == 1 else 'ies'}, {len(scopes)} scope(s) " - f"across {len(routing.instances)} instance(s), {len(problems)} problem(s), " - f"{len(notes)} note(s)" - ) - return EXIT_UNROUTED if problems else EXIT_OK - - -class _ExplicitCache(argparse.Action): - """Record that `--cache` was GIVEN, not merely defaulted. - - 🔴 THE DEFAULT AND AN EXPLICIT VALUE EQUAL TO IT ARE DIFFERENT FACTS, and - comparing the value against the default cannot tell them apart. With more - than one instance the default must be resolved PER INSTANCE while an - explicit `--cache` pins one directory, so the difference decides whether a - fan-out is allowed at all. - """ - - def __call__(self, parser, namespace, values, option_string=None): # noqa: D102 - setattr(namespace, self.dest, values) - namespace.cache_explicit = True - - -def build_parser() -> argparse.ArgumentParser: - p = argparse.ArgumentParser( - prog="cairn", - description=( - "Read-through client for the hosted subsystem store. Syncs a local " - "cache and runs the UNMODIFIED local reader against it, so a recall " - "never depends on the network and never reports an unreachable " - "store as an empty one." - ), - ) - # Resolved at parser-BUILD time through the accessor, so the module global - # stays the single point of truth and a test can repoint reader and writer - # together with one assignment. - p.add_argument( - "--cache", type=Path, default=_read_store.read_store_root(), - action=_ExplicitCache, - ) - # The flag's own default lives here rather than on the action, because an - # Action only runs when the option APPEARS. - p.set_defaults(cache_explicit=False) - # `None` = not given, resolved to `DEFAULT_TIMEOUT` by `_store_timeout`, - # which is the ONLY resolver — there is no second, longer default. - # (This comment used to promise one, naming a subcommand and a helper that - # were both removed before this repo was published — two symbols that have - # never existed here. A comment is a claim, and one pointing at absent - # symbols sends a reader hunting a timeout path that is not there. The - # removed names are deliberately not repeated: the closing condition for - # this fix is that they grep to zero in this file.) - p.add_argument("--timeout", type=int, default=None) - sub = p.add_subparsers(dest="cmd", required=True) - - def common(sp): - sp.add_argument("--scope", default=None) - sp.add_argument("--repo", default=".") - sp.add_argument( - "--no-sync", - action="store_true", - help="skip the network entirely and read the cache as it stands", - ) - return sp - - s = sub.add_parser("sync", help="refresh the local cache from the pod") - s.add_argument("--scope", default=None) - s.set_defaults(func=cmd_sync) - - r = common(sub.add_parser("recall", help="the scope's digest")) - r.add_argument("--mode", default=rc.DEFAULT_MODE) - # The digest's footer names `--ref` and `--limit` by hand; `--list` and - # `--page` are the other two the reader has always had. All four are - # forwarded to `rc`, never re-implemented — see `cmd_recall`. - r.add_argument( - "--ref", - default=None, - help="surface ONE entry by ref instead of the whole scope", - ) - # 🔴 `--ref-to`, AND THE SPELLING IS THE POINT. `--ref` names an ENTRY; this names - # something an entry POINTS AT, and the two compose. The pod's parameter is `?ref-to=` - # — the same spelling — because `?ref=` already means `--ref` there and redefining it - # would break a pinned contract. Both clients carry this flag or `tests/parity/` reds. - r.add_argument( - "--ref-to", - default=None, - metavar=":", - help="only entries whose `refs:` carries this ref (the REVERSE lookup)", - ) - # 🔴 SCALAR, AND LAST-WINS LIKE EVERY OTHER VALUE-BEARING FLAG HERE — an OPERATOR DECISION - # rather than a gate. A repeatable `--tag` with AND semantics shipped first; nobody had - # asked for the repetition, and the choice between AND and OR had no author of record, so - # the surface is one tag. `default=None` and not `""`: `rc.recall` refuses an operand that - # folds away, and `--tag ''` must reach that refusal rather than read as "no filter" — so - # absent and empty have to stay distinguishable all the way into the option ladder. - r.add_argument( - "--tag", - default=None, - metavar="", - help="only entries whose `tags:` carries this tag", - ) - r.add_argument( - "--list", - action="store_true", - dest="listing", - help="the INDEX ONLY: one line per entry, never a body, never truncated", - ) - r.add_argument( - "--limit", - type=int, - default=None, - help="print up to N entry BODIES instead of the default digest", - ) - r.add_argument( - "--page", - type=int, - default=None, - help="which page of the INDEX to list, 1-based", - ) - r.set_defaults(func=cmd_recall) - - q = common(sub.add_parser("search", help="search the scope for hunks")) - q.add_argument("query") - q.add_argument("--all-scopes", action="store_true") - # The same flag `recall` carries, for the same reason. Searching within the entries - # that reference one task is the narrowing a reverse lookup is usually wanted for. - q.add_argument( - "--ref-to", - default=None, - metavar=":", - help="only entries whose `refs:` carries this ref (the REVERSE lookup)", - ) - # The same scalar `--tag` `recall` carries, for the same reason. Searching within one - # category is the narrowing the key exists for. - q.add_argument( - "--tag", - default=None, - metavar="", - help="only entries whose `tags:` carries this tag", - ) - q.set_defaults(func=cmd_search) - - v = common(sub.add_parser("validate", help="the post-write check: parse, dropped lines, marker reachability")) - v.set_defaults(func=cmd_validate) - - e = common(sub.add_parser("ls-entries", help="one `/.md` per line")) - e.set_defaults(func=cmd_ls_entries) - - # 🔴 `doctor` TAKES NO `--scope`/`--repo` AND IS NOT `common()`. It asks about - # THIS HOST and THIS CREDENTIAL, not about a scope, and a `--scope` here would - # invite the filtered-cache mistake `cmd_sync` documents. `--no-sync` it does - # take: "diagnose without touching the network" is a real mode, and it turns - # every pod-dependent check UNMEASURED with that as the stated reason rather - # than reporting a zero. - # - # 🔴 ITS EXIT CODES ARE DOCUMENTED BY THE COMMAND. `cairn_doctor.EXIT_LEGEND` - # is printed at the foot of every human-readable run and carried in `--json`, - # so no skill has to restate them and none can restate them wrongly. - d = sub.add_parser( - "doctor", - help="one call: pod reachability, credential, cache stamp, counts, " - "scope visibility, and which store this host's reader resolves", - epilog=_doctor_epilog(), - formatter_class=argparse.RawDescriptionHelpFormatter, - ) - d.add_argument("--json", action="store_true") - d.add_argument( - "--no-sync", - action="store_true", - help="do not contact the store; pod-dependent checks report UNMEASURED", - ) - d.set_defaults(func=cmd_doctor) - - ro = sub.add_parser( - "routes", - help="print the scope->instance table, and grade it against reality", - ) - ro.add_argument( - "--check", action="store_true", - help="grade the table BOTH ways and exit non-zero on any problem", - ) - ro.add_argument( - "--no-sync", action="store_true", - help="do not refresh first (--check then refuses: see cmd_routes)", - ) - ro.set_defaults(func=cmd_routes) - - # --- the write verbs ----------------------------------------------------- - # 🔴 `writes=True` IS NOT DECORATION. `main` maps a `StoreUnreachable` to - # exit 3 ("store-unreachable, no cache"), which is a READ verdict and reads - # as "nothing was shown". For a write the honest code is 7 — the record was - # NOT made — and the two must not share a number, because the whole point of - # write-through is that a caller can tell a failed write from a stale read. - # 🔴 NEITHER TAKES `--no-sync`. It would be meaningless on `append` and - # actively harmful on `put` (see that function on deriving a precondition - # from bytes we did not confirm), so it is absent rather than refused. - ap = sub.add_parser( - "append", - help="append ONE dated, attributed bullet to an entry (writes to the pod)", - ) - ap.add_argument("--scope", default=None) - ap.add_argument("--repo", default=".") - ap.add_argument("--ref", required=True, help="the entry: a filename stem or an alias") - # 🔴 THE LIMIT IS IN THE HELP because the only other way to learn it was to - # exceed it. Interpolated from the shared constant, never typed — a help - # string quoting a stale number is the same drift as a second copy of the - # constant, and harder to notice because nothing tests prose. - ap.add_argument( - "--text", required=True, - help="the bullet, ONE line, with NO leading `- ` and NO leading date — " - "the server adds both; max " - f"{entry_shape.BULLET_TEXT_MAX} characters", - ) - # 🔴 REQUIRED, WITH NO DEFAULT AND NO ENV FALLBACK. The server refuses a - # request without it (400), and criterion 4 is that every appended bullet - # records the actor AND the session. A default would be a value nobody - # chose, attached to a durable record; an env fallback would silently - # attribute one agent's bullet to whatever the shell last exported. - ap.add_argument("--session", required=True, help="the writing session's id") - ap.set_defaults(func=cmd_append, writes=True) - - pu = sub.add_parser( - "put", help="replace a whole entry behind an If-Match precondition" - ) - pu.add_argument("--scope", default=None) - pu.add_argument("--repo", default=".") - pu.add_argument("--ref", required=True) - pu.add_argument("--file", type=Path, required=True, help="the new entry bytes") - pu.add_argument( - "--if-match", default=None, dest="if_match", - help="the entry revision this edit is based on; derived from a LIVE " - "sync when omitted", - ) - pu.set_defaults(func=cmd_put, writes=True) - - # 🔴 `create` IS THE THIRD WRITE VERB AND THE ONLY ONE THAT CAN MAKE AN - # ENTRY. `append` and `put` both resolve an existing ref; before this the - # protocol's only route to a new entry was a local write into the frozen - # mirror, which no reader sees. It takes no `--if-match` (there are no prior - # bytes) and no `--no-sync` (it reads no cache at all). - cr = sub.add_parser( - "create", - help="create a NEW entry that does not exist yet (refuses to overwrite)", - ) - cr.add_argument("--scope", default=None) - cr.add_argument("--repo", default=".") - cr.add_argument( - "--ref", required=True, - help="the new entry's filename stem — it becomes `.md` in the scope", - ) - cr.add_argument("--file", type=Path, required=True, help="the new entry bytes") - cr.set_defaults(func=cmd_create, writes=True) - - return p - - -def main(argv: Sequence[str] | None = None) -> int: - # 🔴 BEFORE `parse_args`, SO `--help` WARNS TOO, AND BECAUSE THE POSITION IS COMPARED. - # `tests/parity/harness.py` diffs this client's stderr against the Go client's - # byte-for-byte, and `internal/client.Run` emits the same sweep before ITS `Parse`. - # After `parse_args` the notice would land after argparse's usage error on this side - # and before the Go client's on the other. - # - # The FILE-key half cannot happen here — the config path is not known until an alias - # has been resolved — so `load_config` emits that half through the same sink. - _warn_deprecations(env_aliases.deprecations(os.environ)) - - args = build_parser().parse_args(argv) - if not hasattr(args, "no_sync"): - args.no_sync = False - # 🔴 AFTER `parse_args`, so a usage refusal (argparse exits 2 above) cannot record. - read_ledger.begin(args.cmd) - try: - return args.func(args) - except cairn_instances.UnroutedScope as exc: - # A backstop, not the primary path: every call site that can raise this - # catches it where the remedy is clearest. Here so a future verb that - # forgets cannot turn a routing refusal into a traceback at exit 1. - return _unrouted(exc) - except cairn_instances.RoutingConfigError as exc: - # 🔴 THE SAME CODE AS AN UNROUTED SCOPE, DELIBERATELY. Both mean "this - # client could not decide which instance to use and did nothing"; the - # remedy for both is a file the operator owns. A second code would ask - # every consumer to learn a distinction neither of them can act on - # differently. - print(f"🔴 cairn: REFUSING — {exc}", file=sys.stderr) - return EXIT_UNROUTED - except WriteRefused as exc: - # 🔴 THE STORE ANSWERED, AND THE ANSWER IS NO. Printed with the server's - # own `X-Store-Status`, because that token is what distinguishes the four - # 404s from each other (`scope-unknown` vs `ref-unknown`) and a 405 - # (`read-only`) — which is the one that means "the write path is not - # deployed on the running image", i.e. an operator problem and not a - # caller problem, and which reads exactly like a wrong URL. - print( - f"🔴 cairn: the store REFUSED the write [{exc.status}] — {exc.detail}", - file=sys.stderr, - ) - return exc.exit_code - except StoreCorrupt as exc: - # 🔴 LOUD, and never absorbed into "served from cache". A server that - # ships a link, a traversal member, a duplicate, or a count disagreeing - # with its own header is not an outage — it is the case that must stop - # the run, cache or no cache. - print(f"🔴 cairn: REFUSED the archive — {exc}", file=sys.stderr) - return EXIT_CORRUPT - except StoreUnreachable as exc: - # 🔴 A WRITE AND A READ DO NOT SHARE A CODE HERE. Exit 3 is - # "store-unreachable, no cache" — a statement about what was DISPLAYED. - # On a write nothing was displayed and, more importantly, nothing was - # RECORDED; a caller that reads 3 as "the read came back empty" would - # carry on believing the bullet landed. `writes` is set by the write - # subparsers only, so this cannot drift with a new read verb. - if getattr(args, "writes", False): - print( - f"🔴 cairn: the write did NOT happen — {exc}\n" - f" Nothing was queued and nothing was written locally. " - f"Re-run when the store is reachable.", - file=sys.stderr, - ) - return EXIT_WRITE_UNREACHABLE - # Reached only by a config failure outside `resolve_state`; still named. - print(f"🔴 cairn: {STATE_NO_CACHE} — {exc}", file=sys.stderr) - return EXIT_UNREACHABLE_NO_CACHE - except (rc.StoreMissingError, subsystem_resolver.ResolverError) as exc: - # 🔴 THE READER-ERROR RUNG THIS LADDER WAS MISSING, AND ITS ABSENCE WAS A - # DIVERGENCE (#111). `internal/client/cli.go`'s ladder ends with exactly - # this arm — "EVERYTHING ELSE IS A READER ERROR — a missing store root, an - # unreadable entry — and it exits 3" — and this one simply stopped, so the - # SAME condition printed a Python traceback at exit 1 here and a named line - # at exit 3 there. MEASURED on one scope holding one `chmod 000` entry - # before this arm existed: `cairn validate` → 1, `cairn recall` → 1, the Go - # client → 3 for both. - # - # 🔴 3, AND IT IS THE ORACLE'S OWN NUMBER RATHER THAN THE PORT'S. - # `subsystem_recall.main` — the reader this client wraps — has always - # answered `except (TouchError, ResolverError) … return 3` for this exact - # condition, and `_exit_for`'s docstring states the rule it rests on: "3 is - # already 'the store is broken' for this CLI (`StoreMissingError`, - # `EntryUnreadableError`)". Measured directly: `subsystem_recall.py --store - # --scope ` over that store exits 3, and 0 with the same entry - # readable. So the wrapper was the only thing in the system that did not - # already agree. - # - # 🔴 NOT `EXIT_CORRUPT` (5), WHICH IS THE OTHER CANDIDATE AND IS WRONG. - # 5 is a MALFORMED entry — one that was READ and rejected — and the whole - # of `load_index`'s residual ledger rests on "could not interpret this - # file" and "could not READ the store" being different facts, only the - # first of which has an honest degraded form. Routing an unreadable entry - # to 5 means collecting it as a `MalformedEntry`, which would make `recall` - # serve the readable entries at exit 0 for a store it did not fully read, - # and make `validate` print `N-1 of N parse, 1 malformed` about a file - # nothing opened. That trades a fail-closed read for a partial one. - # - # ⚠ NAMED CLASSES, NOT A BARE `except OSError`, AND THE DIFFERENCE IS - # DELIBERATE. Go reaches its arm with raw OS errors too, because its verbs - # return them as values; catching `OSError` at this boundary would turn any - # unexpected I/O bug anywhere in the client into a confident "the store is - # broken, exit 3". - # - # 🔴 IT DOES NOT CATCH EVERY UNREADABLE-STORE CONDITION, AND THE RESIDUAL IS - # NAMED RATHER THAN DECLARED CLOSED. Only the reads that go through - # `load_store` raise `EntryUnreadableError` and so land here by class; a - # LISTING read outside it raises a raw `OSError`, which this tuple - # deliberately does not catch. Still unwrapped, by name: `cmd_validate`'s - # `held` and `cmd_routes`' cache-ROOT listings (traceback at exit 1 against - # the Go client's 3 — `tests/parity/README.md` row 4's cache-root depth), - # `cmd_validate`'s per-scope DENOMINATOR (reachable only by the world changing - # mid-run; see the comment at that line), and `cmd_ls_entries`' `glob`, which - # swallows the error instead of raising it. A cache root with no `x` bit never - # reaches any verb at all — it raises out of `resolve_state` first, which is - # the same row 4. ⚠ Nothing enumerates that set mechanically, so re-derive it - # rather than trusting this list: `grep -n 'iterdir()\|glob(' cairn`. - # - # 🔴 THE `ResolverError` HALF IS WIDER THAN THE TWO CLASSES JUSTIFIED ABOVE, - # AND THAT IS A DECISION, NOT AN OVERSIGHT. `ResolverError` has five - # subclasses; the paragraphs above argue `StoreMissingError` and - # `EntryUnreadableError`. The other three — `UnknownScopeError`, - # `AmbiguousRefError`, `InvalidPathError` — would report here as - # `3 = store-unreachable, no cache`, which is the WRONG sentence for each of - # them. Kept wide anyway, for three reasons, in order of weight: - # - # 1. NARROWING WOULD CREATE A DIVERGENCE IN THE TRACEBACK DIRECTION. - # `internal/client/cli.go`'s equivalent arm is the FALLBACK for every - # error the verbs return ("EVERYTHING ELSE IS A READER ERROR"), so it is - # already wider than this tuple. A narrower oracle means any future - # `ResolverError` on a read path is exit 3 with a named line there and a - # Python TRACEBACK at exit 1 here — which is #111, re-opened, and is - # strictly worse than a wrong-but-named sentence. - # 2. MEASURED LATENT, not merely argued: all three are STATUSES on this - # reader, not raises. Over one cache, `recall --scope no-such-scope` → - # exit 0 `status=scope-absent`, `recall --ref ` → exit 0 - # `status=ref-ambiguous`, both with no traceback; `load_store` loads with - # `ON_MALFORMED_COLLECT`, so `MalformedEntryError` cannot escape it - # either (its docstring says so). `InvalidPathError` is reached only from - # `associate_paths` on writer-validated input. - # 3. `subsystem_recall.main` — the reader this client wraps — catches - # `(TouchError, ResolverError)` wholesale for the same condition, so a - # narrower tuple HERE would also disagree with the module it fronts. - # - # ⚠ WHAT WOULD CHANGE THIS: a `ResolverError` subclass becoming reachable - # from a read path with a code of its own (a 2 or a 5). Then this arm must - # list its classes, and `cli.go`'s fallback needs the same split in the same - # commit — not one side. - print(f"🔴 cairn: {exc}", file=sys.stderr) - return EXIT_UNREACHABLE_NO_CACHE - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/claudedocs/plan-cairn-v1-event-log.md b/claudedocs/plan-cairn-v1-event-log.md index c74af08d..2f36022a 100644 --- a/claudedocs/plan-cairn-v1-event-log.md +++ b/claudedocs/plan-cairn-v1-event-log.md @@ -429,7 +429,7 @@ exit criterion. | **2 — SQL, single-user** — *built, not deployed; battery met, eval not run (§6.2)* | `sessions_query` on a SELECT-only login role, caps. Shipped as `cairn log query SQL [--json]`. | An escape battery — `set_config` on any setting, `RESET ROLE`, temp-table writes, multi-statement, `pg_sleep` beyond the timeout, reading any table outside the views — each refused, each shown to succeed on a deliberately weakened role (positive control). Eval not lower than Phase 1. | | **3 — L0 slim + consolidation** | Fact shape, citations, invalidation; consolidation plugin; agents stop the per-session append ritual. | 100% of new facts cite ≥1 event visible to every reader of their scope (checked, not sampled); seeded contradictions in a synthetic world are marked invalidated; eval "curated-store facts" category stays ≥ 7/8 pooled and weak-model "both" does not drop. | | **4 — shared instances** | §5's six preconditions; a materialised, refreshed trailer-walk result so `View` re-checks are cheap at list scale. | Authz battery: each prefilter clause and the re-check mutated one at a time, each caught by its OWN failing test; identical bodies for absent/hidden/deleted across all tools; held-back re-measured on indexed text and recorded; operator decision recorded. | -| **5 — deletions** | §4's remove rows. Independent of 1–4; can run in parallel. | CI green with the oracle and its gates gone; the P8 retirement ledger has a disposition per row; `leakscan` still passes with both controls. | +| **5 — deletions** — *executed on `chore/delete-python-oracle` (§6.3); after the Stage 2 client-JSON work (#326) merged; merge-ordered after the consumer port* | §4's remove rows. Independent of 1–4; can run in parallel. | CI green with the oracle and its gates gone; the P8 retirement ledger has a disposition per row (§6.3); `leakscan` still passes with both controls. ⚠ One §4 row was NOT taken as written: `tests/conformance/` was KEPT, not removed — its Go half is the HTTP contract gate, and the goldens recorded from the oracle were FROZEN as a fixed corpus rather than deleted (§6.3). | ### 6.1 Phase 1 outcome — closed on ordering, 2026-12-03 @@ -513,6 +513,37 @@ arms (`tests/memeval/arms.py`) do not offer `query`, so a run today measures Pha **Open from the #328 sandbox audit:** finding 🟢 7, recorded as open by the coordinator. Its text was not in this branch's context; it is in the audit report. +### 6.3 Phase 5 outcome — the P8 retirement ledger, row by row + +The ledger lived in `tests/parity/README.md`, which is deleted with that directory; its dispositions are +recorded here so they outlive it. "Frozen" below means: recorded from the retired Python implementation at +`ec1b756b15ea37469124c635d0d82f6e10d57899` (the last commit that had it), kept as a FIXED contract, pinned +by digest, and never re-recorded from Go (that would make the test agree with itself). + +| ledger row | disposition | +|---|---| +| `tests/parity/` (harness, world, hostile, README) and the `parity` CI job | **deleted** — with one client there is nothing to compare. | +| `tests/dualrun/` (~2,900 lines), `tests/test_dualrun_harness.py`, the `dualrun` CI job | **deleted** — its second arm, `server/server.py`, is gone, so it cannot run. The audit-record `ts=` spelling guard was already Go-side (`internal/api`) and is untouched. ⚠ The two things the row asked to re-home were NOT re-homed: the mode-2 store generator (`genstore.py`) is deleted with the harness, and the "byte-identity is scoped to the uncompressed tar" lesson survives only as history in `server/README.md`. | +| `internal/store/pyoserror.go` | **kept** — live code reached from `internal/client` and `internal/doctor`. Decision: the CPython `[Errno N] …: ''` spelling stays as the documented error contract; nothing re-records it. | +| `tests/test_go_client_ledgers.py`'s cross-client tests | **re-pointed** — the verb set and the routes are compared with `testlib/capability_ledger.LEDGER` (and the routes also with the conformance corpus), read out of the running binaries; the cross-client exit-code equality is deleted; `test_the_go_clients_exit_codes_keep_the_shared_set_at_0_and_9` **kept** as is. | +| residual 7 and `test_the_GO_ONLY_ledger_flags_are_exactly_the_declared_set` | **decided: public surface.** `-verbs` / `-exit-codes` are documented in `README.md`; the guard is re-pointed (no third single-dash flag may answer 0 undeclared), no longer a divergence check. | +| the Python half of the client READ LEDGER (S11) | **deleted** (`lib/read_ledger.py`, `tests/test_read_ledger.py`). `env_pin.READ_LEDGER_ENV` was not re-homed: `testlib/env_pin.py` had no consumer left and is deleted; the one remaining pytest driver of the client (`tests/memeval/world.py`) runs it under `env -i` with an explicit environment, which carries no session id. `internal/client/readledger.go` and its tests are untouched. | +| the `go_only` declaration machinery (residual 11) | **folded, not dropped** — every route, verb, row and golden stays; only the mark goes (`requests.json`, `capability_ledger`, the flake's `want-go-only*.txt` merged into one list each, `checkRouteLedger`'s go-only branch). `cases.load_corpus` refuses any unread row key, so the mark cannot linger. | +| the 31 narrower parity rows | **deleted** with the harness. | +| `testlib.capability_ledger.cli_verbs_from_parser`, `testlib.cairn_source` | **re-pointed, not deleted** — the ledger is asserted against `cairn -verbs` / `cairn-server -routes`; `cairn_source` (an AST reader of the Python script) is deleted. | +| `packages.cairn`, `checks.client-resolves-its-lib`, the `lib/` rule in `AGENTS.md` | **deleted** — both conditions met (default flipped earlier; `packages.cairn` now gone). `apps.cairn` and `packages.server-image` (+ its `cairn-store` publish leg) go too. | +| `report_json`'s key `"tasks"` | **deleted** with `lib/subsystem_recall.py`. The naming decision it deferred was taken by the Go client's `--json` document (Stage 2), which spells the field `refs`. | +| residuals 3, 4, 5, 6 | **deleted** with the table. Residual 3's ULP property remains measured by the frozen reader fixture (`st_mtime_hex` per entry). ⚠ The four unreadable-entry/scope-dir parity rows are gone with the harness. Replaced by Go tests through the CLI entry point: `internal/client`'s `TestAnUnreadableEntryIsReportedWithTheORACLESSentenceAtExitThree` (`validate` AND `recall`, unreadable entry) and `TestAnUnreadableScopeDirectoryIsReportedWithTheReadersSentenceAtExitThree` (both verbs, mode-000 scope directory: exit 3, the store-wide sentence, the CPython-spelled tail naming the directory); the env-alias deprecation line on stderr is `TestAnEnvironmentAliasIsAnnouncedOnStderrByTheCLI`. Each mutation-checked (scope-dir read error swallowed; the alias sweep removed from `Run`; the sink pointed at stdout; the raw Go error in the sentence — 4/4 killed). | +| residual 9 and its two paragraphs | **declarations deleted, behaviour kept** — `internal/client/verbs.go` (`opts.Ref` literal) and `snapshot.go` (literal prefix) now state the rule, not a divergence; the `fnmatch`/`filepath.Match`/`HasPrefix` measurement is re-homed in `snapshot.go` as a property of the matchers. | +| the Python half of the closed `tags:` vocabulary | **deleted**; `tests/test_tag_vocabulary.py` keeps the hand-typed `DECLARED`/`DECLARED_REFUSAL` literals against `internal/write`; the four `put-*-tag-*` goldens are in the frozen corpus. | +| the Python half of the CITATION ID | **option (a): kept the fixture, relabelled it a frozen contract** — `internal/store/citationid_test.go`'s header says so; `tests/test_citation_ids.py` pins the file's sha256; the generator is deleted. `internal/store` and `internal/pytext` untouched; `internal/pytext/testdata/decode_replace.json` is NOT frozen (it records the interpreter, still regenerated). | + +Beyond the ledger: the conformance corpus's oracle-recorded goldens are frozen (124 after the #327 audit deleted the four never-compared `oracle_only` rows; count + digest, +`tests/conformance/README.md`); the reader fixture and the marker-sweep fixture are frozen the same way; the +seed tests and the CPython `re.I` sweep were split out of deleted files rather than dropped; the env-alias +removal anchor moved from "`packages.cairn` is retired" (met) to a CHANGELOG-announced release, aliases still +working (`internal/envalias`'s package doc names the next step). + ## 7. Open questions for the operator **Decided 2026-12-03.** The operator answered Q1, Q3, Q6, Q7 and Q8 directly and chose the scope diff --git a/cmd/cairn-server/createuser.go b/cmd/cairn-server/createuser.go index a1b4a0de..4340a6a8 100644 --- a/cmd/cairn-server/createuser.go +++ b/cmd/cairn-server/createuser.go @@ -480,8 +480,8 @@ func openSessionAuthority(ctx context.Context, env map[string]string, warn func( // in the journal and delete or correct it — and a count tells an operator that something is // wrong without telling them what to edit. // -// ⚠ AND IT IS SILENT WHEN NOTHING WAS DROPPED, WHICH IS THE NORMAL CASE AND KEEPS THIS OFF -// THE STARTUP OUTPUT `tests/dualrun/` COMPARES BETWEEN THE TWO SERVERS. +// ⚠ AND IT IS SILENT WHEN NOTHING WAS DROPPED, WHICH IS THE NORMAL CASE AND KEPT THIS OFF +// THE STARTUP OUTPUT THE RETIRED `tests/dualrun/` GATE COMPARED BETWEEN THE TWO SERVERS. // // ⚠ IT IS THE ONE-SHOT SPELLING, FOR `-issue-credential`, WHICH READS THE JOURNAL ONCE AND // EXITS. A process that keeps reading it wants `newDropAnnouncer` instead — same line, said @@ -571,7 +571,8 @@ func newDropAnnouncer(journal string, model func() control.Model, warn func(stri // stale exactly the way the tally it replaced did, and the one that stood here had already // lost `internal/identity`. Adding the first caller here would falsify all of them at once // while closing none of the thing they defer, which is a status SURFACE — a `doctor` -// section, a route, or the startup banner `tests/dualrun/harness.py` compares. So this +// section, a route, or the startup banner (which the retired `tests/dualrun/harness.py` +// compared between the two servers). So this // reports the EVENT and the remedy, and the value stays where those comments say it is. // // ⚠ NO COUNT IS QUOTED, AND THE ABSENCE IS DELIBERATE. This sentence used to say "six diff --git a/cmd/cairn-server/main.go b/cmd/cairn-server/main.go index 5917fd7c..f3659cfe 100644 --- a/cmd/cairn-server/main.go +++ b/cmd/cairn-server/main.go @@ -1,4 +1,4 @@ -// Command cairn-server is the Go port of `server/server.py`: the pod that serves +// Command cairn-server is the Go port of the retired `server/server.py`: the pod that serves // scoped, per-token-authorised entries. // // 🔴 IT IS THE DEPLOYED POD. ⚠ This read "IT IS NOT DEPLOYED BY THIS COMMIT, AND @@ -585,9 +585,11 @@ func main() { // `Staleness` DID. `control.Cache.Staleness()` is a renderable value with no caller // outside the tests — this program does not print it, `internal/doctor` does not read // it, and no route carries it — so the window, and a `degraded`/`stale` authority - // with it, is bounded and SILENT. The surface is deferred because the one place to - // print it is the startup banner below, which `tests/dualrun/harness.py` compares - // between the two servers; the closing condition is in `tokenfile`'s package doc. + // with it, is bounded and SILENT. The surface was deferred because the one place to + // print it is the startup banner below, which the retired `tests/dualrun/harness.py` + // compared between the two servers; that gate went with the Python oracle, so the reason + // is gone and the surface is simply unbuilt — the closing condition is in `tokenfile`'s + // package doc. // // ⚠ SIGHUP IS DELIBERATELY NOT ONE OF THESE TRIGGERS. The reload path above already // re-materializes as part of publishing the new table, and a second registration diff --git a/cmd/cairn/main.go b/cmd/cairn/main.go index 831bc16f..275a1711 100644 --- a/cmd/cairn/main.go +++ b/cmd/cairn/main.go @@ -4,11 +4,12 @@ // `internal/report`, so byte-identity between pod output and local output is a property of there // being one implementation rather than a discipline two implementations are held to. // -// ⚠ THIS BINARY IS NOW `packages.default`/`apps.default`, AND THE PYTHON CLIENT IS STILL -// SHIPPED AND STILL THE ORACLE. The cutover moved which client a consumer gets by default; it -// deleted nothing. `packages.cairn` remains the Python client, `tests/parity/harness.py` still -// runs both against ONE cache root and diffs stdout, stderr and exit code per verb and flag -// combination, and the plan puts the deletion of Python at P8. +// ⚠ THIS BINARY IS `packages.default`/`apps.default`, AND IT IS NOW THE ONLY CLIENT. The +// cutover moved which client a consumer got by default and deleted nothing; the Python client +// (`packages.cairn`) stayed the oracle, and `tests/parity/harness.py` ran both against ONE cache +// root and diffed stdout, stderr and exit code per verb and flag combination, until P8 deleted +// Python, the packaging and that gate together. Nothing compares this client against a second +// implementation any more; what it agreed with is frozen in the contracts recorded at `ec1b756`. // // 🔴 THE GREEN GATE IS NOT WHAT LICENSED THE FLIP, AND SAYING SO IS THE POINT: a branch took it // on that reading and was REVERTED. It was taken on an operator decision, after residual 8's @@ -37,13 +38,14 @@ import ( func main() { argv := os.Args[1:] - // 🔴 TWO LEDGER FLAGS, READ OUT OF THE RUNNING BINARY, BECAUSE THE PYTHON-SIDE DISCOVERY - // CANNOT SEE A COMPILED PROGRAM. `tests/testlib/capability_ledger.py` asks the PYTHON - // argparse parser what subcommands it has, and `tests/test_cairn_doctor.py` walks the - // `cairn` script's AST for its `EXIT_*` constants — neither has an equivalent here, so a - // Go-only verb, a Go client that silently LOST a verb, or a Go exit code colliding with - // `doctor`'s 10 would each leave those gates green. These flags are what closes that, the - // same way `cairn-server -routes` closes the route ledger's blind spot. + // 🔴 TWO LEDGER FLAGS, READ OUT OF THE RUNNING BINARY, BECAUSE SOURCE-SIDE DISCOVERY + // CANNOT SEE A COMPILED PROGRAM. While the Python client lived, `tests/testlib/ + // capability_ledger.py` asked ITS argparse parser what subcommands it had, and the retired + // `tests/test_cairn_doctor.py` walked the `cairn` script's AST for its `EXIT_*` constants — + // neither had an equivalent here, so a Go-only verb, a Go client that silently LOST a verb, or + // a Go exit code colliding with `doctor`'s 10 would each have left those gates green. These + // flags are what closed that, and `tests/test_go_client_ledgers.py` reads them today — the same + // way `cairn-server -routes` closes the route ledger's blind spot. // // ⚠ THEY ARE NOT SUBCOMMANDS AND THEY ARE SINGLE-DASH ON PURPOSE. Every real verb is a // bare word and every real option is `--`-prefixed, so `-verbs` cannot collide with either, diff --git a/conftest.py b/conftest.py index 7105cd87..af61b56c 100644 --- a/conftest.py +++ b/conftest.py @@ -1,9 +1,8 @@ -"""Make the extracted modules importable without installing the package. +"""Make the test helpers importable without installing anything. -🔴 `lib/` AND `tests/` BOTH GO ON THE PATH, and neither is a package. The modules -import each other by bare name (`from entry_shape import …`), which is what lets -the same files be vendored into a consumer's own tree unchanged. A package -rename would be a silent behaviour change for every one of those imports. +`tests/` goes on the path, and it is not a package: modules import each other by bare +name (`from testlib import …`, `import reader_fixtures`). (Until the Python client and pod +were retired, `lib/` and `server/` went on the path too, for the modules those shipped.) """ from __future__ import annotations @@ -11,7 +10,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parent -for p in (ROOT / "lib", ROOT / "tests", ROOT / "server"): +for p in (ROOT / "tests",): s = str(p) if s not in sys.path: sys.path.insert(0, s) diff --git a/flake.nix b/flake.nix index fa9a4bcb..a01d6ee3 100644 --- a/flake.nix +++ b/flake.nix @@ -7,8 +7,8 @@ outputs = { self, nixpkgs }: let - # Darwin is listed because the CLIENT is stdlib Python and has no reason - # not to build there. The IMAGE is Linux-only, and is exposed only on + # Darwin is listed because the CLIENT is a static Go binary and has no + # reason not to build there. The IMAGE is Linux-only, and is exposed only on # Linux rather than failing at evaluation with a `dockerTools` error. # 🔴 `x86_64-darwin` IS DELIBERATELY ABSENT, AND ITS ABSENCE IS LOAD-BEARING. # nixpkgs 26.11 — which `flake.lock` pins — DROPPED that platform, so @@ -33,78 +33,50 @@ # tree, which is itself the fact a reader of the tag most wants. version = self.shortRev or self.dirtyShortRev or "unknown"; - # 🔴 THE RUNTIME CONTRACT, IN ONE PLACE, BECAUSE THERE ARE NOW TWO BUILDS. - # ⚠ This read "`server/Dockerfile` is what is deployed today" until the Go - # cutover. NEITHER Python image is deployed now — the cluster pulls - # `cairn-store-go`. The pin below still earns its place, because both - # builds state the contract and can still disagree. - # The image below is a - # second way to produce the same pod, and two build paths that can - # disagree about env/port/user is the whole hazard of adding one. These - # values are the single nix-side authority for it, and - # `tests/test_flake_image_matches_dockerfile.py` pins them against the - # Dockerfile so neither can move alone. + # 🔴 THE POD'S RUNTIME CONTRACT, IN ONE PLACE. `serverEnv`, `serverUid` and `serverPort` + # are the single nix-side statement of it; `mkGoServerImage` DERIVES its env, uid, port + # and exposed port from them, and `tests/test_flake_go_image_runtime_contract.py` pins + # that it stays derived rather than copied. # - # HOME is not decoration: `lib/subsystem_read_store.py` evaluates - # `Path.home() / ".cache" / …` at IMPORT time, and `Path.home()` raises - # when it can resolve neither $HOME nor a passwd entry — the ordinary - # state of a numeric-UID container. The value is never used by the server - # (every call passes `--store`), but the import would fail before - # anything could say so. + # 🔴 `serverEnv` IS EMPTY, AND THAT IS A FACT ABOUT TODAY, NOT ABOUT THE MECHANISM. The + # image's `Env` is `serverEnv // { PATH; SSL_CERT_FILE; }`, so a variable added here + # reaches the pod and cannot be forgotten on it. It held `HOME` and two CPython knobs + # for the retired Python pod (whose reader evaluated `Path.home()` at import time), all + # subtracted from the Go pod by name; with that pod deleted the subtraction had nothing + # left to subtract from, so the binding was emptied rather than the mechanism removed. + # Nothing in `go list -deps ./cmd/cairn-server` reads `$HOME` (every such call is under + # `internal/client`, which the server does not import) — re-run that before adding one. # - # 🔴 NEITHER IMAGE SETS A STORE VARIABLE IN EITHER SPELLING, AND THAT IS A DECISION - # RATHER THAN AN OMISSION. `SUBSYSTEM_STORE_ROOT=/data`, - # `SUBSYSTEM_STORE_PORT=8102` and - # `SUBSYSTEM_STORE_TOKEN_FILE=/run/secrets/subsystem-store/token` were here, and are - # gone. Two measurements decided it: + # 🔴 THE IMAGE SETS NO STORE VARIABLE IN EITHER SPELLING, AND THAT IS A DECISION RATHER + # THAN AN OMISSION. `SUBSYSTEM_STORE_ROOT=/data`, `SUBSYSTEM_STORE_PORT=8102` and + # `SUBSYSTEM_STORE_TOKEN_FILE=/run/secrets/subsystem-store/token` were here, and are gone. + # Two measurements decided it: # # * THEY CONFIGURED NOTHING. Each value was byte-identical to the code default the - # server falls back to with the variable unset — `server/server.py`'s - # `DEFAULT_STORE`/`DEFAULT_PORT`/`DEFAULT_TOKEN_FILE` and - # `cmd/cairn-server/main.go`'s `defaultStore`/`defaultPort`/`defaultTokenFile`. - # Measured on both by running each with `env -i`: the oracle prints - # `listening on 0.0.0.0:8102 store=/data`, and the Go server names - # `/run/secrets/subsystem-store/token` in its token-file refusal. So removing - # them moves no resolved value. `tests/test_flake_image_matches_dockerfile.py` - # pins that agreement against BOTH implementations now that the image no longer - # states it. - # * THEY COST THREE DEPRECATION WARNINGS AT EVERY POD START. The resolver sweeps - # the WHOLE process environment, and the image's own `ENV` is part of it — so the - # pod emitted three unactionable lines nobody could clear from a manifest. - # Measured: `deprecations(image_env)` is 3, and it is still 3 after a Deployment - # migrates its own `env:` to `CAIRN_*`, because the image half is still there. - # With the image setting nothing, that same migrated Deployment measures 0. + # server falls back to with the variable unset — `cmd/cairn-server/main.go`'s + # `defaultStore`/`defaultPort`/`defaultTokenFile` (and, while it existed, the Python + # server's). Measured with `env -i`: the server names + # `/run/secrets/subsystem-store/token` in its token-file refusal. So removing them + # moved no resolved value; `tests/test_server_deployment_defaults.py` pins those + # defaults against what a Deployment assumes now that the image does not state them. + # * THEY COST THREE DEPRECATION WARNINGS AT EVERY POD START. The resolver sweeps the + # WHOLE process environment, and the image's own `ENV` is part of it — so the pod + # emitted three unactionable lines nobody could clear from a manifest. # - # 🔴 AND IT CLOSES THE SHADOWING HAZARD AT THE ROOT RATHER THAN DEFERRING IT TO P8. - # The note that used to sit here explained why the image had to keep the OLD spelling: - # an image `ENV` is a DEFAULT present whether or not the manifest mentions it, and - # new-name-wins would have let a `CAIRN_STORE_ROOT` baked here outrank a Deployment - # that explicitly set `SUBSYSTEM_STORE_ROOT`. That reasoning was correct and is now - # moot: with no image default there is nothing to outrank a manifest, in either - # spelling, so the images could adopt `CAIRN_*` later with no window at all. + # 🔴 AND IT CLOSES THE SHADOWING HAZARD AT THE ROOT. An image `ENV` is a DEFAULT present + # whether or not the manifest mentions it, and new-name-wins would let a + # `CAIRN_STORE_ROOT` baked here outrank a Deployment that explicitly set + # `SUBSYSTEM_STORE_ROOT`. With no image default there is nothing to outrank a manifest, + # in either spelling. # # ⚠ THE ACCEPTED COST, STATED SO IT IS NOT REDISCOVERED AS A BUG. `docker inspect` and # this file no longer show where the store lives, which port it binds or where the - # token is read from. The operator took that trade knowingly. What replaced the - # env-based assertion is a pin on the CODE defaults in both implementations — - # `STORE_DEFAULTS` in `tests/test_flake_image_matches_dockerfile.py`, ONE declared - # constant holding all THREE values, spelled by hand and checked against each - # implementation's own constants. (`DEPLOY_CONTRACT` in - # `tests/test_flake_go_image_runtime_contract.py` is an alias for it, `= STORE_DEFAULTS`, - # so the sibling module's assertions read in the same vocabulary; the declaration has - # one home and this is not it.) - # - # ⚠ AND THE STARTUP LINE COVERS TWO OF THE THREE, NOT THREE — a sentence here used to - # say it printed all of them. Both pods print - # `listening on : store= token-ids=…`; `token-ids=` is the credential - # FINGERPRINTS, and neither implementation's startup line prints the token PATH. The Go - # server's `-h` prints it as a flag default, the oracle's `--help` does not, and both - # emit it on stderr only in the `token file absent` fallback notice. - serverEnv = { - HOME = "/home/nonroot"; - PYTHONDONTWRITEBYTECODE = "1"; - PYTHONUNBUFFERED = "1"; - }; + # token is read from. The operator took that trade knowingly; `STORE_DEFAULTS` in + # `tests/test_server_deployment_defaults.py` is the one declared constant holding all + # three values. The startup line prints `listening on : store= + # token-ids=…` — two of the three; the token PATH appears as `-h`'s flag default and in + # the `token file absent` notice only. + serverEnv = { }; serverUid = 65532; serverPort = 8102; @@ -132,69 +104,13 @@ uiPort = 8103; uiSessionDir = "/var/lib/cairn-ui"; - # 🔴 THE GO POD'S ENV IS `serverEnv` MINUS A NAMED SET — A SUBTRACTION, NEVER - # A SECOND LITERAL. There are now THREE builds of a pod and only ONE statement - # of the contract: `serverEnv` above. Deriving the Go image's env from it means - # a variable added there reaches BOTH pods and cannot be forgotten on one. - # A second attrset holding copies would invert that — the drift would be silent - # and in the direction that matters, a pod missing an env its Deployment sets. - # - # 🔴 IT NOW SUBTRACTS EVERYTHING, SO `serverEnvGo` IS `{ }`, AND THE MECHANISM IS - # KEPT ANYWAY RATHER THAN COLLAPSED TO A LITERAL. Dropping the three store variables - # from `serverEnv` left it holding only CPython knobs and a `HOME` for them, all - # three of which are Python-only — so the Go image's `Env` is its `//` override - # alone (`PATH`, `SSL_CERT_FILE`). Replacing this with a hardcoded two-element env - # would read as a simplification and would silently stop the NEXT shared variable - # from reaching the Go pod, which is the exact drift the subtraction exists for. The - # empty result is a fact about today's `serverEnv`, not about the derivation. - # - # WHY EACH NAME LEAVES, READ OUT OF THE CODE RATHER THAN ASSUMED: - # * `PYTHONDONTWRITEBYTECODE` / `PYTHONUNBUFFERED` are CPython knobs. A Go - # binary never reads either; carrying them would assert the image runs an - # interpreter, which is the one thing this image is for NOT doing. - # * `HOME` is in `serverEnv` because `lib/subsystem_read_store.py` evaluates - # `Path.home()` at IMPORT time and it raises in a numeric-UID container. - # MEASURED on the Go side rather than inferred, and stated as the METHOD - # rather than a count that would rot: nothing in `go list -deps - # ./cmd/cairn-server` calls `os.UserHomeDir` or reads `$HOME` — every such - # call lives under `internal/client`, which the server does not import, and - # `internal/hostid` reads only `CAIRN_HOST`/`ASIB_HOST`/`ACTIVITY_HOST`. Re-run - # that pair before moving a name out of this list. So there is no - # import-time home to resolve, and an env var nothing reads in an image - # whose env IS the deploy contract is a claim about the pod that is false. - # - # ⚠ WHAT THIS DOES NOT CLAIM: that `$HOME` is unreachable in the container. - # `kubectl exec … -- sh` lands in a shell with no `HOME`. busybox `ash` does not - # need one, and both documented procedures name absolute paths (`tar -xf -` into - # `/data`, `kill -HUP 1`). If a procedure ever needs `~`, it goes in `serverEnv` - # and both pods get it — which is the point of the subtraction. - # - # ⚠ KEEPING `HOME` AND DROPPING ONLY THE TWO `PYTHON*` KNOBS WAS PROPOSED IN REVIEW - # AND DECLINED; RECORDED SO IT IS NOT RE-LITIGATED FROM SCRATCH. The proposal's cost - # argument is real — this comment, and a standing obligation to re-run `go list -deps` - # whenever the server's imports change. Three things decided it the other way. - # (1) The failure mode of a WRONG drop is LOUD, not silent: `os.UserHomeDir` returns - # an explicit "$HOME is not defined" error. The silent-drift class the subtraction - # exists to prevent is the OTHER direction — a variable that never reaches the Go - # pod at all — and that one is closed structurally by `removeAttrs`. - # (2) Keeping it is MORE derivation, not less: `mkServerImage` creates and chowns - # `/home/nonroot` in `fakeRootCommands` precisely because it sets `HOME`. A `HOME` - # naming a directory the image does not contain is false in two ways instead of - # one, so "keep" means restoring that mkdir here too. - # (3) The image's `Env` IS the deploy contract, and the next operator debugging a - # buffering or home-directory question reads it as one. - serverEnvPythonOnly = [ "HOME" "PYTHONDONTWRITEBYTECODE" "PYTHONUNBUFFERED" ]; - serverEnvGo = builtins.removeAttrs serverEnv serverEnvPythonOnly; - # 🔴 THE INTERPRETER IS PINNED TO THE ONE THE SUITE ACTUALLY RUNS UNDER. - # `pkgs.python3` follows nixpkgs and was 3.14 here, while - # `server/Dockerfile` is `python:3.12-slim` and CI pins `python-version: - # "3.12"` — so the packaged client and the flake image shipped an - # interpreter NOTHING in this repo had ever run the suite against, and a - # lock bump could move it again silently. The suite already emits a 3.14 - # tar-extraction DeprecationWarning, so the gap is behaviourally live, - # not theoretical. Change this in the same commit as the Dockerfile and - # the CI matrix, never alone. + # `pkgs.python3` follows nixpkgs and was 3.14 here, while CI pins + # `python-version: "3.12"` — so a check built on it ran an interpreter + # NOTHING in this repo had ever run the suite against, and a lock bump could + # move it again silently. Nothing SHIPPED uses it any more (the Python + # client and pod are retired); the devShell and the Python-driven checks do. + # Change this in the same commit as the CI matrix, never alone. python = pkgs: pkgs.python312; # 🔴 THE POD IS OPERATED THROUGH `kubectl exec`, SO THE IMAGE MUST CARRY A @@ -213,9 +129,9 @@ # those applets in ~2 MB, and the procedures use only POSIX spellings. # # 🔴 `serverPath` MUST NAME A DIRECTORY THE APPLETS ACTUALLY LAND IN, and - # `serverTools` MUST REACH `contents`. Both are asserted by - # `tests/test_flake_image_matches_dockerfile.py`, and BOTH assertions - # exist because their absence was measured: with the guard pinning only + # `serverTools` MUST REACH `contents`. Both are asserted for the pod by + # `tests/test_flake_go_image_runtime_contract.py`, and BOTH assertions + # exist because their absence was measured (on the retired Python image): with the guard pinning only # the two bindings, a mutant that reverted `contents` to `[ tree ]` and a # mutant that set `serverPath = "/nonexistent"` EACH SURVIVED the whole # suite while restoring the exact defect the guard was written for — a @@ -229,10 +145,9 @@ serverTools = pkgs: [ pkgs.busybox ]; # 🔴 THE GO POD CARRIES `serverTools` PLUS CA ROOTS, AND THE EXTRA IS NOT - # DECORATION. `mkServerImage` ships no `/etc`, so a container built from it has - # NO CA bundle at any path Go's `crypto/x509` searches. That costs the Python pod - # nothing — it makes no outbound TLS connection — but `internal/identity/jwks.go` - # fetches a JWKS over `https` for the Supabase backend, and without roots that + # DECORATION. `serverTools` alone ships no `/etc`, so a container built from it has + # NO CA bundle at any path Go's `crypto/x509` searches — and `internal/identity/jwks.go` + # fetches a JWKS over `https` for the OIDC backend, so without roots that # fetch fails certificate verification on an image that otherwise starts, passes # health checks and serves. Same shape as the missing-`sh` defect `serverTools` # exists for: four pinned values agreeing over a pod that cannot do its documented @@ -245,10 +160,6 @@ # JWKS fetch against a real issuer is NOT verified by anything in this repository — # it needs a pod, a network and an issuer, none of which a nix build has. # - # ⚠ AND IT IS GO-ONLY ON PURPOSE. Adding `cacert` to `serverTools` would change - # `packages.server-image`'s layer contents, which is the one thing - # `tests/test_flake_image_matches_dockerfile.py` is written against, for a pod - # that has no use for it. goServerTools = pkgs: serverTools pkgs ++ [ pkgs.cacert ]; # 🔴 NAMED BY ABSOLUTE STORE PATH, AND `SSL_CERT_FILE` IS *NOT* WHAT MAKES THE @@ -293,54 +204,27 @@ # anything arranged a filesystem layout around it. goServerCaBundle = pkgs: "${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"; - # 🔴 AN ALLOWLIST, NOT AN EXCLUDE LIST, FOR THE SAME REASON - # `server/Dockerfile.dockerignore` is one: a working tree of this repo - # holds store CONTENT (entry files) and caches that must never reach a - # build artefact, and an exclude list ships whatever nobody thought to - # name. Flake source is already git-filtered — untracked files are not - # copied — but that is a property of how the source was FETCHED, not of - # this derivation, and it does not hold for `nix build path:.`. Stating - # the filter here makes the property true of the derivation itself. - onlyCode = pkgs: pkgs.lib.cleanSourceWith { - src = ./.; - name = "cairn-source"; - filter = path: type: - let rel = pkgs.lib.removePrefix (toString ./. + "/") (toString path); - in - (type == "directory" && (rel == "lib" || rel == "server")) - || (rel == "cairn") - || (pkgs.lib.hasPrefix "lib/" rel && pkgs.lib.hasSuffix ".py" rel) - || (rel == "server/server.py"); - }; - - # 🔴 A SECOND ALLOWLIST FOR THE GO TREE, AND IT IS SEPARATE FROM - # `onlyCode` ON PURPOSE. `onlyCode` feeds the PYTHON artefacts — the - # packaged client and the pod image — and widening it to carry `go.mod`, - # `cmd/` and `internal/` would put the Go sources into both of those - # closures for nothing, and would change the `server-image` layer contents - # that `tests/test_flake_image_matches_dockerfile.py` is written against. - # Two filters is the honest shape while two implementations are alive; the - # day Python is retired, one of them goes away rather than being widened. - # - # An allowlist rather than an exclude list, for the same reason as - # `onlyCode`: a working tree of this repo holds store CONTENT and caches - # that must never reach a build artefact, and an exclude list ships - # whatever nobody thought to name. + # 🔴 AN ALLOWLIST FOR THE GO TREE, NOT AN EXCLUDE LIST: a working tree of this + # repo holds store CONTENT (entry files) and caches that must never reach a + # build artefact, and an exclude list ships whatever nobody thought to name. + # Flake source is already git-filtered — untracked files are not copied — but + # that is a property of how the source was FETCHED, not of this derivation, and + # it does not hold for `nix build path:.`. (There were two filters while the + # Python client and pod existed; theirs went with them.) # # 🔴 `tests/conformance/requests.json` IS IN THIS FILTER ON PURPOSE, AND IT # IS THE ONE NON-GO FILE HERE. `TestTheRouteLedgerMatchesTheConformance # Corpus` reads that list and compares it against the routes this server - # dispatches, in BOTH directions — it is the guard that closes the - # "a route added after the fixtures were generated" blind spot for a - # non-Python implementation, which `tests/conformance/README.md` names as - # explicitly open on this side. Leaving the file out would make the + # dispatches, in BOTH directions — it is the in-process half of the guard + # that closes the "a route added after the fixtures were recorded" blind + # spot (`tests/conformance/README.md`). Leaving the file out would make the # package's own test run skip its most load-bearing guard, in a sandbox, # silently. A sandbox that pins a dimension cannot be read as coverage of # it — so the dimension is supplied instead. # # 🔴 AND `internal/report/testdata/reader_fixtures.json` IS HERE FOR EXACTLY THE - # SAME REASON, WHICH IS WHY THE TWO SIT TOGETHER. That file is the ORACLE'S OWN - # rendered bytes for fifty report shapes the HTTP corpus cannot send — every + # SAME REASON, WHICH IS WHY THE TWO SIT TOGETHER. That file is the retired ORACLE'S + # OWN rendered bytes, FROZEN, for the report shapes the HTTP corpus cannot send — every # badge, the pagination branches, the search rungs, the difflib ratios — and # `TestTheRenderedBytesMatchTheORACLE…` is the differential gate over it. # Leaving it out would not skip quietly: the test calls `t.Fatalf`, so the @@ -389,8 +273,8 @@ # 🔴 AND A THIRD ONE, FOUND BY A RED SANDBOX BUILD RATHER THAN BY ANYONE # READING THE PARAGRAPH ABOVE. `internal/store/markersweep_test.go` is the # differential sweep behind `marker.go`'s narrowing ledger: it replays the - # ORACLE's verdicts for every generated line against two hand-rolled - # transcriptions of CPython regexes. Its fixture was first written to + # retired ORACLE's verdicts (FROZEN in that fixture) for every generated line + # against two hand-rolled transcriptions of CPython regexes. Its fixture was first written to # `tests/fixtures/`, which this allowlist does not carry — so the sweep was # green on the dev host and RED here, which is the two-tier split the # comment above describes, arriving one commit after it was written. Moved @@ -399,9 +283,9 @@ || (rel == "internal/store/testdata/marker_oracle_sweep.json") # 🔴 AND A FOURTH, ADDED WITHOUT WAITING FOR THE RED BUILD THIS TIME — the # paragraph above is what made it predictable. `internal/store`'s - # citation-id test replays `tests/citation_ids.py`'s PYTHON answers, so the - # two implementations of `CitationID` / `citation_id` cannot drift without - # one of them going red. 🔴 THE ALLOWLIST IS FILE-BY-FILE FOR FIXTURES: the + # citation-id test replays the citation ids FROZEN at the retirement of the + # Python implementation that recorded them — a contract pin, so a derivation + # change that would orphan every id already printed goes red. 🔴 THE ALLOWLIST IS FILE-BY-FILE FOR FIXTURES: the # `hasPrefix "internal/"` row above is inside the `type == "directory"` # clause, so it carries the DIRECTORY and not the JSON inside it. A reader # who assumes a directory row covers its files gets the two-tier split the @@ -663,7 +547,7 @@ moduleTests = mkGoModuleTests pkgs; meta = with pkgs.lib; { - description = "The Go port of the cairn store API (P1: dual-run against the Python oracle)"; + description = "The cairn store API server"; homepage = "https://github.com/ZacxDev/cairn"; license = licenses.mit; mainProgram = "cairn-server"; @@ -671,10 +555,9 @@ }; }; - # 🔴 THE GO CLIENT IS NOW `packages.default`/`apps.default`, AND THE PYTHON ONE IS STILL - # SHIPPED AS `packages.cairn`. That is a DEFAULT CUTOVER, not a deletion: the oracle, its - # `lib/`, `checks.client-resolves-its-lib` and the parity gate are all untouched, and - # Python is retired at P8. + # 🔴 THE GO CLIENT IS `packages.default`/`apps.default` — AND SINCE THE PYTHON CLIENT WAS + # RETIRED, THE ONLY CLIENT. The cutover came first (below) and the retirement later, as + # two separate decisions. # # 🔴 WHAT LICENSED THE FLIP WAS AN OPERATOR DECISION, NOT A GREEN GATE — RECORDED HERE # SO NOBODY RE-DERIVES IT FROM THE GATE. An earlier draft took the flip on exactly that @@ -686,14 +569,11 @@ # The read verbs route now and that guard is deleted. That closure is a PRECONDITION, # not the licence. # - # ⚠ THE FLIP WIDENS THE CLI CONTRACT, AND THAT IS ITS COST RATHER THAN A SIDE EFFECT - # (`tests/parity/README.md` residual 7). `cairn -verbs` and `cairn -exit-codes` exit 0 - # with a table on stdout here where the oracle's argparse exits 2 with `usage:`, so a - # single-dash token `nix run github:…/cairn` refused BEFORE this commit answers 0 AFTER - # it, for every consumer who does not name `#cairn`. `README.md` carries the - # announcement; measured at both points on the flip's branch. + # ⚠ THE FLIP WIDENED THE CLI CONTRACT: `cairn -verbs` and `cairn -exit-codes` exit 0 with a + # table on stdout here where the retired Python client's argparse exited 2 with `usage:`. + # `README.md` documents both flags as public surface. # - # 🔴 `gitMinimal` ON THE WRAPPER'S PATH, FOR THE SAME REASON THE PYTHON PACKAGE HAS IT. + # 🔴 `gitMinimal` ON THE WRAPPER'S PATH. # The client invokes `git` by BARE NAME to derive a repo's scope # (`internal/client/reposcope.go`), so a package that did not carry its own answer # would inherit whatever the caller's PATH holds — and `cairn recall` with no `--scope` @@ -720,7 +600,7 @@ ''; meta = with pkgs.lib; { - description = "The Go port of the cairn client (P2: parity-gated against the Python one)"; + description = "The cairn client"; homepage = "https://github.com/ZacxDev/cairn"; license = licenses.mit; mainProgram = "cairn"; @@ -1043,33 +923,30 @@ doCheck = false; }; - # The screenshot generator's data input: `tests/reader_fixtures.py`, the `lib/` it imports and - # the `server/server.py` it parses at import — text, scanned by `tests/leakscan.py`, and NOTHING - # else from the tree. + # The screenshot generator's data input: `tests/reader_fixtures.py` (a builder with no imports + # beyond the standard library) and the FROZEN fixture file whose `scopes`/`entries` it + # materialises — text, scanned by `tests/leakscan.py`, and NOTHING else from the tree. (Until + # the Python oracle was retired the builder DEFINED the world itself and needed `lib/` and + # `server/server.py` beside it; the world was carried over byte-for-byte into the fixture.) # # 🔴 `renameScope` IS THE PROVENANCE CONTROL'S HOOK, NOT A FEATURE: it renames one fixture scope - # in the builder, and `checks.ui-screenshots-are-current` requires the render to CHANGE under it — - # so "the committed bytes equal the derivation" is a claim about the fixture world rather than - # about a picture that would look the same whatever the fixture said. + # in the copied fixture, and `checks.ui-screenshots-are-current` requires the render to CHANGE + # under it — so "the committed bytes equal the derivation" is a claim about the fixture world + # rather than about a picture that would look the same whatever the fixture said. uiScreenshotFixture = pkgs: renameScope: pkgs.runCommand "cairn-ui-screenshot-fixture" { nativeBuildInputs = [ pkgs.gnused pkgs.gnugrep ]; } '' - mkdir -p "$out/tests" "$out/server" - cp ${./server/server.py} "$out/server/server.py" - cp -r ${pkgs.lib.cleanSourceWith { - src = ./lib; - name = "cairn-fixture-lib"; - filter = path: type: !(pkgs.lib.hasSuffix ".pyc" (toString path)) - && baseNameOf path != "__pycache__"; - }} "$out/lib" + mkdir -p "$out/tests" "$out/internal/report/testdata" cp ${./tests/reader_fixtures.py} "$out/tests/reader_fixtures.py" + cp ${./internal/report/testdata/reader_fixtures.json} "$out/internal/report/testdata/reader_fixtures.json" chmod -R u+w "$out" ${pkgs.lib.optionalString renameScope '' - n=$(grep -c 'alpha-notes' "$out/tests/reader_fixtures.py" || true) + f="$out/internal/report/testdata/reader_fixtures.json" + n=$(grep -c 'alpha-notes' "$f" || true) if [ "$n" = 0 ]; then echo "FAIL (could not vouch): the provenance control's scope 'alpha-notes' is not in the fixture" >&2 exit 2 fi - sed -i 's/alpha-notes/alpha-renamed/g' "$out/tests/reader_fixtures.py" + sed -i 's/alpha-notes/alpha-renamed/g' "$f" ''} ''; @@ -1155,165 +1032,26 @@ ''; }; - mkCairn = pkgs: pkgs.stdenv.mkDerivation { - pname = "cairn"; - inherit version; - src = onlyCode pkgs; - - strictDeps = true; - nativeBuildInputs = [ pkgs.makeWrapper ]; - dontBuild = true; - - # 🔴 `lib/` MUST SIT BESIDE THE REAL SCRIPT, AND PYTHONPATH IS NOT A - # SUBSTITUTE. The client finds its siblings with - # `Path(__file__).resolve().parent / "lib"`, and `.resolve()` follows - # symlinks — so the directory that must contain `lib/` is the one - # holding the REAL file, never the one holding whatever was invoked. - # Hence real script and `lib/` together under `libexec`, with `bin/` - # holding a wrapper that execs it. Exporting PYTHONPATH instead would - # make the modules reachable by a SECOND mechanism shadowing the first, - # leaving the file's own stated one silently dead — so the next person - # to move this layout would see nothing break until they also dropped - # the wrapper. - installPhase = '' - runHook preInstall - - install -Dm755 cairn $out/libexec/cairn/cairn - install -Dm644 -t $out/libexec/cairn/lib lib/*.py - - # `--replace-fail`, never `--replace`: a substitution that matches - # nothing must be an error. A silently-unmatched shebang rewrite - # leaves `/usr/bin/env python3` in a store path, which then works on - # the machine that built it and fails on one with no system python — - # a failure landing nowhere near its cause. - substituteInPlace $out/libexec/cairn/cairn \ - --replace-fail '#!/usr/bin/env python3' '#!${(python pkgs)}/bin/python3' - - # `git` is invoked by BARE NAME (`lib/entry_shape.py::_git`) to derive - # a repo's scope. Prefixed rather than suffixed so the package carries - # its own answer instead of inheriting whatever the caller's PATH holds. - # - # `gitMinimal`, not `git`: the only invocations are `rev-parse` and - # `merge-base`, and full `git` drags perl's CGI/libwww stack — 385 MiB - # of a 386 MiB closure, paid on every consumer's switch, for an 800 KB - # stdlib script. gitMinimal supplies both and closes at 159 MiB. - makeWrapper $out/libexec/cairn/cairn $out/bin/cairn \ - --prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.gitMinimal ]} - - runHook postInstall - ''; - - # 🔴 WITHOUT THIS THE DERIVATION IS NOT REPRODUCIBLE, and `nix build - # --rebuild` says so: the install check below IMPORTS the whole closure, - # CPython writes `lib/__pycache__/*.pyc` into `$out` before the daemon - # seals it, and each `.pyc` header records the source mtime as build - # WALL-CLOCK while the installed `.py` are normalised to mtime 1. Two - # builds of one input then differ in exactly those seven files. - # Worse, that bytecode is permanently INVALID and never used — the - # recorded mtime never matches the sealed source, so every invocation - # recompiles anyway and the files are dead weight in the closure. - PYTHONDONTWRITEBYTECODE = "1"; - - # 🔴 AT BUILD TIME, NOT ONLY IN `checks`. A consumer pinning this flake - # builds the PACKAGE and never runs `nix flake check`, so a - # sibling-import break would otherwise reach a machine and be found by - # the operator at the moment they wanted to read a note. - # - # ⚠ `--help` IS SUFFICIENT FOR THAT BREAK — an earlier version of this - # comment claimed the opposite ("argparse is built before any subcommand - # imports anything, so `--help` alone is not evidence") and it was - # MEASURED FALSE: the imports are at module scope, so removing `lib/` - # kills `--help` at line 91 with `ModuleNotFoundError: timeouts`, right - # here, before `checks.client-resolves-its-lib` can even be built. - # `checks.client-resolves-its-lib` therefore earns its place on the - # POSITIVE side — it runs a real subcommand to completion against a real - # cache root — not as a deeper detector of a missing `lib/`. - doInstallCheck = true; - installCheckPhase = '' - runHook preInstallCheck - $out/bin/cairn --help > /dev/null - runHook postInstallCheck - ''; - - meta = with pkgs.lib; { - description = "Read-through client for the cairn subsystem-note store"; - homepage = "https://github.com/ZacxDev/cairn"; - license = licenses.mit; - mainProgram = "cairn"; - platforms = platforms.unix; - }; - }; - - mkServerImage = pkgs: - let - # ALL of `lib/`, not an enumeration. The Dockerfile enumerates because - # a docker build context is a directory it must not slurp wholesale, - # and `test_the_image_copies_every_module_it_needs` exists to keep - # that hand-written list honest. Here the source filter has already - # excluded everything that is not code, so there is no list to keep - # honest and no closure for it to get wrong — the module set cannot - # drift from the imports because it is not stated separately. - tree = pkgs.runCommand "cairn-server-tree" { } '' - mkdir -p $out/app/lib $out/app/server - cp ${onlyCode pkgs}/lib/*.py $out/app/lib/ - cp ${onlyCode pkgs}/server/server.py $out/app/server/ - ''; - in - pkgs.dockerTools.buildLayeredImage { - name = "cairn-store"; - tag = version; - contents = [ tree ] ++ serverTools pkgs; - - # `/data` is where the PVC mounts and `/home/nonroot` is what HOME - # names; both are created and owned here so the image is runnable - # without a mount. ⚠ UNGUARDED: nothing in this repo checks either - # line. `publish-image.yml`'s smoke run starts this image with no - # token source and expects a NON-ZERO exit, and `server/server.py` - # returns on the missing token before it opens the store root. - fakeRootCommands = '' - mkdir -p ./data ./home/nonroot - chown -R ${toString serverUid}:${toString serverUid} ./data ./home/nonroot - ''; - enableFakechroot = true; - - config = { - Cmd = [ "${(python pkgs)}/bin/python3" "/app/server/server.py" ]; - # 🔴 `PATH` IS DECLARED, and its absence was not cosmetic. Without - # it `kubectl exec … -- tar` resolves nothing even once busybox is - # in the image, so the seed path fails with `executable file not - # found in $PATH` rather than anything naming the real cause. - Env = pkgs.lib.mapAttrsToList (k: v: "${k}=${v}") - (serverEnv // { PATH = serverPath; }); - User = "${toString serverUid}:${toString serverUid}"; - ExposedPorts = { "${toString serverPort}/tcp" = { }; }; - WorkingDir = "/app"; - }; - }; - # 🔴 THE GO POD'S IMAGE. IT IS AN ADDITION, AND UNTIL IT LANDED THERE WAS NO # GO SERVER IMAGE AT ALL — `packages.cairn-server-go` is a bare binary package. - # ⚠ IT IS NOW PUBLISHED: `.github/workflows/publish-image.yml` pushes this output - # to the `cairn-store-go` ghcr package beside the Python pod's `cairn-store`, - # under the same `sha-<40-hex>` tag scheme. 🔴 AND IT IS NOW DEPLOYED: the + # ⚠ IT IS PUBLISHED: `.github/workflows/publish-image.yml` pushes this output + # to the `cairn-store-go` ghcr package under a `sha-<40-hex>` tag. (The retired + # Python pod was published beside it as `cairn-store`; that leg was deleted with it.) + # 🔴 AND IT IS NOW DEPLOYED: the # cluster pulls `cairn-store-go`. ⚠ This read "PUBLISHED IS NOT DEPLOYED — no # manifest references it, and the cutover is a separate decision"; the cutover # was taken and both halves went false. It is the site an earlier draft of the # sweep MISSED while editing this very file — and then cited, from # `publish-image.yml`, as proof `flake.nix` had never made the claim. # - # 🔴 A THIRD BUILD, NOT A THIRD STATEMENT OF THE CONTRACT, AND THAT DISTINCTION - # IS THE WHOLE DESIGN. `server/README.md` says "do not add a third way to produce - # this pod: a third statement of the runtime contract would be outside that pin, - # and it would be the one that actually ships". The hazard it names is a COPY. - # This derivation states nothing: uid, port, exposed port and every environment - # variable come from `serverUid`/`serverPort`/`serverEnvGo`, which are the same - # bindings `tests/test_flake_image_matches_dockerfile.py` pins against - # `server/Dockerfile`. `tests/test_flake_go_image_runtime_contract.py` is what - # closes the loop on this side, because being DERIVED is a property of today's - # source and a copy is one edit away. + # 🔴 IT STATES NOTHING OF THE CONTRACT ITSELF. Uid, port, exposed port and every + # environment variable come from `serverUid`/`serverPort`/`serverEnv` above; + # `tests/test_flake_go_image_runtime_contract.py` closes the loop, because being + # DERIVED is a property of today's source and a copy is one edit away. (It was once + # a THIRD build of the pod beside the Python image and `server/Dockerfile`, which is + # why that test exists; both are retired.) # - # 🔴 IT CARRIES BUSYBOX AND DECLARES `PATH` FOR EXACTLY THE REASON `mkServerImage` - # DOES — see the 🔴 above `serverPath`. The operational procedures are the pod's, + # 🔴 IT CARRIES BUSYBOX AND DECLARES `PATH` — see the 🔴 above `serverPath`. The operational procedures are the pod's, # not the interpreter's: `server/seed.sh` pushes the store through # `kubectl exec … -- tar -xf -` and runs its containment guard through `sh -c`, # and `server/README.md`'s credential revocation is @@ -1322,16 +1060,13 @@ # verdict — so an image without a shell would take away a revocation path that # the binary itself still implements. # - # ⚠ `Cmd` NAMES THE BINARY BY ABSOLUTE STORE PATH, like `mkServerImage` names its - # interpreter. `/bin/cairn-server` would also resolve, and that is the reason not + # ⚠ `Cmd` NAMES THE BINARY BY ABSOLUTE STORE PATH. `/bin/cairn-server` would also resolve, and that is the reason not # to use it: the entrypoint would then depend on `contents` placing the package's # `bin/` at the image root AND on `PATH`, so a change to either would turn a # wiring mistake into a container that does not start. # - # ⚠ `WorkingDir = "/"`, not `/app`: there is no `/app`. The Python pod's `/app` is - # where its SOURCE is copied, and a single binary has no source tree. `/` matches - # what `server/Dockerfile` leaves the Python pod at, and every path the server - # touches — the store, the token file — is absolute. + # ⚠ `WorkingDir = "/"`: a single binary has no source tree to sit in, and every + # path the server touches — the store, the token file — is absolute. mkGoServerImage = pkgs: let goServer = mkGoServer pkgs; in @@ -1342,7 +1077,7 @@ # `/data` is where the PVC mounts; created and owned here so the image is # runnable without a mount. No `/home/nonroot`: this pod has no `HOME` — see - # `serverEnvPythonOnly`. + # `serverEnv`. # # ⚠ THE `chown` IS UNGUARDED, AND THE RETRACTED CLAIM WAS THAT A SMOKE TEST # WOULD CATCH IT. The sentence that used to carry this — "nothing runs this @@ -1371,7 +1106,7 @@ config = { Cmd = [ "${pkgs.lib.getExe goServer}" ]; - Env = pkgs.lib.mapAttrsToList (k: v: "${k}=${v}") (serverEnvGo // { + Env = pkgs.lib.mapAttrsToList (k: v: "${k}=${v}") (serverEnv // { PATH = serverPath; SSL_CERT_FILE = goServerCaBundle pkgs; }); @@ -1448,12 +1183,9 @@ { packages = forAll (pkgs: { - cairn = mkCairn pkgs; - # 🔴 `default` IS THE GO CLIENT, AND `cairn` IS STILL THE PYTHON ONE. The - # cutover was an OPERATOR DECISION taken after residual 8 closed — never a - # gate outcome; see the block above `mkGoClient` for the reverted draft that - # read it the other way. `packages.cairn` is NOT deleted here: it is still - # the oracle the parity gate measures against, and it goes at P8. + # 🔴 `default` IS THE GO CLIENT — the only client. The cutover was an OPERATOR + # DECISION, never a gate outcome; the Python client (`packages.cairn`, `apps.cairn`) + # was retired afterwards and there is no `#cairn` attribute any more. # # 🔴 THIS LINE AND `apps.default` MOVE TOGETHER OR NOT AT ALL — see the block # above `apps` for why one alone gives two clients under one name. @@ -1474,27 +1206,21 @@ cairn-clickup = mkClickupPlugin pkgs; } // nixpkgs.lib.optionalAttrs (builtins.elem pkgs.stdenv.hostPlatform.system linuxSystems) { - server-image = mkServerImage pkgs; - # 🔴 THE PYTHON POD KEEPS THE UNSUFFIXED NAME, and that is not inertia: - # `.github/workflows/publish-image.yml` builds `packages.server-image` by - # name, `server/README.md` documents it, and consumers pin it. Renaming it to - # make room for this one would change what gets PUBLISHED, which is a deploy - # decision and not a build. `server-image-go` is published under its OWN - # package name (`cairn-store-go`), which is what keeps that true. + # ⚠ `server-image-go` KEEPS ITS SUFFIX although the Python `server-image` it was + # distinguished from is retired: `publish-image.yml` builds it by name and + # consumers pin the `cairn-store-go` package it publishes to. Renaming either is a + # deploy decision, not a cleanup. server-image-go = mkGoServerImage pkgs; - # 🔴 `ui-image`, NOT `ui-image-go`. The `-go` suffix on the pod distinguishes - # it from a PYTHON sibling that exists and is still published; this surface has - # no second implementation and never had one, so a suffix would imply a - # counterpart a reader would then go looking for. + # 🔴 `ui-image`, NOT `ui-image-go`. This surface never had a second + # implementation, so a suffix would imply a counterpart a reader would then go + # looking for. # # ⚠ IT IS PUBLISHED, AND THE CLAIM THAT IT WAS NOT IS RETRACTED — the wording # here has now been wrong in BOTH directions, which is why the record is kept. # It first read "It publishes to its own ghcr package", present tense, for a leg # the same change deliberately excluded. It was then corrected to "NOTHING - # PUBLISHES IT YET — `publish-image.yml` pushes `server-image` and - # `server-image-go` and no third leg exists", which is the sentence that went - # stale: that workflow now builds this derivation, pushes it under the OCI name + # PUBLISHES IT YET", which is the sentence that went stale: that workflow now builds this derivation, pushes it under the OCI name # below, and PROVES the result pullable with no credentials. So the name below # is a package anybody can pull. ui-image = mkGoUIImage pkgs; @@ -1507,23 +1233,14 @@ # `nix profile install` and every flake input got the other — one name, two # clients, differing by which command the consumer happened to use. # - # 🔴 `apps.cairn` DELIBERATELY DID NOT MOVE, AND IT IS PINNED RATHER THAN LEFT TO - # PROSE. It is the escape hatch the announcement names: `nix run - # github:…/cairn#cairn` is still the Python client, which is what makes residual - # 7's widening opt-out-able rather than forced. Because `README.md` now PROMISES - # that, repointing this one line at `mkGoClient` would defeat the promise while - # `packages.default`/`apps.default`/`packages.cairn` all stayed exactly right — - # the half-flip class one attribute over. `default-is-the-go-client` asserts it. + # ⚠ THERE IS NO `apps.cairn` ANY MORE. It was the opt-out to the retired Python + # client, kept while that client shipped; it went with `packages.cairn`. # # ⚠ THERE IS NO `apps.cairn-go`, DELIBERATELY. `nix run .#cairn-go` already # resolves through `packages.cairn-go`'s `mainProgram = "cairn"` — measured, not - # assumed — so an entry here would be a third name for one binary with nothing to - # buy, and `apps.default` above is now a fourth. + # assumed — so an entry here would be a second name for one binary with nothing to + # buy. apps = forAll (pkgs: { - cairn = { - type = "app"; - program = "${nixpkgs.lib.getExe (mkCairn pkgs)}"; - }; default = { type = "app"; program = "${nixpkgs.lib.getExe (mkGoClient pkgs)}"; @@ -1531,7 +1248,7 @@ # ⚠ A DEVELOPER COMMAND, NOT A CLIENT, AND IT IS THE ONE APP HERE THAT WRITES TO # THE WORKING TREE. `nix run .#build-ui-stylesheet` regenerates # `internal/ui/app.css` from `internal/ui/tailwind.css`. It is not part of the - # default/`cairn` wiring the check below pins, and adding it changes neither. + # default wiring the check below pins, and adding it changes nothing there. build-ui-stylesheet = { type = "app"; program = "${nixpkgs.lib.getExe (buildUIStylesheet pkgs)}"; @@ -1551,7 +1268,6 @@ }); checks = forAll (pkgs: { - cairn = mkCairn pkgs; # Each module's suite, once; every Go package below depends on its module's entry. go-module-tests = mkGoModuleTests pkgs; plugins-module-tests = mkPluginModuleTests pkgs; @@ -1747,10 +1463,8 @@ # 🔴 WHICH CLIENT THE UNQUALIFIED NAMES RESOLVE TO, PINNED AS A RELATIONSHIP # BETWEEN RESOLVED DERIVATIONS. Before this check, NOTHING in the repository # asserted it: `packages.default`/`apps.default` appeared in `flake.nix` and in no - # test, the two other `checks.*` entries name `mkCairn`/`mkGoClient` explicitly, - # every CI job builds by explicit attribute, and the parity harness builds with - # `go build ./cmd/cairn` and runs the oracle script directly. The wiring was pinned - # by PROSE, and prose is walkable three ways: + # test, and every CI job builds by explicit attribute. The wiring was pinned by + # PROSE, and prose is walkable: # # • a flip taken on the wrong licence, REVERTED once already, could land fully # green — nothing here would have noticed either the flip or the revert; @@ -1759,11 +1473,9 @@ # resolves `apps.default` FIRST and only falls back to `packages.default`'s # `mainProgram`, so the run path and the build path would serve two different # clients under ONE name, differing by which command the consumer used; - # • a later accidental revert of either line would be invisible; - # • and the SAME half-flip one attribute over: repointing `apps.cairn` at the Go - # client leaves all three of the assertions above green — `packages.cairn` is - # untouched by it — while the ESCAPE HATCH `README.md` promises silently - # becomes the Go client. That is why `apps.cairn` is compared here too. + # • a later accidental revert of either line would be invisible. + # (While the Python client shipped this also pinned `apps.cairn`/`packages.cairn` as + # the documented opt-out; both were retired with it.) # # 🔴 IT COMPARES RESOLVED DERIVATIONS, NOT SPELLINGS. A guard matching the string # `mkGoClient` in this file is walkable by renaming the binding while the wiring @@ -1789,11 +1501,8 @@ # says nothing about `mainProgram`, and no CI job runs `.#` bare. The NAME check # below is the second, independent reading. # - # ⚠ WHAT IT DOES NOT CLAIM: nothing about either client's BEHAVIOUR; and the name - # check is insensitive on the PYTHON side, where `pname` is already `cairn`, so a - # `mainProgram` removed from `mkCairn` would leave it green. That is a real gap, - # named rather than papered over — the hazard it exists for is `mkGoClient`, whose - # pname and mainProgram DIFFER. + # ⚠ WHAT IT DOES NOT CLAIM: anything about the client's BEHAVIOUR. The name check + # exists for `mkGoClient`, whose pname (`cairn-go`) and mainProgram (`cairn`) DIFFER. default-is-the-go-client = let system = pkgs.stdenv.hostPlatform.system; @@ -1803,14 +1512,10 @@ exe = drv: builtins.unsafeDiscardStringContext (nixpkgs.lib.getExe drv); defaultPkg = path self.packages.${system}.default; goPkg = path self.packages.${system}.cairn-go; - pyPkg = path self.packages.${system}.cairn; defaultExe = exe self.packages.${system}.default; - pyExe = exe self.packages.${system}.cairn; appProgram = builtins.unsafeDiscardStringContext self.apps.${system}.default.program; - pyAppProgram = - builtins.unsafeDiscardStringContext self.apps.${system}.cairn.program; - # Both clients declare `mainProgram = "cairn"`, which is the single name every + # The client declares `mainProgram = "cairn"`, which is the single name every # documented invocation uses. `mkGoClient`'s pname is `cairn-go`, so this is # the one operand where the fallback is DISTINGUISHABLE from the intent. wantExeName = "cairn"; @@ -1826,8 +1531,7 @@ # the floor every equality below rests on — two empty strings compare equal, # so the comparisons are only as good as their operands being store paths. # Keep it, and do not count it as coverage of a defect anyone has observed. - for p in '${defaultPkg}' '${goPkg}' '${pyPkg}' '${defaultExe}' '${pyExe}' \ - '${appProgram}' '${pyAppProgram}'; do + for p in '${defaultPkg}' '${goPkg}' '${defaultExe}' '${appProgram}'; do case "$p" in /nix/store/?*) ;; *) @@ -1859,33 +1563,6 @@ failed=1 fi - if [ "${pyPkg}" = "${defaultPkg}" ]; then - echo "FAIL: packages.cairn and packages.default are the SAME derivation." - echo " packages.cairn = packages.default = ${pyPkg}" - echo " \`#cairn\` is the opt-out README.md announces, and this state points" - echo " it at the Go client. It would NOT redden the parity gate —" - echo " tests/parity/harness.py runs the oracle SCRIPT directly and never" - echo " builds this package — which is exactly why it is asserted here." - failed=1 - fi - - # 🔴 THE ESCAPE HATCH'S `nix run` SPELLING, WHICH THE THREE ABOVE LEAVE FREE. - # `nix run github:…/cairn#cairn` resolves `apps.cairn` FIRST, the same - # precedence that makes `apps.default` load-bearing. README.md now PROMISES - # this spelling opts out, and a flake input taking `apps.${system}.cairn` gets - # the same attribute, so a repoint here is a silent flip of the documented - # escape hatch with every other assertion in this file still green. - if [ "${pyAppProgram}" != "${pyExe}" ]; then - echo "FAIL: apps.cairn does NOT point at packages.cairn — the announced opt-out" - echo " resolves to something else." - echo " apps.cairn.program = ${pyAppProgram}" - echo " getExe packages.cairn = ${pyExe}" - echo " README.md names \`#cairn\` as the opt-out from the default flip, in" - echo " both the CLI and the flake-input spelling. If this pair disagrees," - echo " the opt-out is a promise the tree does not keep." - failed=1 - fi - # 🔴 THE NAME, NOT ANOTHER EQUALITY — the common-mode reading. See the block # above: a removed `meta.mainProgram` moves BOTH sides of an equality at once, # so the equalities cannot see it. `getExe` falls back to the pname with only a @@ -1893,9 +1570,7 @@ # and breaks every documented invocation while the comparisons stay green. for spec in \ 'getExe packages.default|${builtins.baseNameOf defaultExe}' \ - 'apps.default.program|${builtins.baseNameOf appProgram}' \ - 'getExe packages.cairn|${builtins.baseNameOf pyExe}' \ - 'apps.cairn.program|${builtins.baseNameOf pyAppProgram}'; do + 'apps.default.program|${builtins.baseNameOf appProgram}'; do label="''${spec%%|*}" name="''${spec##*|}" if [ "$name" != '${wantExeName}' ]; then @@ -1913,15 +1588,11 @@ echo "ok: packages.default == packages.cairn-go == ${defaultPkg}" echo " apps.default.program == ${appProgram}" - echo " packages.cairn is distinct == ${pyPkg}" - echo " apps.cairn.program == getExe packages.cairn == ${pyAppProgram}" - echo " all four resolved programs are named '${wantExeName}'" + echo " both resolved programs are named '${wantExeName}'" { echo "packages.default ${defaultPkg}" echo "packages.cairn-go ${goPkg}" - echo "packages.cairn ${pyPkg}" echo "apps.default.program ${appProgram}" - echo "apps.cairn.program ${pyAppProgram}" echo "exe-name ${wantExeName}" } > $out ''; @@ -1951,22 +1622,20 @@ ''; # 🔴 THE GO CLIENT'S OWN LEDGER, READ OUT OF THE RUNNING BINARY — the one claim a - # compile cannot make, and the one the PYTHON-side gates are structurally blind to. - # `capability_ledger.cli_verbs_from_parser` asks the PYTHON argparse parser what - # subcommands it has and has no equivalent for a compiled program, so a Go client - # that GAINED a verb or silently LOST one leaves that gate green. + # compile cannot make: a client that GAINED a verb or silently LOST one, or whose exit + # codes moved, is a red check here rather than a surprise for a caller. # # 🔴 AND IT IS A PAIR, NOT A ZERO. A check that asserted only "the command exited 0" # would pass for a binary that printed nothing. The exact set is pinned by hand here - # — the same verbs `tests/test_capability_ledger.py` discovers from the Python parser, - # which is what makes the two implementations comparable at all. 🔴 THE SET IS THE + # — and `tests/test_capability_ledger.py` pins that hand list against the capability + # ledger, so it is not free text. 🔴 THE SET IS THE # HEREDOC BELOW AND THE COUNT IS NOT WRITTEN DOWN ANYWHERE IN THIS COMMENT: a number # here would be a hand list one word long, which is the thing the heredoc replaced. # # ⚠ WHAT THIS SANDBOX CANNOT HAVE: no store, no token, no network and no HOME with a - # cache root, so it exercises the LEDGERS and nothing about reading or writing. The - # parity harness is what measures behaviour, and it needs a running pod that a nix - # sandbox is the wrong place for. + # cache root, so it exercises the LEDGERS and nothing about reading or writing. The Go + # client's own tests (against an in-process pod) and the end-to-end scripts under + # `tests/` are what measure behaviour. go-client-declares-its-verbs = pkgs.runCommand "cairn-go-client-declares-its-verbs" { nativeBuildInputs = [ (mkGoClient pkgs) ]; } '' set -o pipefail @@ -1979,49 +1648,40 @@ exit 1 fi - cat > want-verbs.txt <<'EOF' + # 🔴 ONE LIST, SORTED, AND NOT FREE TEXT: `tests/test_capability_ledger.py` pins it + # against `testlib/capability_ledger.LEDGER`'s verbs, so a verb cannot be added + # here alone without a red test. (Until the Python client was retired this was two + # lists — the verbs both clients had, and the Go-only ones; the split was FOLDED, + # not dropped, when there stopped being a second client to differ from.) + cat > want-all-verbs.txt <<'EOF' append writes - create writes - doctor reads - ls-entries reads - put writes - recall reads - routes reads - search reads - sync reads - validate reads - EOF - # 🔴 THE GO-ONLY VERBS, DECLARED APART FROM THE SHARED SET ABOVE. Decision 3 of - # the arcs/sessions plan puts new verbs in the Go client only, so a verb here has - # NO Python twin. Neither list is free text: `tests/test_capability_ledger.py` - # pins the one above against the PYTHON parser and this one against - # `capability_ledger.GO_ONLY_VERBS` (the `go_only` rows), so a verb cannot be - # moved between them, or declared Go-only here alone, without a red test. The - # first, `sessions`, is the arcs/sessions S2 slice; the arc registry is S3; the four - # `memo-*` verbs are scope mail's S3 (decision 8 of the scope-mail plan); `sources` - # is the scope-refs plan's S3 and `audit-refs` its S5; `transcript` is the transcripts - # plan's S8 (its decision 17); `log` is Phase 1 of the v1 event-log plan; `associate`, `refs`, `parse` - # and `fold` are its Phase 5 (the Python client's last consumers move to the Go one). - cat > want-go-only-verbs.txt <<'EOF' arc-register writes - associate reads arc-show reads arcs reads + associate reads audit-refs reads + create writes + doctor reads + fold reads log reads + ls-entries reads memo-check reads memo-read reads memo-retract writes memo-send writes - fold reads parse reads + put writes + recall reads refs reads + routes reads + search reads sessions reads sources reads + sync reads transcript reads + validate reads EOF - sed -i 's/^ *//; /^$/d' want-verbs.txt want-go-only-verbs.txt - sort -u want-verbs.txt want-go-only-verbs.txt > want-all-verbs.txt + sed -i 's/^ *//; /^$/d' want-all-verbs.txt if ! diff -u want-all-verbs.txt verbs.txt; then echo "FAIL: the Go client's declared verb set is not the set this check names." @@ -2039,10 +1699,8 @@ exit 1 fi - # 🔴 THE SHARED EXIT-CODE SET, COMPUTED FROM THE BINARY'S OWN TWO TABLES. The Python - # ledger computes its intersection over the PYTHON client's nine codes, so a Go-only - # code colliding with `doctor`'s 10 leaves it green. `{0, 9}` is the documented set - # and this is where the Go side's version of it is checked. + # 🔴 THE SHARED EXIT-CODE SET, COMPUTED FROM THE BINARY'S OWN TWO TABLES. `{0, 9}` is + # the documented set; a client code colliding with `doctor`'s 10 would move it. grep '^client ' codes.txt | awk '{print $3}' | sort -u > client-values.txt grep '^doctor ' codes.txt | awk '{print $3}' | sort -u > doctor-values.txt comm -12 client-values.txt doctor-values.txt > shared.txt @@ -2070,14 +1728,13 @@ # command exited 0" would pass for a binary that printed nothing, which # is the reassuring zero this repository keeps finding. So the exact # route set is pinned, spelled out by hand — the same set - # `tests/test_conformance_suite.py` spells for the oracle, which is what - # makes the two implementations comparable at all. + # `tests/test_conformance_suite.py` spells as `EXPECTED_ROUTES`. # # ⚠ WHAT THIS SANDBOX CANNOT HAVE, stated rather than assumed away: no # store, no token file and no network, so it exercises the LEDGER and # nothing about serving. The conformance corpus is what measures the - # served behaviour, and it needs a running pair of servers that a nix - # sandbox is the wrong place for. + # served behaviour, and it needs a running server that a nix sandbox is + # the wrong place for. go-server-declares-its-routes = pkgs.runCommand "cairn-go-server-declares-its-routes" { nativeBuildInputs = [ (mkGoServer pkgs) ]; } '' set -o pipefail @@ -2089,46 +1746,37 @@ exit 1 fi - cat > want.txt <<'EOF' - GET recall - GET search - GET snapshot - HEAD recall - HEAD search - HEAD snapshot - POST entry - PUT entry - EOF - # 🔴 THE GO-ONLY ROUTES, DECLARED APART FROM THE ORACLE-SHARED SET ABOVE — - # routes the deployed pod serves and `server/server.py` does not (decision 3 of - # the arcs/sessions plan). `tests/test_capability_ledger.py` pins the list above - # against the oracle's tables and this one against the `go_only` rows of - # `tests/conformance/requests.json` AND of the capability ledger. The first, - # `sessions/`, is the arcs/sessions S2 slice; `arcs`/`arc` are S3's; - # `sources/` is S2 of the scope-refs plan; `whoami` is the caller's own - # self-view. - cat > want-go-only.txt <<'EOF' + # One list, sorted. `tests/test_capability_ledger.py` pins it against the ledger's + # routes (the old Go-only half was folded in when the oracle was retired). + cat > want-all.txt <<'EOF' GET arc GET arcs + GET recall + GET search GET sessions + GET snapshot GET sources GET whoami HEAD arc HEAD arcs + HEAD recall + HEAD search HEAD sessions + HEAD snapshot HEAD sources HEAD whoami + POST entry PUT arc + PUT entry EOF - sed -i 's/^ *//; /^$/d' want.txt want-go-only.txt - sort -u want.txt want-go-only.txt > want-all.txt + sed -i 's/^ *//; /^$/d' want-all.txt if ! diff -u want-all.txt routes.txt; then echo "FAIL: the Go server's declared route set is not the set this check" echo " names. Adding a row to a dispatch table is adding a public," echo " internet-reachable endpoint, and this is where somebody has" echo " to think about it — update the conformance request list and" - echo " regenerate in the same change." + echo " record its goldens (run_go.sh record) in the same change." exit 1 fi @@ -2175,9 +1823,8 @@ # DECISION RATHER THAN A GAP — a draft of this file carried one, modelled on # `go-server-declares-its-routes` above. That check earns its place because # the pod's route set is the SERVED CONTRACT `tests/conformance/requests.json` - # replays and the corpus builder is Python, blind to a compiled binary: the - # ledger read out of the running program is a genuinely second instrument in - # a second environment. The UI has neither — `ui.DeclaredRoutes()` derives + # replays, and the ledger read out of the running program is a genuinely second + # instrument in a second environment. The UI has neither — `ui.DeclaredRoutes()` derives # from the same map its dispatcher reads, and the only expectation anywhere # is a hand-written list. A check that ran the binary to print that list and # diffed it against a third hand-written copy would restate one claim down a @@ -2188,79 +1835,14 @@ # it. When a later phase gives this surface an external corpus, the second # tier comes back with it. - # 🔴 THIS CHECK IS THE POSITIVE HALF, AND IT IS *NOT* THE DETECTOR FOR A - # MISSING `lib/` — `doInstallCheck` above is, and it fires first. - # - # An earlier version of this comment claimed the opposite: that dropping - # `lib/` would leave `cairn` with a working `--help` because "argparse is - # built before any subcommand imports anything". MEASURED FALSE — the - # imports are at MODULE SCOPE (`cairn:91`), so `--help` dies with - # `ModuleNotFoundError: timeouts` during the package's own install check, - # and this derivation never gets built. The sentence is deleted rather - # than reworded because a maintainer who believed it would conclude - # `doInstallCheck` proves nothing and delete the only build-time gate - # standing between a broken client and a consumer's `home-manager switch`. - # - # What this check adds is DEPTH THE INSTALL CHECK DOES NOT REACH: it runs - # a real subcommand to completion against a real cache root, driving - # `cairn_doctor`, `subsystem_read_store` and `entry_shape` through their - # logic rather than merely importing them. - # - # Its EXIT CODE is deliberately not asserted. `doctor` reports on an - # operator's configuration, and in a build sandbox there is no store, no - # token and no pod — a non-zero verdict is the CORRECT answer here, and - # demanding zero would either pin a wrong expectation or push the check - # into faking an environment. What is asserted is the thing that - # distinguishes a working package from a broken one: it ran far enough - # to produce its own report rather than dying in an import. - client-resolves-its-lib = pkgs.runCommand "cairn-client-resolves-its-lib" - { nativeBuildInputs = [ (mkCairn pkgs) ]; } '' - set -o pipefail - # HOME is unset in the sandbox and `Path.home()` is evaluated at - # import time by `subsystem_read_store` — the same reason the image - # sets it. Without this the check would fail for a reason that has - # nothing to do with what it is testing. - export HOME=$TMPDIR - - if ! cairn doctor > out.txt 2> err.txt; then - echo "note: doctor exited non-zero, which is expected with no store configured" - fi - - # 🔴 NEGATIVE-CONTROL-SHAPED ASSERTION: an ImportError is exactly what - # a lost `lib/` produces, and it is what this check exists to catch. - # Asserting its ABSENCE is only meaningful alongside the positive - # assertion below — "no error appeared" is also what a command that - # never ran produces. - if grep -qE 'ModuleNotFoundError|ImportError' err.txt; then - echo "FAIL: the packaged client could not import its own lib/:" - cat err.txt - exit 1 - fi - - # Positive: the report was actually produced. `doctor` prints one - # check line per subject, so a run that imported and executed says - # something; a run that did nothing says nothing, and that is the - # zero this pair exists to tell apart. - if ! grep -q . out.txt; then - echo "FAIL: doctor produced NO output — it cannot have run." - echo "--- stderr ---"; cat err.txt - exit 1 - fi - - echo "ok: packaged client imported its own lib/ and produced a report" - cp out.txt $out - ''; }); devShells = forAll (pkgs: { default = pkgs.mkShell ({ - # 🔴 THE SAME PIN AS THE ARTEFACTS, AND THIS WAS THE FOURTH THING. - # `pkgs.python3` here resolved to 3.14 while the package shebang, the - # image `Cmd`, `server/Dockerfile` and the CI matrix were all 3.12 — - # so the shell `shellHook` tells you to run the suite in was on a - # DIFFERENT interpreter from the one shipped, and a lock bump would - # move it again silently. That is precisely what pinning the other - # three was supposed to close. + # 🔴 THE SAME PIN AS CI. `pkgs.python3` here resolved to 3.14 while the + # CI matrix was 3.12 — so the shell `shellHook` tells you to run the suite + # in was on a DIFFERENT interpreter from the one CI runs, and a lock bump + # would move it again silently. packages = [ ((python pkgs).withPackages (ps: [ ps.pytest ])) pkgs.git @@ -2282,14 +1864,13 @@ # today. If you move one, move the other. pkgs.postgresql_18 # `server/seed.sh` stages the store with `rsync -a --delete`, and the - # seed tests in `tests/test_subsystem_store_api.py` run it for real. + # seed tests in `tests/test_seed.py` run it for real. # stdenv does not provide rsync, so without this the shell only passes # those tests on a host that happens to carry its own (workbench gets # one from `~/.nix-profile`); the remote-run workspace pod has none. pkgs.rsync - # `verify-byte-identity.sh` fetches with curl, and the byte-identity - # verifier tests run it; like rsync, the shell only passed them on a - # host that carries its own. + # `tests/conformance/run_go.sh` polls the server's `/healthz` with curl; + # like rsync, a shell without it only works on a host that carries its own. pkgs.curl ]; shellHook = '' @@ -2297,7 +1878,7 @@ echo " python3 -m pytest tests -q -p no:randomly" echo "the Go port's own tests:" echo " go test ./... && go vet ./..." - echo "the conformance corpus against the Go server (the P1 gate):" + echo "the conformance corpus against the Go server:" echo " tests/conformance/run_go.sh" echo "and the leak gate, which must pass before any push:" echo " python3 tests/leakscan.py --self-test && python3 tests/leakscan.py" diff --git a/internal/api/api_test.go b/internal/api/api_test.go index ec423707..b86a1226 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -53,24 +53,18 @@ type corpusRow struct { Method string `json:"method"` Target string `json:"target"` NegativeRoute bool `json:"negative_route"` - // GoOnly is the corpus's DECLARATION that only this server serves the row's - // route (decision 3 of the arcs/sessions plan: new surfaces are Go-only, and the - // oracle is not extended). The Python validator refuses the mark for a route the - // oracle declares; this side refuses it for a route THIS server does not - // dispatch. See `checkRouteLedger`. - GoOnly bool `json:"go_only"` } // corpusRows reads the conformance request list's rows. // -// 🔴 THIS FUNCTION IS THE GO SIDE OF A LEDGER THE SUITE CANNOT BUILD ITSELF. -// `tests/conformance/cases.declared_routes` reads the ORACLE's two dispatch tables by -// AST and fails when the declared set grows or shrinks against what the corpus -// addresses — and `tests/conformance/README.md` states plainly that this closure is -// "not closed for a non-Python implementation … so P1 has to add the equivalent ledger -// on the Go side". This is it, and it reads the SAME data file rather than a copy of -// it: a suite that replays a recorded list is structurally blind to a route added after -// the list was written, in either language. +// 🔴 THIS FUNCTION IS ONE OF TWO READERS OF ONE LEDGER, AND IT IS THE ONE THAT NEEDS NO +// BINARY. `tests/conformance/cases.declared_routes` asks the built server +// (`cairn-server -routes`) for the same set and `suite.py run` refuses to start without +// it; this test reads `DeclaredRoutes()` in-process. Both read the SAME data file rather +// than a copy of it: a suite that replays a recorded list is structurally blind to a +// route added after the list was written. (Until the Python oracle was retired, the +// suite's half read THAT server's dispatch tables by AST, and this side existed because +// that reader could not see a compiled program.) func corpusRows(t *testing.T) []corpusRow { t.Helper() path := filepath.Join(repoRoot(t), "tests", "conformance", "requests.json") @@ -113,25 +107,16 @@ func routeOf(c corpusRow) (string, bool) { // checkRouteLedger compares the routes this server declares against the routes the // corpus addresses. It is a pure function of its two operands so the guard can be fed -// a SYNTHETIC Go-only route — none exists yet — and watched to go red and green. +// a SYNTHETIC route and watched to go red and green. // // 🔴 IT FAILS WHEN THE SET GROWS **AND** WHEN IT SHRINKS. A route the corpus never // addresses is a public, internet-reachable endpoint nothing replays; a corpus row for // a route this server no longer serves records a 404 as if it were the contract. -// -// 🔴 `go_only` ROWS COUNT AS COVERAGE HERE, AND THAT IS THE WHOLE OF WHAT "HONOURED" -// MEANS ON THIS SIDE. Every route a `go_only` row addresses is one THIS server must -// dispatch, so a Go-only route needs a row like any other; what this side cannot know -// is whether the ORACLE serves it, and that edge is the Python validator's (it refuses -// the mark for a route `server.py` declares). Together: Go's routes minus the oracle's -// equals the routes `go_only` rows address — and `tests/test_go_client_ledgers.py` -// checks that equation directly, out of the running binary. func checkRouteLedger(declared []string, rows []corpusRow) error { if len(declared) == 0 { return fmt.Errorf("this server declares no route at all") } addressed := map[string]bool{} - goOnly := map[string]bool{} for _, c := range rows { // A `negative_route` row exists to pin what a NON-route answers, so it // contributes no coverage — the same exclusion the Python side makes, and for @@ -144,17 +129,14 @@ func checkRouteLedger(declared []string, rows []corpusRow) error { continue } addressed[name] = true - if c.GoOnly { - goOnly[name] = true - } } for _, name := range declared { if !addressed[name] { return fmt.Errorf("this server declares %q and the conformance request list "+ "never addresses it. A suite that replays a recorded list is STRUCTURALLY "+ "BLIND to a route added after the list was written — add a row per "+ - "principal shape (marked `go_only` if the oracle does not serve it), then "+ - "regenerate", name) + "principal shape, then record its golden from this server "+ + "(`tests/conformance/run_go.sh record`)", name) } } names := make([]string, 0, len(addressed)) @@ -166,14 +148,6 @@ func checkRouteLedger(declared []string, rows []corpusRow) error { if slices.Contains(declared, name) { continue } - // The specific diagnosis FIRST: a stale Go-only declaration is a different - // mistake from a stale shared row, and the fix differs (drop the mark and the - // rows, or wire the route), so it gets its own sentence. - if goOnly[name] { - return fmt.Errorf("the conformance request list marks %q `go_only` and this "+ - "server does not dispatch it. A Go-only declaration for a route Go does "+ - "not serve is STALE — it would record a 404 as the Go-only contract", name) - } return fmt.Errorf("the conformance request list addresses %q and this server does "+ "not dispatch it. The ledger fails when the set SHRINKS as well as when it "+ "grows", name) @@ -187,21 +161,19 @@ func TestTheRouteLedgerMatchesTheConformanceCorpus(t *testing.T) { } } -func TestTheRouteLedgerHonoursADeclaredGoOnlyRouteAndOnlyThat(t *testing.T) { - // 🔴 NO GO-ONLY ROUTE EXISTS YET, so the machinery is proved on a SYNTHETIC one - // rather than by adding a public endpoint. The real corpus and the real ledger are - // the base; `synthetic-go-only` is a head nothing serves. +func TestTheRouteLedgerRefusesAGrownOrAShrunkRouteSet(t *testing.T) { + // The machinery is proved on a SYNTHETIC route rather than by adding a public + // endpoint. The real corpus and the real ledger are the base; `synthetic-route` is + // a head nothing serves. rows := corpusRows(t) declared := DeclaredRoutes() - const head = "synthetic-go-only" + const head = "synthetic-route" withRoute := append(slices.Clone(declared), "GET "+head) row := corpusRow{ID: "synthetic", Method: "GET", Target: APIPrefix + head + "/alpha-notes"} - // GREEN: a declared Go route with a `go_only` row addressing it. - marked := row - marked.GoOnly = true - if err := checkRouteLedger(withRoute, append(slices.Clone(rows), marked)); err != nil { - t.Fatalf("a Go-only route WITH its go_only row must pass: %v", err) + // GREEN: a declared route with a row addressing it. + if err := checkRouteLedger(withRoute, append(slices.Clone(rows), row)); err != nil { + t.Fatalf("a declared route WITH its row must pass: %v", err) } // RED: the same route with NO row — the grow direction, with its own sentence. err := checkRouteLedger(withRoute, rows) @@ -209,20 +181,11 @@ func TestTheRouteLedgerHonoursADeclaredGoOnlyRouteAndOnlyThat(t *testing.T) { !strings.Contains(err.Error(), head) { t.Fatalf("a Go route with no corpus row must be refused by the GROW check, got %v", err) } - // RED: a `go_only` row for a route this server does NOT dispatch — the stale - // declaration, refused with the go-only sentence rather than the generic one. - err = checkRouteLedger(declared, append(slices.Clone(rows), marked)) - if err == nil || !strings.Contains(err.Error(), "is STALE") || - !strings.Contains(err.Error(), head) { - t.Fatalf("a go_only row for an undispatched route must be refused as STALE, got %v", err) - } - // …and the CONTROL on that branch: the same row UNmarked gets the generic - // shrink sentence, so the STALE text above is chosen by the mark and not by - // accident. + // RED: a row for a route this server does NOT dispatch — the shrink direction. err = checkRouteLedger(declared, append(slices.Clone(rows), row)) - if err == nil || strings.Contains(err.Error(), "is STALE") || - !strings.Contains(err.Error(), "SHRINKS") { - t.Fatalf("an unmarked row for an undispatched route must get the SHRINK sentence, got %v", err) + if err == nil || !strings.Contains(err.Error(), "SHRINKS") || + !strings.Contains(err.Error(), head) { + t.Fatalf("a row for an undispatched route must get the SHRINK sentence, got %v", err) } // The positive control on the base: the unmodified pair passes, so every red above // is the synthetic change and not the harness. diff --git a/internal/api/authority_test.go b/internal/api/authority_test.go index 61a76927..e6f49f99 100644 --- a/internal/api/authority_test.go +++ b/internal/api/authority_test.go @@ -32,8 +32,9 @@ import ( // // It fails when the set GROWS as well as when it shrinks, and it carries a positive // control on the ALLOW COUNT, because a matrix in which every cell refuses is perfectly -// self-consistent and measures nothing — the shape `tests/parity/README.md` records the -// P2 harness shipping with (72 PASS / 0 FAIL while the pod refused every request). +// self-consistent and measures nothing — the shape `tests/parity/README.md` recorded the +// P2 harness shipping with (72 PASS / 0 FAIL while the pod refused every request; deleted +// with the Python oracle — read it at `ec1b756`). // --------------------------------------------------------------------------- // The fixture's principals. Each reaches a different set, and no two rows of the matrix diff --git a/internal/api/federation_audit_test.go b/internal/api/federation_audit_test.go index d2bb1e46..0bdd4050 100644 --- a/internal/api/federation_audit_test.go +++ b/internal/api/federation_audit_test.go @@ -242,7 +242,7 @@ func TestAGroupNameCannotForgeAnAuditField(t *testing.T) { // TestAMachineTokenLineCarriesNoTokenOrGroupFields is an INVARIANT guard (the bug it // would catch never existed at 1db64d9): every non-JWT line keeps its old shape, which is -// what `tests/dualrun/` compares against the oracle. +// what the retired `tests/dualrun/` gate compared against the oracle. func TestAMachineTokenLineCarriesNoTokenOrGroupFields(t *testing.T) { h := newMatrixHarness(t) var lines []string diff --git a/internal/api/lockout_claims_test.go b/internal/api/lockout_claims_test.go index f93661ca..78bdfc9b 100644 --- a/internal/api/lockout_claims_test.go +++ b/internal/api/lockout_claims_test.go @@ -293,8 +293,8 @@ func TestClaimsRefusalsNeitherAddToNorForgiveTheFailureCount(t *testing.T) { // TestASignedTokenIsAuditedWithItsSubAndJti pins the two new audit fields: present // on a verified token's line (authenticated or claims-refused), ABSENT from every other -// line (which keeps a machine-token line byte-identical to the oracle's for -// `tests/dualrun/`), and unable to forge a field or a line. +// line (which kept a machine-token line byte-identical to the oracle's for the retired +// `tests/dualrun/` gate), and unable to forge a field or a line. func TestASignedTokenIsAuditedWithItsSubAndJti(t *testing.T) { h := newLockHarness(t) diff --git a/internal/api/routes.go b/internal/api/routes.go index 323d7b37..c96f704f 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -16,13 +16,12 @@ import ( // `head = parts[0]` — so the guard moved from "what does the source look like" to // "what does the code dispatch from". // -// 🔴 AND FOR A NON-PYTHON IMPLEMENTATION THAT GUARD HAD TO BE REBUILT. The -// conformance suite reads the ORACLE's two dict literals by AST to prove the corpus -// addresses every declared route; there is no source for that reader to read here, -// and `tests/conformance/README.md` says so under "what this suite cannot see". What -// closes it on this side is `DeclaredRoutes` below, plus the Go test that compares its -// output against `tests/conformance/requests.json` — the same ledger claim, made from -// the same data file, failing when the set GROWS or SHRINKS. +// 🔴 `DeclaredRoutes` BELOW IS THE ONE DECLARATION OF THE ROUTE SET. The Go test that +// compares it against `tests/conformance/requests.json`, and the conformance suite (which +// reads it out of the built binary through `cairn-server -routes`), make the same ledger +// claim from the same data file, failing when the set GROWS or SHRINKS. (The suite once +// read the retired Python oracle's two dict literals by AST instead; that reader could +// not see a compiled program, which is why this side has its own.) // readArity counts the path components a read route takes INCLUDING the route name // itself, so `recall/` is 2 and `snapshot` is 1. @@ -64,21 +63,12 @@ type writeKey struct { // method on the server. The KEYS are declared here as the ledger, so the set is // readable without reading the wiring. // -// ⚠ `sessions`, `arcs`, `arc` AND `PUT arc` ARE GO-ONLY BY DECISION (decision 3 of the -// arcs/sessions plan): `server/server.py` does not serve them, and every row addressing them in -// `tests/conformance/requests.json` is marked `go_only`. The four places a head moves together are -// this table, those rows, the `go_only` rows of `tests/testlib/capability_ledger.LEDGER`, and -// `flake.nix`'s `want-go-only.txt`. -// -// ⚠ `sources` IS GO-ONLY ON THE SAME PRECEDENT (decision 10 of the scope-refs plan): the read of a -// scope's declared code sources, from a journal the browser surface writes and this pod only READS. -// Its derived `HEAD` is the ledger's one rule, kept (the plan's Q16). The dual-run gate discovers -// routes from the oracle, so it is BLIND to this head — a named gap, not a fifth ledger. -// -// ⚠ `whoami` IS GO-ONLY ON THE SAME PRECEDENT: the caller's own authority as JSON, built from -// the federation report and the read set (`whoami.go`). The oracle has no control plane and no -// group federation to report, so extending it would serve a view of nothing. Same four places, -// and the dual-run gate is blind to it for the same reason as `sources`. +// ⚠ A HEAD MOVES TOGETHER IN THREE PLACES: this table, the rows addressing it in +// `tests/conformance/requests.json` (each with a golden recorded from this server, see that +// directory's README), and `flake.nix`'s `want.txt` for `checks.go-server-declares-its-routes`. +// `sessions`, `arcs`, `arc`, `PUT arc`, `sources` and `whoami` were added after the Python oracle +// stopped being extended and were declared "Go-only" until it was retired; the decisions behind +// them are in the arcs/sessions and scope-refs plans. var readHeads = []string{"recall", "search", "snapshot", "sessions", "arcs", "arc", "sources", "whoami"} var writeKeys = []writeKey{ diff --git a/internal/api/server.go b/internal/api/server.go index 376a8619..b0148872 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -1222,8 +1222,8 @@ func (rq *request) audit(result int, status string) { "result=" + strconv.Itoa(result) + " status=" + auditField(status, 32) // 🔴 APPENDED, AND ONLY FOR A VERIFIED SIGNED TOKEN. A line for a machine token, an // unauthenticated request or any refusal that never verified a signature is - // BYTE-IDENTICAL to what it was, which is what keeps `tests/dualrun/`'s line-for-line - // comparison with the oracle (which verifies no signed token) unmoved. The values are + // BYTE-IDENTICAL to what it was, which is what kept the retired `tests/dualrun/`'s + // line-for-line comparison with the oracle (which verified no signed token) unmoved. The values are // signed by the issuer, not chosen by an anonymous caller, but they pass through // `auditField` all the same — a `sub` carrying a space or a newline must not become a // second field or a second line. One statement per field, so a later field is an diff --git a/lib/README.md b/internal/client/ROUTING.md similarity index 90% rename from lib/README.md rename to internal/client/ROUTING.md index 40842e08..968be875 100644 --- a/lib/README.md +++ b/internal/client/ROUTING.md @@ -1,19 +1,18 @@ -# `lib/` — the reader, and where a scope LIVES +# Routing — where a scope LIVES, and the rules that bind an edit to it -The Python client's library half: cache resolution, recall and search rendering, scope and ref -resolution, `doctor`, and the multi-instance routing this file exists for. - -🔴 **THIS FILE IS THE EVICTION TARGET FOR ROUTING, AND THAT IS WHY IT EXISTS.** `AGENTS.md` is -loaded by every session in this repository before any work starts — it is measured and ceilinged -by `tests/test_agent_instructions_weight.py` — so a rule that binds only the people editing -`lib/cairn_instances.py`, `cairn`'s routing helpers and `internal/client/instances.go` is paid by -everyone and read by almost nobody. It lives here, where it costs nothing until somebody opens it, -and `AGENTS.md` carries one line pointing at it. **Moved, not deleted: every claim below was in -`AGENTS.md` and is reproduced verbatim.** +🔴 **RE-HOMED FROM `lib/README.md`, WHICH WAS DELETED WITH THE PYTHON CLIENT.** `AGENTS.md` points +here for the multi-instance routing rules: they bind anyone editing `internal/client/instances.go`, +`routes.go`, `state.go` or the verbs that consult them, and they cost nothing until somebody opens +this file. The text below is the old file's routing section with the Python identifiers mapped to +their Go equivalents (`Routing.MultiInstance`, `Routing.AliasFor`, `Routing.Check`, +`CacheRootFor`, `DefaultCacheRoot()`, `ResolveState`). ⚠ Where it still names a Python file, a +Python test or the parity harness, that is the HISTORY of how a rule was measured — those files are +deleted; the Go twin of each guard lives in `internal/client`'s tests, and `tests/routing_mutants.py` +is the mutation battery over them. ## 🔴 THE CLIENT CAN BE POINTED AT SEVERAL INSTANCES, AND AN UNROUTED SCOPE REFUSES -`lib/cairn_instances.py` owns three questions: what is configured, which +`internal/client/instances.go` owns three questions: what is configured, which instance a scope belongs to, and whether the two agree. The rules that bind anyone editing that path: @@ -28,10 +27,10 @@ anyone editing that path: recreates is a write landing in a store nobody reads, which is found days later by accident if at all. - 🔴 **"IS THIS HOST ROUTING?" IS TWO QUESTIONS, AND COLLAPSING THEM INTO ONE - BOOLEAN IS A MEASURED DEFECT.** `Routing.multi_instance` (`len(instances) > 1`) + BOOLEAN IS A MEASURED DEFECT.** `Routing.MultiInstance` (`len(instances) > 1`) decides what is LABELLED — the banner label, the write label, `doctor`'s per-instance rows, `ls-entries`' prefix, the `--all-scopes` fan-out and the - caveat's extra clause all ask it, so they cannot disagree. `Routing.alias_for` + caveat's extra clause all ask it, so they cannot disagree. `Routing.AliasFor` decides WHERE a scope lives, and it consults the TABLE first, whatever the instance count is. Three rows share one configuration — **one instance with a table present**, which is what an operator has the moment they write their @@ -48,16 +47,16 @@ anyone editing that path: configured…"* — false on that host, on every call — and every scope not yet in the table refused at exit 11. Column 3 is the obvious fix and it opens a **silent misroute**: a write landing in a store nobody decided on. Do not - re-collapse these; the table above is reproduced at `Routing.alias_for` and + re-collapse these; the table above is reproduced at `Routing.AliasFor` and guarded by `TestOneInstanceWithATablePresent`. -- **One rule, one place: `Routing.check` asks `Routing.alias_for`.** The grader's +- **One rule, one place: `Routing.Check` asks `Routing.AliasFor`.** The grader's "the table names an alias no instance provides" finding, and its "a write to it will REFUSE" finding, are both predictions about what the resolver does — so they ask it rather than re-deriving from the same two inputs. That is also what keeps the grader honest on a one-instance host, where an unnamed scope does *not* refuse. -- **The default instance's cache root does not move.** `cache_root_for` returns - `DEFAULT_CACHE_ROOT` unchanged for `personal` and a SIBLING directory for every +- **The default instance's cache root does not move.** `CacheRootFor` returns + `DefaultCacheRoot()` unchanged for `personal` and a SIBLING directory for every other alias. A child directory would look exactly like a SCOPE to every reader that enumerates `/`. - 🔴 **`STORE_IS_PER_HOST` IS BYTE-MIRRORED INTO TENS OF TRACKED FILES, NOT FOUR @@ -188,10 +187,10 @@ anyone editing that path: - 🔴 **AND THAT GUARANTEE IS ABOUT *LABELLING*, NOT ABOUT *ROUTING* — the sentence above is echoed at SEVERAL sites, and the number is deliberately not written here — `tests/test_narrowing_echo_sites.py` holds the set.** They - are: here, `internal/client/instances.go`, `tests/parity/README.md`, `cairn`'s - `_instance_for` docstring, `internal/client/routes.go`'s `readInstance`, - `internal/client/state.go`'s `BannerNamed`, `tests/test_cairn_instances.py`, - and `tests/unchanged_output_capture.py`, the harness that measures the claim. + are: here, `internal/client/instances.go`, `internal/client/routes.go`'s + `readInstance`, and `internal/client/state.go`'s `BannerNamed`. (Five more were + deleted with the Python client: its script, the parity record, its instances + test, and the byte-identity capture harness that measured the claim.) Every one of them reads wider than it is, and every one carries this narrowing. ✅ **THE SET IS NOW ASSERTED, AND THE RE-COUNT RECIPE THAT STOOD HERE IS DELETED RATHER THAN CORRECTED** — it matched two literal phrases, so @@ -209,7 +208,7 @@ anyone editing that path: prose always has. The scope-taking reads did not consult the table at all before; - they do now, and `alias_for` row 3 REFUSES at ONE instance as well as at + they do now, and `AliasFor` row 3 REFUSES at ONE instance as well as at many. So exactly one single-instance case moved: a host whose table routes the scope to an alias it has no config for — a stale or typo'd entry, the case `routes --check` exists to find. Measured over one world with the @@ -238,13 +237,13 @@ anyone editing that path: exits 4 and `ls-entries --scope alpha-notes` exits 0 on BOTH clients, byte-identical to the unscoped runs — the CONCLUSION stands and only the reason moved. The reason is load-bearing: a later change that routed - `ls-entries --scope` through `alias_for` would falsify the conclusion while + `ls-entries --scope` through `AliasFor` would falsify the conclusion while the old reason still read as covering it. - 🔴 `routes` reports rather than routes, and it must keep working before any table is right: it is the verb an operator runs *while standing up* a second instance. - 🔴 **`routes --check` MUST THREAD THE ALIAS INTO THE STATE RESOLVER, NOT JUST THE - CACHE PATH.** `resolve_state`/`ResolveState` FETCHES as well as unpacks, so a + CACHE PATH.** `ResolveState`/`ResolveState` FETCHES as well as unpacks, so a caller that hands it instance `N`'s cache root while it loads the DEFAULT instance's credentials fetches `personal` N times and unpacks it over every other instance's cache — the exact damage the sibling-directory layout exists to @@ -253,7 +252,7 @@ anyone editing that path: missing. Measured on a two-instance host before the fix: `cairn[secondary]` banner naming `personal`'s URL, `secondary`'s cache holding `personal`'s scopes, and a false "exists on no configured instance" at exit 11. -- 🔴 **DIRECTION TWO OF `Routing.check` IS A NOTE, NOT A VERDICT.** It subtracts the +- 🔴 **DIRECTION TWO OF `Routing.Check` IS A NOTE, NOT A VERDICT.** It subtracts the cache's DIRECTORY LISTING from the table's keys, and a snapshot ships entry FILES — so a scope holding no entries is missing from that set whether it is stale, pre-registered before its first write, or pruned back to empty. Grading diff --git a/internal/client/anchor.go b/internal/client/anchor.go index 1df9451b..5922ce3c 100644 --- a/internal/client/anchor.go +++ b/internal/client/anchor.go @@ -18,7 +18,8 @@ import ( // The Python oracle never had any of it. `Path(anchor).glob(pattern)` treats the anchor // literally by construction, so each of these was also a silent cross-client divergence that // the parity gate could not see, because no world it built named a directory with a -// metacharacter in it. (`tests/parity/harness.py` now builds one — see its world root.) +// metacharacter in it. (`tests/parity/harness.py` came to build one in its world root before it +// was deleted with the oracle; read it at `ec1b756`.) // // 🔴 THE THREE REMAINING SITES DO **NOT** SHARE A PREDICATE, AND FORCING ONE WOULD HAVE BEEN // THE ORIGINAL MISTAKE AGAIN. `Focus` matches a fixed GLOB pattern against names, `ReapOrphans` diff --git a/internal/client/anchor_test.go b/internal/client/anchor_test.go index 53deeda2..e10e4f98 100644 --- a/internal/client/anchor_test.go +++ b/internal/client/anchor_test.go @@ -23,8 +23,8 @@ import ( // unterminated `[` in a directory name took `filepath.Match` to `ErrBadPattern`, the error was // discarded at the call site, and the empty match set was reported as an ordinary answer. The // oracle has never had any of them, so each was also a silent cross-client divergence — which -// is why `tests/parity/harness.py` now names its world root with a `[` in it, and why three of -// its rows go red at that commit. +// is why `tests/parity/harness.py` came to name its world root with a `[` in it, and why three of +// its rows went red at that commit (that harness is deleted with the oracle; read it at `ec1b756`). // // ⚠ THE INVARIANT ROWS BESIDE THEM ARE LABELLED AS SUCH AND ARE NOT REGRESSION COVERAGE. They // pass at `e293c6e` too. They exist because each fix replaced a pattern match with an @@ -263,8 +263,8 @@ func TestReapOrphansStillDiscriminatesByPrefixAgeAndKind(t *testing.T) { // TestPutDerivesARevisionUnderAMetacharacterCacheRoot is the third site. // -// 🔴 THE NAME IS PINNED BY `tests/parity/README.md`'s RETIRED RESIDUAL 9, WHICH IS WHY IT IS -// NOT SPELLED LIKE ITS TWO SIBLINGS. That row's closing condition is a command — +// 🔴 THE NAME WAS PINNED BY `tests/parity/README.md`'s RETIRED RESIDUAL 9 (that README is deleted +// with the oracle; read it at `ec1b756`), WHICH IS WHY IT IS NOT SPELLED LIKE ITS TWO SIBLINGS. That row's closing condition is a command — // `go test ./internal/client/ -run PutDerivesARevisionUnderAMetacharacterCacheRoot -count=1 -v` // must print a `--- PASS:` line — and the row spends a paragraph warning that a zero-selection // `-run` exits 0, so the exit code cannot tell an unwritten test from a met condition. Measured @@ -554,7 +554,8 @@ func TestHandoffGlobsKeepTheLiteralDIRECTORYPrefixThatFocusJOINS(t *testing.T) { // 🔴 THE CLAIM THIS ROW ACTUALLY RESTS ON IS THE BEHAVIOUR, NOT THAT MECHANISM. End to end on // one fixture, repo at mode `0111`: `Focus` → `Source="claudedocs/handoff-demo.md"`, // `focus_window` → `FocusWindow(paths=(), source=None)`. So this row pins a GO property and a -// DECLARED divergence (`tests/parity/README.md` residual 10), not a parity property. The +// DECLARED divergence (`tests/parity/README.md` residual 10, deleted with the oracle; read it at `ec1b756`), +// not a parity property. The // direction is still the right one — the Go side answers the doc where the oracle claims // absence — but that is a choice, not agreement. // diff --git a/internal/client/arcs.go b/internal/client/arcs.go index 0bd67804..44b8e807 100644 --- a/internal/client/arcs.go +++ b/internal/client/arcs.go @@ -15,12 +15,13 @@ import ( ) // THE ARC-REGISTRY VERBS — `arcs`, `arc-show`, `arc-register` — the Go-only surface of the -// arcs/sessions S3 slice (decision 3 of `claudedocs/plan-cairn-arcs-sessions.md`; declared by the -// `go_only` rows of `tests/testlib/capability_ledger.LEDGER`). +// arcs/sessions S3 slice (decision 3 of `claudedocs/plan-cairn-arcs-sessions.md`; declared by +// rows of `tests/testlib/capability_ledger.LEDGER`, which carried a Go-only mark until the Python +// oracle was retired). // // 🔴 ALL THREE ASK THE POD, NONE READS THE CACHE. Registrations live in the pod's journal and are -// deliberately NOT in the snapshot (which `tests/dualrun/` byte-compares against the oracle, so a -// Go-only member there would be a divergence by construction). So the two read verbs print the +// deliberately NOT in the snapshot (which the retired `tests/dualrun/` byte-compared against the +// oracle, so a Go-only member there would have been a divergence by construction). So the two read verbs print the // pod's body VERBATIM — `internal/report`'s arc renderer is the only rendering of these answers — // and a pod that cannot be reached is exit 3 ("nothing was read at all"), not a stale answer. // diff --git a/internal/client/arcscheck_test.go b/internal/client/arcscheck_test.go index 5fe8ee3c..6f79096d 100644 --- a/internal/client/arcscheck_test.go +++ b/internal/client/arcscheck_test.go @@ -129,8 +129,8 @@ func TestArcsCheckFlags(t *testing.T) { // TestTheArcsCheckAddedNoExitCode is Q5's constraint ASSERTED, not a ledger moved: both code tables // `cairn -exit-codes` prints, spelled LITERALLY. A constant added for the check — or anywhere — turns -// this red, beside the two cross-client ledgers in `tests/test_go_client_ledgers.py` and -// `tests/test_cairn_doctor.py` that it must also keep green. +// this red, beside the ledger in `tests/test_go_client_ledgers.py` that it must also keep green +// (the second, `tests/test_cairn_doctor.py`, was retired with the Python client). func TestTheArcsCheckAddedNoExitCode(t *testing.T) { wantClient := map[string]int{ "EXIT_OK": 0, "EXIT_USAGE": 2, "EXIT_UNREACHABLE_NO_CACHE": 3, "EXIT_REFRESH_FAILED": 4, diff --git a/internal/client/cli.go b/internal/client/cli.go index b73c2451..9e130c38 100644 --- a/internal/client/cli.go +++ b/internal/client/cli.go @@ -49,9 +49,10 @@ var commonReadFlags = []string{"--scope", "--repo", "--no-sync"} // has; there is no equivalent for a compiled binary, so an undeclared Go-only verb (or a Go // client that silently LOST one) would leave that gate green. `cairn -verbs` prints this table // and `tests/test_go_client_ledgers.py` reads it out of the RUNNING binary — the same shape, and -// for the same reason, as `cairn-server -routes`. A verb here that the Python client lacks is -// legal IFF a `go_only` row of `tests/testlib/capability_ledger.LEDGER` declares it (decision 3 -// of the arcs/sessions plan), and must also appear in `flake.nix`'s `want-go-only-verbs.txt`. +// for the same reason, as `cairn-server -routes`. A verb added here needs a row in +// `tests/testlib/capability_ledger.LEDGER` and a line in `flake.nix`'s `want-all-verbs.txt`, or +// both gates go red. (Until the Python client was retired, a verb it lacked was legal only behind +// a Go-only mark on that row; the mark was folded away with the oracle.) func Verbs() []Verb { return []Verb{ {Name: "sync", Ledger: LedgerNone, Help: "refresh the local cache from the pod", @@ -68,8 +69,8 @@ func Verbs() []Verb { // this names something an entry POINTS AT, and the two compose. The pod's // parameter is `?ref-to=` — the same spelling — because `?ref=` already // means `--ref` there and redefining it would break a pinned contract. - // BOTH clients declare it or `tests/parity/` reds on an unrecognised - // argument. + // While the Python client lived, BOTH clients had to declare it or + // `tests/parity/` went red on an unrecognised argument. // `--tag` is the scalar CATEGORY narrowing, and it composes with everything // here — it is a filter over the entry set, not a selector of one entry, so // `RejectRecallFlags` deliberately does not name it. @@ -85,7 +86,7 @@ func Verbs() []Verb { Run: func(e Env, o Options) (int, error) { return Report(e, o, true) }}, // 🔴 GO-ONLY, DECLARED: the Python client has no `sessions` (decision 3 of the // arcs/sessions plan), and the `scope-sessions` row of `capability_ledger.LEDGER` plus - // `flake.nix`'s `want-go-only-verbs.txt` are what make that legal. It renders through the + // `flake.nix`'s `want-all-verbs.txt` are what make that legal. It renders through the // SAME `report.Sessions` the pod's `sessions/` route does. {Name: "sessions", Ledger: LedgerResolved, Help: "which sessions wrote attributed bullets in the scope, with coverage", Flags: commonReadFlags, Run: Sessions}, @@ -113,13 +114,13 @@ func Verbs() []Verb { Flags: []string{"--scope", "--repo", "--slug", "--from"}, Run: ArcRegister}, // 🔴 GO-ONLY, DECLARED: the scope's declared code sources (S3 of the scope-refs plan) — the // `scope-sources` row of `capability_ledger.LEDGER` and `flake.nix`'s - // `want-go-only-verbs.txt` make that legal. Read-only: the browser surface is the ONLY + // `want-all-verbs.txt` make that legal. Read-only: the browser surface is the ONLY // writer (decision 5), so there is no `sources-set` verb and there must not be one. Asks the // pod and prints its body verbatim, the arc verbs' shape — see `SourcesShow`. {Name: "sources", Ledger: LedgerResolved, Help: "which code (repositories and branch) the scope declares it describes (asks the pod)", Flags: []string{"--scope", "--repo"}, Run: SourcesShow}, // 🔴 GO-ONLY, DECLARED: the reference auditor (S5 of the scope-refs plan) — the `audit-refs` - // row of `capability_ledger.LEDGER` and `flake.nix`'s `want-go-only-verbs.txt`. It exits on + // row of `capability_ledger.LEDGER` and `flake.nix`'s `want-all-verbs.txt`. It exits on // DOCTOR'S 0/9/10 at its own call site (decision 8), like `arcs --check`. Read-only: it writes // only its own mirror cache, never the store and never the pod. {Name: "audit-refs", Ledger: LedgerResolved, Help: "check the scope's entries' paths, symbols, commits and PRs against its declared code sources (fetches them)", @@ -169,7 +170,7 @@ func Verbs() []Verb { {Name: "associate", Ledger: LedgerResolved, Help: "which entries of the scope a list of repo-relative paths names (--paths-from FILE, or - for stdin)", Flags: []string{"--scope", "--repo", "--no-sync", "--paths-from", "--min-paths", "--json"}, Run: Associate}, // 🔴 GO-ONLY, DECLARED: scope mail's four verbs (S3 of the scope-mail plan, decision 8) — - // the `memo-*` rows of `capability_ledger.LEDGER` and `flake.nix`'s `want-go-only-verbs.txt` + // the `memo-*` rows of `capability_ledger.LEDGER` and `flake.nix`'s `want-all-verbs.txt` // make that legal. FLAT and hyphenated for the arc verbs' reason: ONE `Writes` bit each. They // talk to `cairn-ui`'s client listener (`CAIRN_UI_URL`), never the pod — see `memo.go`. {Name: "memo-check", Ledger: LedgerResolved, Help: "print memos this session has not seen, as one fenced UNTRUSTED block (asks the memo listener)", @@ -183,14 +184,14 @@ func Verbs() []Verb { Flags: []string{"--scope", "--repo", "--id"}, Run: MemoRetract}, // 🔴 GO-ONLY, DECLARED: the agent read API's client (S8 of the transcripts plan, decision 17; Q15 // adopted under O13) — the `transcript` row of `capability_ledger.LEDGER` and `flake.nix`'s - // `want-go-only-verbs.txt`. ONE verb whose positional is the action (`skeleton`, `records`, + // `want-all-verbs.txt`. ONE verb whose positional is the action (`skeleton`, `records`, // `tool`): all three read, so the one `Writes` bit the flat-verb ruling protects is the same for // each. It asks `cairn-ui`'s client listener (`CAIRN_UI_URL`) — see `transcript.go`. Class `*`: // it prints ANOTHER session's transcript, whose visibility set may hold any scope (decision 3a). {Name: "transcript", Ledger: LedgerAll, Help: "read a stored session transcript: skeleton | records | tool (asks cairn-ui's client listener)", Notes: transcriptNotes, Flags: transcriptVerbFlags(), Run: Transcript}, // 🔴 GO-ONLY, DECLARED: L2 search over the stored transcripts (Phase 1 of the v1 event-log - // plan) — the `log` row of `capability_ledger.LEDGER` and `flake.nix`'s `want-go-only-verbs.txt`. + // plan) — the `log` row of `capability_ledger.LEDGER` and `flake.nix`'s `want-all-verbs.txt`. // ONE verb with the action as its positional, `transcript`'s shape and for its reason: all three // actions READ. Class `*`, `transcript`'s: it prints other sessions' content. See `log.go`. {Name: "log", Ledger: LedgerAll, Help: "search the stored session transcripts: list | search QUERY | read SESSION | query SQL — QUERY is full-text (words, \"phrases\", OR, -exclude), not regex", @@ -258,10 +259,10 @@ var ErrHelpRequested = errors.New("help requested") // Usage is this client's own help text. // -// ⚠ IT IS NOT ARGPARSE'S, AND THAT IS DECLARED DIFFERENCE 1 IN `tests/parity/README.md`. -// Reproducing argparse's `usage:` block, its column layout and its wording in Go would be a second -// implementation of a library nobody reads twice. What the parity gate compares on these rows is -// the EXIT CODE and that stdout is NON-EMPTY — the second half matters, because a client that +// ⚠ IT IS NOT ARGPARSE'S, AND THAT WAS DECLARED DIFFERENCE 1 IN `tests/parity/README.md` (deleted +// with the oracle; read it at `ec1b756`). Reproducing argparse's `usage:` block, its column layout and its +// wording in Go would have been a second implementation of a library nobody reads twice. What the +// retired parity gate compared on these rows was the EXIT CODE and that stdout is NON-EMPTY — the second half matters, because a client that // printed nothing and exited 0 would pass an exit-only comparison while telling the reader nothing. func Usage(verb string) string { var b strings.Builder @@ -367,10 +368,11 @@ func looksLikeOption(token string) bool { func isHelpFlag(token string) bool { return token == "--help" || token == "-h" } // usageError is a command line this client refuses. 🔴 IT IS EXIT 2, WHICH IS THE ONE PART OF THE -// USAGE CONTRACT BOTH CLIENTS SHARE. The MESSAGE is not: the Python client's usage text is +// USAGE CONTRACT BOTH CLIENTS SHARED. The MESSAGE was not: the Python client's usage text was // argparse's, and reproducing argparse's wording, its `usage:` line and its `--help` layout in Go -// would be a large second implementation of a library nobody reads twice. That difference is -// declared in `tests/parity/README.md` and the parity harness compares the CODE on these rows. +// would have been a large second implementation of a library nobody reads twice. That difference +// was declared in `tests/parity/README.md` (deleted with the oracle; read it at `ec1b756`) and the parity +// harness compared the CODE on these rows. type usageError struct{ message string } func (e *usageError) Error() string { return e.message } @@ -773,11 +775,11 @@ func verbNames() []string { // Run is the whole client: parse, dispatch, and map every escaping error to its own exit code. func Run(env Env, argv []string) int { - // 🔴 BEFORE `Parse`, SO `--help` WARNS TOO, AND BECAUSE THE POSITION IS COMPARED. - // `tests/parity/harness.py` diffs the two clients' stderr byte-for-byte, so WHERE in the - // program the deprecation sweep runs is part of the contract rather than a detail: the - // Python client emits the same sweep at the top of its `main()`. Emitting it after - // `Parse` would order it differently against a usage error on the two sides. + // 🔴 BEFORE `Parse`, SO `--help` WARNS TOO, AND BECAUSE THE POSITION WAS COMPARED. + // The retired `tests/parity/harness.py` diffed the two clients' stderr byte-for-byte, so + // WHERE in the program the deprecation sweep runs was part of the contract rather than a + // detail: the Python client emitted the same sweep at the top of its `main()`. Emitting it + // after `Parse` would have ordered it differently against a usage error on the two sides. // // The FILE-key half of the sweep cannot happen here — the config path is not known until // an alias has been resolved — so `LoadConfigFor` emits that half through the same sink. @@ -890,16 +892,18 @@ func Run(env Env, argv []string) int { // reproduced". #111 grew the oracle's `main()` the reader-error rung this function always // had, and `entry_files_in` stopped swallowing `EACCES` on the scope directory. MEASURED on // both clients at both depths: byte-identical stderr and exit 3 on all four (verb × depth), - // gated by four rows in `tests/parity/harness.py`. + // gated by four rows in `tests/parity/harness.py` until it was deleted with the oracle. // // ⚠ WHAT REMAINS IS ONE DEPTH UP — THE CACHE ROOT — AND IT IS STILL OPEN IN BOTH ITS MODES, - // declared in `tests/parity/README.md` residual 4 rather than closed. Without `x` the root + // declared in `tests/parity/README.md` residual 4 rather than closed (that table is deleted + // with the oracle — read it at `ec1b756`; `claudedocs/plan-cairn-v1-event-log.md` §6.3 records the + // disposition and the coverage gap it left). Without `x` the root // never reaches a verb at all: the oracle's `resolve_state` raises at exit 1 while // `ResolveState` here answers `store-unreachable, no cache` at 3, which is the branch above // and not this one. WITH `x` and without `r` (mode 0111) the stamp read succeeds and // `Validate`'s and `Routes`' own root listings are reached — those hand this arm a raw // `*os.PathError`, so the number is 3 but the TEXT is not the reader's sentence, and the - // oracle tracebacks at 1. Read that row, not this paragraph, for the closing condition. + // oracle died with a traceback at 1. That row, not this paragraph, held the closing condition. fmt.Fprintf(env.Stderr, "🔴 cairn: %s\n", runErr) return ExitUnreachableNoCache } diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 34bad267..ebc0c407 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -20,12 +20,14 @@ import ( "github.com/ZacxDev/cairn/internal/report" ) -// 🔴 WHAT THIS FILE OWNS, AND WHAT THE PARITY GATE OWNS. `tests/parity/harness.py` runs both -// clients over one cache root and diffs the bytes — that is the deliverable's evidence and it -// covers every verb. It cannot reach an archive a real pod will not send, a table's own shape, or a -// message whose input the harness has no way to construct. Those are here. Where a case IS -// reachable from the harness, it is NOT duplicated here: a second assertion over one behaviour -// means neither can be observed to be wrong. +// 🔴 WHAT THIS FILE OWNS, AND WHAT THE PARITY GATE OWNED. `tests/parity/harness.py` ran both +// clients over one cache root and diffed the bytes — that was the deliverable's evidence and it +// covered every verb. It could not reach an archive a real pod will not send, a table's own shape, +// or a message whose input the harness had no way to construct. Those are here. Where a case WAS +// reachable from the harness, it was NOT duplicated here: a second assertion over one behaviour +// means neither can be observed to be wrong. ⚠ That harness is deleted with the Python oracle, +// and nothing was added here in its place — the cases this file left to it are no longer +// compared against a second implementation. func gzTar(t *testing.T, build func(*tar.Writer)) []byte { t.Helper() diff --git a/internal/client/envalias_test.go b/internal/client/envalias_test.go index 26531d8e..9df6282e 100644 --- a/internal/client/envalias_test.go +++ b/internal/client/envalias_test.go @@ -14,8 +14,8 @@ import ( // // 🔴 SWEPT BY PREFIX, NOT LISTED — AND THE VERSION BEFORE THIS ONE CLAIMED THE SWEEP // WITHOUT DOING IT. Its comment called this "the Go-side sibling of -// `tests/testlib/env_pin.py`, which does the same job". `env_pin` clears by PREFIX plus the -// derived host-label names; this function hand-listed four extras beside the ledger and so +// `tests/testlib/env_pin.py`, which does the same job". `env_pin` (since retired with the Python +// client) cleared by PREFIX plus the derived host-label names; this function hand-listed four extras beside the ledger and so // missed `CAIRN_MIRROR_ROOT`, which `cli.go` reads with a direct `os.Getenv`. A developer // with that exported reached a test that believed it had cleared the environment. The // docstring named a relationship while the body inspected one side of it. diff --git a/internal/client/exit.go b/internal/client/exit.go index 99e61d89..f9d1ba93 100644 --- a/internal/client/exit.go +++ b/internal/client/exit.go @@ -23,14 +23,14 @@ package client // actually read — at ONE call site, which already knows the verb it invoked. `doctor` never // creates an entry and `create` never runs diagnostics. // -// 🔴 AND THE LEDGER THAT PINS THAT SET IS PYTHON-ONLY UNTIL SOMETHING READS THIS FILE. -// `tests/test_cairn_doctor.py` DISCOVERS both operands — doctor's codes and the client's — -// but it discovers the CLIENT's by walking the `cairn` script's AST, which cannot see a -// compiled binary. That is a real gap, not a detail: a Go-only code colliding with 10 would -// leave that ledger green. It is closed by `ExitCodes()` below, which is read out of the -// RUNNING binary by `cairn -exit-codes` and compared against the Python set by -// `tests/test_cairn_doctor.py::TestTheSharedExitCodeSetCoversTheGoClientToo` — the same -// shape, and for the same reason, as `api.DeclaredRoutes()` and `cairn-server -routes`. +// 🔴 AND THE LEDGER THAT PINNED THAT SET WAS PYTHON-ONLY UNTIL SOMETHING READ THIS FILE. +// The retired `tests/test_cairn_doctor.py` discovered both operands — doctor's codes and the +// client's — but it discovered the CLIENT's by walking the `cairn` script's AST, which cannot +// see a compiled binary: a Go-only code colliding with 10 would have left that ledger green. +// `ExitCodes()` below closed it, read out of the RUNNING binary by `cairn -exit-codes` — the +// same shape, and for the same reason, as `api.DeclaredRoutes()` and `cairn-server -routes`. +// With the Python client gone the cross-client equality is deleted; what reads the table now +// is `tests/test_go_client_ledgers.py::test_the_go_clients_exit_codes_keep_the_shared_set_at_0_and_9`. const ( ExitOK = 0 // ExitUsage is the third bucket, not a read outcome: the caller must change the diff --git a/internal/client/focus.go b/internal/client/focus.go index 23fba156..dd3f7e02 100644 --- a/internal/client/focus.go +++ b/internal/client/focus.go @@ -154,13 +154,14 @@ var _ = unicode.IsSpace // (`flake.nix` → `python312`, **3.12.14**), not read: at `0111`, `os.listdir` is called **0** // times and `Path.glob` raises nothing; control, the same fixture readable, finds the doc. So // an auditor asking whether that arm is dead code gets no evidence from here, and anyone -// trying to close `tests/parity/README.md` residual 10 by adjusting it would change nothing. +// trying to close `tests/parity/README.md` residual 10 by adjusting it would have changed +// nothing (that README is deleted with the oracle; read it at `ec1b756`). // Do not restate a mechanism you have not measured yourself; if you keep one, pin the // interpreter version beside it and say it was measured. // -// ⚠ SO THE `--x` REPO IS A REAL DIVERGENCE, NOW DECLARED RATHER THAN ASSERTED AWAY — -// `tests/parity/README.md` residual **10**, which also records that the parity harness -// cannot build such a world. The Go behaviour is kept because it is the NON-NARROWING +// ⚠ SO THE `--x` REPO WAS A REAL DIVERGENCE, DECLARED RATHER THAN ASSERTED AWAY — +// `tests/parity/README.md` residual **10**, which also recorded that the parity harness +// could not build such a world. The Go behaviour is kept because it is the NON-NARROWING // direction and because it is what `filepath.Glob` did here before the fix: the same "answer // the doc rather than claim absence" direction this function exists to protect. It is NOT // kept because the oracle agrees. It does not. diff --git a/internal/client/instances.go b/internal/client/instances.go index d9e0855a..023fca14 100644 --- a/internal/client/instances.go +++ b/internal/client/instances.go @@ -15,7 +15,7 @@ import ( // WHICH INSTANCE does a scope live on, and where is each instance configured? // -// The Go port of `lib/cairn_instances.py` and of `subsystem_read_store`'s alias half. A +// The Go port of the retired `lib/cairn_instances.py` and of `subsystem_read_store`'s alias half. A // deployment may point one client at more than one cairn; this file owns what is configured, // which instance a scope belongs to, and whether the two agree — for a client that knows // NOTHING about who routes where. The scope→alias table is an INPUT (a file), never a constant @@ -63,12 +63,14 @@ import ( // here. `README.md`'s announcement DROPS it rather than recording it — this comment once said // the opposite, and the draft paragraph it referred to was cut: a consumer-facing section // cannot hand a consumer an action for a change that measurably is not one. The record lives -// here, in `lib/README.md`'s bullet and in `tests/parity/README.md`, which is where a -// contributor who might re-derive the wrong expectation reads. +// here and in `ROUTING.md`, which is where a contributor who might re-derive the wrong +// expectation reads (it also lived in `lib/README.md`'s bullet and `tests/parity/README.md`, +// both deleted with the Python oracle; read it at `ec1b756`). // // `sync`, `ls-entries` and `doctor` route NOTHING, so none of -// this reaches them. The same clause is on `lib/README.md`'s bullet, in `tests/parity/README.md`, -// in `cairn`'s `_instance_for` and on `Sync`. +// this reaches them. The same clause is in `ROUTING.md` and on `Sync` (and was on +// `lib/README.md`'s bullet, in `tests/parity/README.md` and in `cairn`'s `_instance_for`, all +// deleted with the Python oracle). // // 🔴 AND THAT LAST CLAUSE USED TO GIVE A DIFFERENT, FALSE REASON — "take no scope, so none of // this reaches them" — WHICH `--help` FALSIFIES FOR TWO OF THE THREE. `cairn sync` and diff --git a/internal/client/ledger_main_test.go b/internal/client/ledger_main_test.go index 27fa429d..1dbc16d9 100644 --- a/internal/client/ledger_main_test.go +++ b/internal/client/ledger_main_test.go @@ -11,8 +11,8 @@ import ( // from inside an agent session (`CLAUDE_CODE_SESSION_ID` set, the developer's real // `XDG_STATE_HOME`), every served call a test made appended FIXTURE scopes to that session's REAL // read ledger — measured: 24 records from one `go test ./internal/... ./cmd/...` — which the capture -// agent then uploads, making the developer's session owner-only (#266's audit; the Python twin is -// `tests/testlib/env_pin.py`'s `READ_LEDGER_ENV`). So TestMain clears both session ids and pins +// agent then uploads, making the developer's session owner-only (#266's audit; the Python twin was +// `tests/testlib/env_pin.py`'s `READ_LEDGER_ENV`, retired with the Python client). So TestMain clears both session ids and pins // `XDG_STATE_HOME` to a scratch directory before any test runs; a test that wants a ledger sets its // own. The originals are kept ONLY so [TestTheTestBinaryWritesNoInheritedLedger]'s probe can prove // its instrument sees a file. diff --git a/internal/client/log.go b/internal/client/log.go index 89d745f7..582471b5 100644 --- a/internal/client/log.go +++ b/internal/client/log.go @@ -20,7 +20,7 @@ import ( // THE `log` VERB — L2 search over the stored session transcripts (Phase 1 of // `claudedocs/plan-cairn-v1-event-log.md`), Go-only and declared (the `log` row of -// `tests/testlib/capability_ledger.LEDGER`, `flake.nix`'s `want-go-only-verbs.txt`). +// `tests/testlib/capability_ledger.LEDGER`, `flake.nix`'s `want-all-verbs.txt`). // // cairn log list [--since DATE] [--until DATE] [--cwd PREFIX | --all-repos] [--limit N] [--session ID] // cairn log search QUERY [--since DATE] [--until DATE] [--cwd PREFIX | --all-repos] [--session ID] [--limit N] diff --git a/internal/client/lsentries_test.go b/internal/client/lsentries_test.go index 62a38583..08636821 100644 --- a/internal/client/lsentries_test.go +++ b/internal/client/lsentries_test.go @@ -17,10 +17,10 @@ import ( // entry — measured twelve of them on a populated cache. // // 🔴 EVERY TEST IN THIS FILE IS RED AT THE COMMIT BEFORE THE FIX, WITH THE README IN THE -// LISTING rather than with an error. The oracle's own coverage for the same rows is -// `tests/test_cairn_cli.py::TestLsEntriesListsENTRIES`; the two clients are compared -// byte-for-byte by `tests/parity/harness.py`, whose world now seeds sheets and lookalikes, -// so a one-sided fix is a divergence rather than a fix. +// LISTING rather than with an error. The oracle's own coverage for the same rows was +// `tests/test_cairn_cli.py::TestLsEntriesListsENTRIES`, and the two clients were compared +// byte-for-byte by `tests/parity/harness.py`, whose world seeded sheets and lookalikes. Both +// are deleted with the Python oracle, so these rows are now the only coverage. // lsLines is the listing as a slice, with the trailing newline removed and an empty listing // reported as an empty slice rather than as one empty string. @@ -195,10 +195,10 @@ func TestLsEntriesListsAREADMELookalikeAsAnOrdinaryEntry(t *testing.T) { // treats its anchor literally — so this was also a silent divergence the parity gate cannot // see, because no world builds a cache root with a metacharacter in it. // -// ⚠ THE PYTHON TWIN OF THIS ROW IS AN INVARIANT GUARD, AND IS LABELLED AS ONE: -// `tests/test_cairn_cli.py::TestLsEntriesListsENTRIES:: +// ⚠ THE PYTHON TWIN OF THIS ROW (retired with the oracle) WAS AN INVARIANT GUARD, AND WAS LABELLED +// AS ONE: `tests/test_cairn_cli.py::TestLsEntriesListsENTRIES:: // test_a_cache_ROOT_carrying_a_glob_METACHARACTER_still_lists_its_entries` PASSES at -// `a41dd02`. Only this client was wrong; the oracle's row pins that it stays right. +// `a41dd02`. Only this client was wrong; the oracle's row pinned that it stayed right. func TestLsEntriesReadsACacheROOTCarryingAGlobMetacharacter(t *testing.T) { // `t.TempDir()` cannot be made to carry a metacharacter, so `$HOME` is a subdirectory of // it that does — which makes the DEFAULT cache root (`$HOME/.cache/subsystem-store`) the diff --git a/internal/client/memo.go b/internal/client/memo.go index eb938804..f39445b9 100644 --- a/internal/client/memo.go +++ b/internal/client/memo.go @@ -23,9 +23,10 @@ import ( ) // THE MEMO VERBS — `memo-check`, `memo-read`, `memo-send`, `memo-retract` — S3 of -// `claudedocs/plan-cairn-scope-mail.md` (decision 8), Go-only and declared (the `go_only` rows of -// `tests/testlib/capability_ledger.LEDGER`, `flake.nix`'s `want-go-only-verbs.txt`, residual 11 of -// `tests/parity/README.md`). +// `claudedocs/plan-cairn-scope-mail.md` (decision 8), Go-only and declared (Go-only-marked rows of +// `tests/testlib/capability_ledger.LEDGER`, the flake's separate Go-only verb list, residual 11 of +// `tests/parity/README.md`) until the oracle was retired and the Go-only mark was folded away; +// they are ordinary rows of that ledger now. // // 🔴 THEY TALK TO `cairn-ui`'S CLIENT LISTENER, NEVER TO THE POD. Memos live in `cairn-ui`'s // database (decision 2), so the base URL is the instance's `CAIRN_UI_URL` and the credential is @@ -774,8 +775,9 @@ func MemoRetract(env Env, opts Options) (int, error) { var memoWarnings *[]string // deferMemoWarnings points the deprecation sink at a buffer. `Run` calls it for `memo-check` only: -// the other verbs' stderr is diffed byte-for-byte against the oracle (`tests/parity/`), so their -// warning position is part of a contract `memo-check`, which the oracle does not have, is not in. +// the other verbs' stderr was diffed byte-for-byte against the oracle by the retired +// `tests/parity/`, so their warning position was part of a contract `memo-check`, which the oracle +// never had, was not in. func deferMemoWarnings(env Env) { buf := []string{} memoWarnings = &buf diff --git a/internal/client/readledger.go b/internal/client/readledger.go index 5d9f6006..45f420ee 100644 --- a/internal/client/readledger.go +++ b/internal/client/readledger.go @@ -34,8 +34,8 @@ import ( // // 🔴 INVISIBLE TO THE CLIENT'S CONTRACT. Every error here — no state directory, a read-only one, a // symlink where the file should be, a full disk — is SWALLOWED: nothing on stdout or stderr, no -// change to the exit code. That is what keeps `tests/parity/` (which diffs stdout, stderr and the -// exit code byte for byte) unchanged by this file, and what keeps a broken ledger from breaking the +// change to the exit code. That is what kept the retired `tests/parity/` (which diffed stdout, +// stderr and the exit code byte for byte) unchanged by this file, and what keeps a broken ledger from breaking the // tool an agent is using. The cost is stated in threat T3: a write that fails leaves the ledger // SHORT, and the pod's F1 fallback covers it only when the ledger is entirely empty. // @@ -58,8 +58,9 @@ const ( ) // LedgerClass is what one verb's served call records (#266's audit, round 0): the Go verb table -// carries one per verb, the Python oracle mirrors the table (`lib/read_ledger.py`'s `VERB_CLASS`), -// and `tests/test_read_ledger.py` holds the two equal. +// carries one per verb. The Python oracle mirrored the table (`lib/read_ledger.py`'s `VERB_CLASS`) +// and `tests/test_read_ledger.py` held the two equal; both are deleted with the oracle, so +// nothing compares this table against a second one any more. type LedgerClass string const ( @@ -82,8 +83,8 @@ const LedgerSchema = 1 const LedgerAllScopes = "*" // LedgerRecord is one line of the ledger. The field ORDER is the wire order, and the Python oracle -// (`lib/read_ledger.py`) writes the same keys in the same order; `tests/parity/` compares the two -// clients' files with `at`, `client` and `client_version` normalised. +// (`lib/read_ledger.py`) wrote the same keys in the same order; the retired `tests/parity/` +// compared the two clients' files with `at`, `client` and `client_version` normalised. type LedgerRecord struct { Schema int `json:"schema"` Session string `json:"session"` diff --git a/internal/client/readstore.go b/internal/client/readstore.go index 14a76c5e..89dba325 100644 --- a/internal/client/readstore.go +++ b/internal/client/readstore.go @@ -15,11 +15,11 @@ // cluster reconcile would turn "orient me" into an error, or — worse — into an empty // screen that reads like "nothing recorded". // -// ⚠ THE PYTHON CLIENT IS STILL SHIPPED AND IS STILL THE ORACLE. `tests/parity/` runs both -// against ONE cache root and diffs stdout, stderr and exit code per verb; until that gate -// has held over real use, this package is the second implementation and `cairn` is the -// first. Do not delete the Python client, its `lib/`, or its packaging on the strength of -// a green parity run — that is P8's step, not this one's. +// ⚠ THIS PACKAGE WAS THE SECOND IMPLEMENTATION AND IS NOW THE ONLY ONE. While the Python +// client shipped, it was the oracle and `tests/parity/` ran both against ONE cache root and +// diffed stdout, stderr and exit code per verb. P8 deleted the Python client, its `lib/`, its +// packaging and that gate together; what it agreed with survives as the frozen contracts +// recorded at `ec1b756`. package client import ( diff --git a/internal/client/routes.go b/internal/client/routes.go index 8c0db9b5..fa05f05b 100644 --- a/internal/client/routes.go +++ b/internal/client/routes.go @@ -107,9 +107,9 @@ func Routes(env Env, opts Options) (int, error) { // instance, a one-route table, cache root at 0111: this client exits **3** printing // `open : permission denied` where one level down it prints // `index entry unreadable: under (PermissionError: …)`, and the ORACLE exits - // **1** with a traceback. So both the TEXT and the code diverge. It is the cache-ROOT - // depth of `tests/parity/README.md` row 4, which carries it with a closing condition. - // UNGATED. + // **1** with a traceback. So both the TEXT and the code diverged. It was the cache-ROOT + // depth of `tests/parity/README.md` row 4, which carried it with a closing condition + // (deleted with the oracle; read it at `ec1b756`). UNGATED. entries, readErr := os.ReadDir(cache) if readErr != nil { return 0, readErr diff --git a/internal/client/snapshot.go b/internal/client/snapshot.go index d25c4c30..a01c61cc 100644 --- a/internal/client/snapshot.go +++ b/internal/client/snapshot.go @@ -151,28 +151,20 @@ func safeMemberName(name string) bool { // `fnmatch` reads an UNTERMINATED `[` as a literal character where `filepath.Match` refuses the // whole pattern. See `anchor.go` for the class. // -// ⚠ AND THE PREFIX IS NOW LITERAL, WHICH IS A DECLARED DIVERGENCE RATHER THAN A SIDE EFFECT — -// `tests/parity/README.md` residual 9. The name searched for is one this code CREATED, with -// `os.MkdirTemp(parent, base+".new-")`, so a literal prefix is what it always meant and the -// glob spelling was incidental on both clients. Measured, both directions: with a BALANCED -// class in the cache's basename (`wid[ge]t`) `fnmatch` and `filepath.Match` AGREE — both read -// `[ge]` as a character class, so both miss `wid[ge]t.old-…` and both would reap a -// `widgt.old-…` belonging to a different cache. This client now does neither; the oracle still -// does both. Narrow, in the safe direction, and the price of the fix above. -// -// ⚠ `[ge]` IS ONE MEMBER OF THE FAMILY AND NOT THE FAMILY: A `*` OR A `?` IN THE CACHE'S -// BASENAME IS THE SAME DIVERGENCE IN THE SAME DIRECTION, and naming only the balanced class -// read as though they were covered. MEASURED on CPython 3.12.14 over one directory holding -// `wid*t.old-mine`, `wid?et.old-mine2`, `widget.old-sibling`, `widIt.old-sibling2` and -// `widXet.old-other`: for a cache named `wid*t`, `Path.glob("wid*t.old-*")` and -// `fnmatch("wid*t.old-*")` each return ALL FIVE, and for `wid?et` each returns the three whose -// fourth character is anything at all; `strings.HasPrefix` returns exactly the one tree the -// cache created, in both cases. So the oracle offers a SIBLING cache's staging trees for -// removal and this client does not. ⚠ The direction is not identical to the `[ge]` case and the -// difference is worth the clause: with a balanced class the oracle MISSES its own trees, while -// with `*`/`?` it finds its own AND over-reaps its neighbours'. And unlike an UNTERMINATED `[` -// there is no `ErrBadPattern` on either side to make it visible — it is the quiet arm of the -// class `anchor.go`'s header names. +// 🔴 THE PREFIX IS LITERAL, AND A GLOB WOULD BE WRONG IN BOTH DIRECTIONS. The name searched for +// is one this code CREATED, with `os.MkdirTemp(parent, base+".new-")`, so a literal prefix is what +// it always meant. The measurement that is a property of the MATCHERS (not of any client), kept +// here because it is why a glob must not come back: with a BALANCED class in the cache's +// basename (`wid[ge]t`) `fnmatch` and `filepath.Match` AGREE — both read `[ge]` as a character +// class, so both MISS `wid[ge]t.old-…` and both would reap a `widgt.old-…` belonging to a +// different cache; and with a `*` or `?` in the basename (measured on CPython 3.12.14 over one +// directory holding `wid*t.old-mine`, `wid?et.old-mine2`, `widget.old-sibling`, +// `widIt.old-sibling2`, `widXet.old-other`) `Path.glob("wid*t.old-*")`/`fnmatch` return ALL +// FIVE, and for `wid?et` the three whose fourth character is anything — a glob finds its own +// trees AND over-reaps its neighbours', with no `ErrBadPattern` to make it visible. +// `strings.HasPrefix` returns exactly the one tree the cache created, in both cases. (This was +// declared as a divergence from the retired Python client, which globbed; with that client gone +// it is simply what the client does.) func ReapOrphans(cache string) int { cutoff := time.Now().Add(-OrphanGraceSeconds * time.Second) parent, name := filepath.Dir(cache), filepath.Base(cache) diff --git a/internal/client/transcript.go b/internal/client/transcript.go index c8f38018..cdd11573 100644 --- a/internal/client/transcript.go +++ b/internal/client/transcript.go @@ -17,7 +17,8 @@ import ( // THE `transcript` VERB — S8 of `claudedocs/plan-cairn-plugins.md` (decision 17; Q15 adopted under // O13), Go-only and declared (the `transcript` row of `tests/testlib/capability_ledger.LEDGER`, -// `flake.nix`'s `want-go-only-verbs.txt`, residual 11 of `tests/parity/README.md`). +// the flake's separate Go-only verb list, residual 11 of `tests/parity/README.md`) until the oracle +// was retired and the Go-only mark was folded away. // // cairn transcript skeleton --session ID // cairn transcript records --session ID [--stream S] [--from-seq N] [--to-seq N] [--class C] diff --git a/internal/client/transport.go b/internal/client/transport.go index 1b4732e1..d445a923 100644 --- a/internal/client/transport.go +++ b/internal/client/transport.go @@ -73,8 +73,12 @@ type Config struct { // // ⚠ IT IS nil UNTIL `Run` SETS IT, WHICH MEANS A TEST CALLING `LoadConfigFor` DIRECTLY SEES // NO WARNING. That is deliberate — a library call should not write to a stream its caller -// did not name — and it is why `tests/parity/harness.py`, which runs the real binary, is -// what measures the emission rather than a unit test asserting on a captured writer. +// did not name — so the emission is measured through `Run`, the CLI's own entry point, +// which wires the sink: `TestAnEnvironmentAliasIsAnnouncedOnStderrByTheCLI` (stderr, once, +// never stdout). That replaced `tests/parity/harness.py`'s run of the real binary when the +// Python oracle was deleted. ⚠ That test covers the ENVIRONMENT half only: the FILE-key +// half's text is pinned in `internal/envalias` (`FileWarning`), but its emission through +// `LoadConfigFor` and this sink is measured by no test — stated, not closed. var deprecationSink func(string) // SetDeprecationSink names where alias deprecation warnings go. `Run` calls it. @@ -92,8 +96,8 @@ func WarnDeprecations(lines []string) { // current spelling. Each reads from an exported variable OR from a key of the config // file, and each has a deprecated `SUBSYSTEM_STORE_*` alias resolved by // `internal/envalias`. They are named constants rather than literals because the -// "config incomplete" refusal interpolates them, and that refusal is compared -// byte-for-byte against the Python client by `tests/parity/harness.py`. +// "config incomplete" refusal interpolates them, and that refusal was compared +// byte-for-byte against the Python client by the retired `tests/parity/harness.py`. const ( EnvURL = "CAIRN_URL" EnvToken = "CAIRN_TOKEN" diff --git a/internal/client/unreadablescope_test.go b/internal/client/unreadablescope_test.go new file mode 100644 index 00000000..ade180f2 --- /dev/null +++ b/internal/client/unreadablescope_test.go @@ -0,0 +1,87 @@ +package client + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/ZacxDev/cairn/internal/envalias" +) + +// The coverage the retired parity harness used to give, replaced by Go tests against the +// real CLI entry point (`Run`): an unreadable SCOPE DIRECTORY on `recall` and `validate`, +// and the alias deprecation line on stderr. (`recall` and `validate` over an unreadable +// ENTRY are `TestAnUnreadableEntryIsReportedWithTheORACLESSentenceAtExitThree`.) + +func unreadableScopeDirHost(t *testing.T) (home, dir string) { + t.Helper() + home = oneInstanceHost(t) + dir = filepath.Join(home, ".cache", "subsystem-store", "alpha-notes") + // Reachability control: the scope directory must exist, hold an entry, and be + // readable BEFORE the chmod, or "the read failed" would measure an absence. + if names, err := os.ReadDir(dir); err != nil || len(names) == 0 { + t.Fatalf("the fixture never seeded a readable scope directory: %v %v", names, err) + } + if err := os.Chmod(dir, 0o000); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + if _, err := os.ReadDir(dir); err == nil { + t.Skip("running with privileges that read a mode-000 directory; the condition cannot be built") + } + return home, dir +} + +func TestAnUnreadableScopeDirectoryIsReportedWithTheReadersSentenceAtExitThree(t *testing.T) { + for _, verb := range []string{"recall", "validate"} { + t.Run(verb, func(t *testing.T) { + _, dir := unreadableScopeDirHost(t) + code, stdout, stderr := runCLI(t, verb, "--scope", "alpha-notes", "--no-sync") + if code != ExitUnreachableNoCache { + t.Fatalf("an unreadable scope directory exits %d, got %d\nstdout: %s\nstderr: %s", + ExitUnreachableNoCache, code, stdout, stderr) + } + if !strings.Contains(stderr, "index entry unreadable: under ") { + t.Fatalf("the reader's own sentence must name the store, got:\n%s", stderr) + } + if !strings.Contains(stderr, "the store was not fully read") { + t.Fatalf("…and must say the read was INCOMPLETE, got:\n%s", stderr) + } + wantTail := "(PermissionError: [Errno 13] Permission denied: '" + dir + "')" + if !strings.Contains(stderr, wantTail) { + t.Fatalf("the OS-error tail must name the DIRECTORY, want %q in:\n%s", wantTail, stderr) + } + if strings.Contains(stdout, "nothing recorded") { + t.Fatalf("an unreadable scope must never read as an empty one:\n%s", stdout) + } + }) + } +} + +// A `SUBSYSTEM_STORE_*` alias in the ENVIRONMENT reaches the CLI and is announced on +// STDERR — once, naming its replacement — and never on stdout. Through `Run`, the CLI's +// own entry point, which is where the sink is wired (`SetDeprecationSink`). +func TestAnEnvironmentAliasIsAnnouncedOnStderrByTheCLI(t *testing.T) { + home := oneInstanceHost(t) // sets SUBSYSTEM_STORE_URL / _TOKEN, not the new names + _ = home + t.Setenv("CAIRN_URL", "") + t.Setenv("CAIRN_TOKEN", "") + os.Unsetenv("CAIRN_URL") + os.Unsetenv("CAIRN_TOKEN") + envalias.ResetWarnedForTest() + t.Cleanup(envalias.ResetWarnedForTest) + + code, stdout, stderr := runCLI(t, "doctor", "--no-sync") + _ = code // doctor's verdict is not the subject; the announcement is + want := "cairn: $SUBSYSTEM_STORE_URL is a deprecated alias for $CAIRN_URL." + if !strings.Contains(stderr, want) { + t.Fatalf("no deprecation line for the env alias; want %q in stderr:\n%s", want, stderr) + } + if strings.Count(stderr, want) != 1 { + t.Fatalf("the line must appear ONCE, got %d:\n%s", strings.Count(stderr, want), stderr) + } + if strings.Contains(stdout, "deprecated alias") { + t.Fatalf("the deprecation line leaked onto stdout:\n%s", stdout) + } +} diff --git a/internal/client/validate_test.go b/internal/client/validate_test.go index ec9db62c..6783d424 100644 --- a/internal/client/validate_test.go +++ b/internal/client/validate_test.go @@ -18,11 +18,11 @@ import ( // COUNT rather than with an error: `1 of 1` where `0 of 0` is honest, `2 of 2` where the // README inflates it to `3 of 3`, and `1 of 2 … 1 malformed` where nothing parsed at all. // -// The oracle's own regression coverage for the same three rows is +// The oracle's own regression coverage for the same three rows was // `tests/test_cairn_cli.py::TestValidateActuallyRuns` (`test_the_count_EXCLUDES_the_scopes_README`, // `test_a_scope_holding_ONLY_a_README_reports_ZERO_walked`, -// `test_the_MALFORMED_count_is_not_softened_by_a_README`). The two clients are compared -// byte-for-byte by the parity gate, so a one-sided fix is a divergence, not a fix. +// `test_the_MALFORMED_count_is_not_softened_by_a_README`), and the two clients were compared +// byte-for-byte by the parity gate. Both are deleted with the Python oracle. // seedREADME drops a scope-policy sheet into a cached scope. It is NOT an entry: the loader // skips one in every scope, and `/snapshot` ships it, so a real cache has them. @@ -148,7 +148,7 @@ func seedNamedEntry(t *testing.T, root, scope, filename, service string) { // then succeeds — same inode. So the control passed while the fixture had stopped // discriminating the exact-spelling rule from a case fold, and the row went on to fail on // its main assertion with a message pointing at the FILTER rather than at the filesystem. -// `tests/parity/world.py`'s `build_store` already compares CONTENT for exactly this reason; +// The retired `tests/parity/world.py`'s `build_store` compared CONTENT for exactly this reason; // this is that check on this side of the gate, so a fold fails here and says so. // // ⚠ IT ASSERTS DISTINCTNESS, WHICH IS A CLAIM ABOUT THE FIXTURES TOO. Every caller seeds @@ -265,11 +265,10 @@ func TestValidateCountsAREADMELookalikeAsAnOrdinaryEntry(t *testing.T) { // that had the package and not the launcher — the deployed case — ran a check that was // silently weaker than the mandated one, and nothing in its output said so. // -// The oracle's own coverage for the same rows is +// The oracle's own coverage for the same rows was // `tests/test_cairn_cli.py::TestValidateReportsTheWriteProtocolContract`, and the two -// clients are compared byte-for-byte by `tests/parity/` over a scope -// (`crag-notes`) seeded with exactly these defects — so a one-sided change is a -// divergence, not a fix. +// clients were compared byte-for-byte by `tests/parity/` over a scope +// (`crag-notes`) seeded with exactly these defects. Both are deleted with the Python oracle. // seedLossyEntry writes an entry that PARSES and still holds three things no reader can // reach: two lines before the first bullet (the second a declaration) and a @@ -503,14 +502,14 @@ func TestAScopeHoldingONLYAnUnopenablePathAlsoSaysNotChecked(t *testing.T) { // The two NEW blocks, at the verb // -------------------------------------------------------------------------- // -// The oracle's own coverage for the same rows is +// The oracle's own coverage for the same rows was // `tests/test_cairn_cli.py::TestValidateReportsTheWriteProtocolContract` // (`test_a_BENT_SPINE_that_PARSES_is_reported_by_the_ENTRY_SHAPE_block`, // `test_ALL_FOUR_OPEN_ACTION_POPULATIONS_are_reported_SEPARATELY`, // `test_neither_NEW_advisory_moves_the_EXIT_CODE`, -// `test_a_CLEAN_scope_prints_all_FOUR_denominators_IN_ORDER`), and the two clients are -// compared byte-for-byte by `tests/parity/` over `crag-notes`, which now carries every -// shape kind and every openness population — so a one-sided change is a divergence. +// `test_a_CLEAN_scope_prints_all_FOUR_denominators_IN_ORDER`), and the two clients were +// compared byte-for-byte by `tests/parity/` over `crag-notes`, which carried every shape kind +// and every openness population. Both are deleted with the Python oracle. // seedBentSpine writes an entry that PARSES and whose SPINE is wrong three ways at once: // `## Pointers` renamed by case, and the nuance heading written twice with nothing under @@ -728,10 +727,10 @@ func runCLI(t *testing.T, argv ...string) (int, string, string) { // already answered 3, so a row asserting only the code would be an INVARIANT GUARD wearing a // regression test's name. What is red at that commit is the SENTENCE: the two assertions below // on `index entry unreadable` and on the CPython `[Errno 13] … : ''` tail both fail -// there. The oracle's half of the same fix — the exit code — is red in +// there. The oracle's half of the same fix — the exit code — was red in // `tests/test_cairn_cli.py::TestAnUnreadableEntryExitsThreeAndNeverTracebacks`, and the pair -// being compared byte-for-byte is `tests/parity/harness.py`'s -// `validate-unreadable-entry` / `recall-unreadable-entry` rows. +// was compared byte-for-byte by `tests/parity/harness.py`'s +// `validate-unreadable-entry` / `recall-unreadable-entry` rows (all deleted with the oracle). // // ⚠ THE MODE IS SET HERE AND RESTORED HERE. Git does not preserve `000`, so a committed // fixture would arrive readable in CI and every row below would pass over a file nothing diff --git a/internal/client/verbs.go b/internal/client/verbs.go index 8861d5e9..a772505d 100644 --- a/internal/client/verbs.go +++ b/internal/client/verbs.go @@ -156,9 +156,10 @@ func LsEntries(env Env, opts Options) (int, error) { // `anchor.go`. The measurements that were recorded here have moved beside the code // that carries them (`Put` below, `Focus` in `focus.go`, `ReapOrphans` in // `snapshot.go`), because a comment describing a hazard as OPEN is a claim like any - // other and this one would now be false. Residual 9 in `tests/parity/README.md` is - // retired with it; what remains there are the two NARROW divergences the fix chose - // deliberately, which are a different statement. + // other and this one would now be false. Residual 9 in `tests/parity/README.md` was + // retired with it; what remained there were the two NARROW divergences the fix chose + // deliberately, which are a different statement (that README is deleted with the + // oracle; read it at `ec1b756`). // // 🔴 A SCOPE'S `README.md` IS ITS POLICY SHEET, NOT AN ENTRY. Until the filter // existed `ls-entries` listed every scope's sheet as `/README.md` — measured @@ -198,10 +199,10 @@ func LsEntries(env Env, opts Options) (int, error) { // The cache-root row does not reach this walk on EITHER client. `ResolveState` runs // first and reads `.sync-stamp`: the Go client turns that into a state whose // `ExitHint` is `ExitUnreachableNoCache`, banners `store-unreachable, no cache`, and - // the loop `continue`s above — so this code never runs. The oracle raises an UNCAUGHT + // the loop `continue`s above — so this code never runs. The oracle raised an UNCAUGHT // `PermissionError` out of `resolve_state`'s `(cache / SYNC_STAMP).exists()` and - // exits 1 with a traceback, which is `tests/parity/README.md` residual 4's route, not - // a quiet empty listing. + // exited 1 with a traceback, which was `tests/parity/README.md` residual 4's route + // (deleted with the oracle; read it at `ec1b756`), not a quiet empty listing. // // So the claim this paragraph is entitled to is the narrow one: an unreadable SCOPE // DIRECTORY contributes no lines and its siblings still list, on both clients. An @@ -256,8 +257,8 @@ func LsEntries(env Env, opts Options) (int, error) { // unreadable root refuses the whole listing or only that instance's. The two must be // decided together. ⚠ `Validate`'s copy of this read is not closed either — it // RETURNS the raw `*os.PathError` rather than discarding it, so the exit code is 3 - // but the text is not the reader's sentence while the oracle tracebacks at 1; - // `tests/parity/README.md` row 4 carries that whole depth. + // but the text is not the reader's sentence while the oracle died with a traceback at 1; + // `tests/parity/README.md` row 4 carried that whole depth (deleted with the oracle). scopeDirs, _ := os.ReadDir(cache) for _, d := range scopeDirs { scopePath := filepath.Join(cache, d.Name()) @@ -634,8 +635,8 @@ func Validate(env Env, opts Options) (int, error) { // `index entry unreadable: under (PermissionError: …)`, while the ORACLE dies with // a traceback at exit 1. `recall` and `search` are byte-identical at 3 for that same // root, because they reach the walk through `LoadStore`; only this verb reads the root - // itself. Both cache-root modes are `tests/parity/README.md` row 4, which carries them - // with a closing condition. UNGATED. + // itself. Both cache-root modes were `tests/parity/README.md` row 4, which carried them + // with a closing condition (deleted with the oracle; read it at `ec1b756`). UNGATED. var held []string entries, readErr := os.ReadDir(cache) if readErr != nil { @@ -777,8 +778,9 @@ func Validate(env Env, opts Options) (int, error) { // `cairn: : 0 of 0 entry file(s) parse, 0 malformed` at exit **0** — a // confident zero over a directory nothing read — while the oracle dies with a // `FileNotFoundError` traceback at exit **1**. UNGATED, and declared in - // `tests/parity/README.md` → "What the gate structurally cannot see": no STATIC world - // reaches the read, so the parity gate cannot own it. + // `tests/parity/README.md` → "What the gate structurally cannot see" (deleted with the + // oracle; read it at `ec1b756`): no STATIC world reaches the read, so the parity gate could not + // own it. // // ⚠ AN UNCLAIMED CONSEQUENCE, RECORDED BECAUSE NO FIXTURE COVERS IT: reading the // directory (`EntryFileNames` → `os.ReadDir`) instead of globbing @@ -1077,15 +1079,13 @@ func Put(env Env, opts Options) (int, error) { // `cannot derive a revision — 0 cached file(s) match …`, exit 2 — while the oracle // still answered `replaced` at exit 0. See `anchor.go` for the class. // - // ⚠ `opts.Ref` IS NOW LITERAL TOO, AND THAT IS A SECOND DECLARED DIVERGENCE - // (`tests/parity/README.md` residual 9). The oracle interpolates the ref into its - // pattern, so `--ref 'wid*'` is a WILDCARD there: it can match exactly one file and - // derive a precondition from `widget-cfg.md` while the `PUT` that follows addresses - // an entry literally named `wid*` — a precondition taken from bytes the request is - // not addressing, which is the one thing this block exists to prevent. Here it finds - // nothing and refuses with the count. Unreachable from the parity corpus (no row - // passes a metacharacter `--ref`), reachable from a keyboard, and the refusal is the - // safe side. + // 🔴 `opts.Ref` IS LITERAL TOO. Interpolated into a pattern, `--ref 'wid*'` would be a + // WILDCARD: it could match exactly one file and derive a precondition from + // `widget-cfg.md` while the `PUT` that follows addresses an entry literally named + // `wid*` — a precondition taken from bytes the request is not addressing, which is the + // one thing this block exists to prevent. Here it finds nothing and refuses with the + // count. (The retired Python client did interpolate it; that was declared as a + // divergence until the client was deleted.) // // The `.*.md` family keeps its ONE wildcard, in `refVariantName` above. scopeDir := filepath.Join(cache, scope) diff --git a/internal/control/README.md b/internal/control/README.md index 1c318e7d..abe2eef8 100644 --- a/internal/control/README.md +++ b/internal/control/README.md @@ -146,9 +146,9 @@ produce the same row: 🔴 **AND IT CARRIES A POSITIVE CONTROL, BECAUSE A MATRIX IN WHICH EVERY CELL REFUSES IS PERFECTLY SELF-CONSISTENT AND MEASURES NOTHING.** This repository has already paid for -that shape once: `tests/parity/README.md` records the P2 harness reporting 72 PASS / -0 FAIL while the pod refused every request, because two clients failing identically -compare equal. So the allow count is pinned from both sides — **39 of 144 cells allow** +that shape once: `tests/parity/README.md` (deleted with the Python oracle; read it at +`ec1b756`) recorded the P2 harness reporting 72 PASS / 0 FAIL while the pod refused every +request, because two clients failing identically compare equal. So the allow count is pinned from both sides — **39 of 144 cells allow** (32 of the 60 user cells, 7 of the 84 federated ones), not 0 and not 144 — and any fixture change moves that number and forces whoever made it to say what they expected. The user rows are walked on the model that also holds the group map, so a mapping that leaked into `Resolve` @@ -234,14 +234,16 @@ last-known-good keeps answering: loop, and `TestTheHotPathDoesNotContactTheAuthority` in `internal/api` measures the no-network claim from both directions against a REAL server rather than a library double. ⚠ What is still not done is the SURFACE that prints `Staleness`: no `doctor` - output and no startup banner carries the epoch. That is deliberate — the banner is a - string `tests/dualrun/harness.py` compares between the two servers, so a Go-only field - there moves a gate in the same change that most needs it. 🔴 **THIS IS THE ONE TRUE + output and no startup banner carries the epoch. That was deliberate — the banner was a + string the retired `tests/dualrun/harness.py` compared between the two servers, so a + Go-only field there would have moved a gate in the same change that most needed it. That + gate went with the Python oracle; the reason is gone and the surface is simply unbuilt. 🔴 **THIS IS THE ONE TRUE SENTENCE ABOUT REPORTING IN THIS FILE, AND TWO OTHERS USED TO CONTRADICT IT** (the revocation paragraph above, and the divergence section below) by writing **reported** where only **reportable** is earned. **CLOSING CONDITION,** so this is checkable rather - than aspirational: a render — a `doctor` section, a status route, or a banner field - declared in `wire.NORMALIZATIONS` — that a `tests/dualrun/` run exits 0 with. ⚠ And the + than aspirational: a render — a `doctor` section, a status route, or a banner field — + that an operator can read. (It also required a `tests/dualrun/` run to exit 0 with the + field declared in `wire.NORMALIZATIONS`; that half is moot.) ⚠ And the cost of leaving it open GREW rather than stayed flat: a store root that will not enumerate is now a refusal, so `degraded` is a state a healthy-looking pod can sit in, and it is exactly the state an operator cannot see. @@ -687,7 +689,7 @@ What it synthesizes, and why each shape was picked: | a row with NO identity | the whole projection is **refused**, so the pod does not start | `Principal.Display` is what the audit line and every written bullet's ACTOR carry, so a principal with no name is a credential whose use cannot be attributed. ⚠ Unreachable from a token FILE — `ParseTokenRow` gives every row an identity — and reachable from a programmatic `TokenRecord`. It is LOUDER than the old behaviour, which was an empty `identity=` field and a bullet attributed to nobody. | | where scope names come from | the UNION of the store's directories and the mapped rows' allowlists | neither alone is enough. Directories are the only record of what a bare row may read; allowlists are the only record of a scope with **no directory yet**, which is the first-entry create that is how the store gained every scope it has. | | a store root that will not ENUMERATE | the whole projection is **refused** | it used to be swallowed, on the true-at-one-instant grounds that every read route answers 503 through such a root anyway. The projection is CACHED, so the empty world it produced was committed, `materializedAt` moved, the status said `fresh`, and it was served **through a root that was readable again** — measured as `200 scope-absent` for a scope that exists on disk. On the deployed shape the principals are bare rows, so `storeDirs` IS the whole enumeration and it is not one scope, it is all of them. Refusing keeps the last-known-good instead, which is what preserves the credential table the old argument was protecting. 🔴 **AND THE SAME MECHANISM PRESERVES A CREDENTIAL THE OPERATOR IS DELETING** — measured at both ends over one probe: at `fb7e788` a SIGHUP reload through a renamed-away root SUCCEEDS and the revoked row stops authenticating; at `ca632e3` the reload REFUSES and the revoked row still authenticates, across that reload and a second attempt inside the same outage, until the root is readable again. The window is the OUTAGE, not the 30s refresh interval, and SIGHUP is the only revocation path the pod has — `Source` has no write half, so `ApplyNow` returns `ErrAuthorityReadOnly` here. It is not silent: the refused-reload line names the fingerprints still serving and says the authority is unchanged. Declared at `tokenfile.Source.Model`. | -| a COLD start over such a root | `api.New` fails and `cmd/cairn-server` exits **78** | a cache with no last-known-good has nothing to keep, so the only two answers are "serve an enumeration known to be wrong" and "do not come up". Nothing served is lost, and that is checked rather than assumed: every read route answers 503 through that root, and a write cannot land either, because `internal/write` creates a scope directory with `os.Mkdir` and not `MkdirAll`, so it fails on the absent parent. The alternative moves the window to startup rather than removing it, which is exactly where an unmounted volume puts it. ⚠ A divergence from `server/server.py`, which starts and answers 503; declared at `tokenfile.Source.Model` with the same closing condition as the divergence below. | +| a COLD start over such a root | `api.New` fails and `cmd/cairn-server` exits **78** | a cache with no last-known-good has nothing to keep, so the only two answers are "serve an enumeration known to be wrong" and "do not come up". Nothing served is lost, and that is checked rather than assumed: every read route answers 503 through that root, and a write cannot land either, because `internal/write` creates a scope directory with `os.Mkdir` and not `MkdirAll`, so it fails on the absent parent. The alternative moves the window to startup rather than removing it, which is exactly where an unmounted volume puts it. ⚠ A divergence from the retired `server/server.py`, which started and answered 503; declared at `tokenfile.Source.Model` with the same closing condition as the divergence below. | | two rows sharing one IDENTITY | interchangeable only if they describe the **same authority**; otherwise **refused** | the dedupe is keyed on `authorityKey` — `IsLegacy()` plus the folded, sorted allowlist — which is derived from the same two facts `grantsFor` branches on. Keyed on the identity STRING alone, every row after the first contributed only a credential: a mapped row named `legacy` ahead of a real bare row gave that bare row `write` on one scope and took `read` away on another. ⚠ Unreachable from a token FILE (`authz.LoadTokens` guards 8 and 12) — which is a guard in a DIFFERENT package being the only thing between this and a wrong authority, and therefore a reason to gate it here rather than not to. | ### 🔴 The divergence, measured rather than reasoned about @@ -1309,9 +1311,9 @@ credential and finds it cannot write. `internal/api` holds one and `cmd/cairn-server` runs its refresh loop). What is left is the **surface**: no `doctor` output and no startup banner carries the epoch. 🔴 Deliberately not done here: adding a field to `cmd/cairn-server`'s startup line - would change a string `tests/dualrun/harness.py` compares between the two servers, - and dualrun needs a live pod that this change was not in a position to run. Wire it - with that gate in front of you, not without it. The same reasoning is why the authz + would have changed a string `tests/dualrun/harness.py` compared between the two servers, + and dualrun needed a live pod that this change was not in a position to run. That gate + is retired with the Python oracle, so it no longer stands in front of this item. The same reasoning is why the authz epoch is **not** surfaced as a response header or a route: that is a CONTRACT change, and it would regenerate the conformance corpus in the one commit whose whole claim is that the corpus did not move. It is its own piece; diff --git a/internal/control/tokenfile/source.go b/internal/control/tokenfile/source.go index 8caf00b2..45f6ee8c 100644 --- a/internal/control/tokenfile/source.go +++ b/internal/control/tokenfile/source.go @@ -61,11 +61,14 @@ // definition, two comments and `_test.go` files, and nothing that runs in the pod. So the // correct sentence is BOUNDED AND SILENT: an operator inside the // window has no way to see it, and an operator inside a `degraded` or `stale` window has -// no way to see that either. The surface is deferred because the one place to print it is -// the startup banner, which `tests/dualrun/harness.py` compares between the two servers — -// a Go-only field there moves a gate in the same change that most needs it. -// **CLOSING CONDITION:** a render (a `doctor` section, a status route, or a banner field -// declared in `wire.NORMALIZATIONS`) that a `tests/dualrun/` run exits 0 with. A mapped +// no way to see that either. The surface was deferred because the one place to print it is +// the startup banner, which the retired `tests/dualrun/harness.py` compared between the two +// servers — a Go-only field there would have moved a gate in the same change that most +// needed it. That gate went with the Python oracle, so the deferral's reason is gone and +// the surface is simply unbuilt. +// **CLOSING CONDITION:** a render (a `doctor` section, a status route, or a banner field) +// that an operator inside the window can read. (It also required a `tests/dualrun/` run to +// exit 0 with the field declared in `wire.NORMALIZATIONS`; that half is moot.) A mapped // row is UNAFFECTED by the divergence itself — its allowlist is in the file, so a scope it // names is covered whether or not the directory exists. // @@ -272,9 +275,9 @@ var ErrStoreRootUnreadable = errors.New("the store root cannot be enumerated") // also removes the window rather than moving it to startup, which is where an unmounted // volume actually puts it. // -// ⚠ IT IS A DIVERGENCE FROM `server/server.py`, DECLARED RATHER THAN HIDDEN. The oracle -// starts over an unreadable root and answers 503 on every read; this binary does not -// start. Nothing else moves: after a materialization, the served answers are the oracle's +// ⚠ IT WAS A DIVERGENCE FROM THE RETIRED `server/server.py`, DECLARED RATHER THAN HIDDEN. The +// oracle started over an unreadable root and answered 503 on every read; this binary does not +// start. Nothing else moved: after a materialization, the served answers are the oracle's // for a root that is readable and 503 for one that is not. **CLOSING CONDITION,** and it // is the same one the divergence above carries: it closes when scopes stop being // discovered from the filesystem at all, because the store root is then not an input to diff --git a/internal/envalias/envalias.go b/internal/envalias/envalias.go index c9969692..470e93c5 100644 --- a/internal/envalias/envalias.go +++ b/internal/envalias/envalias.go @@ -3,22 +3,24 @@ // renames: `SUBSYSTEM_STORE_*` → `CAIRN_*`, and `CAIRN_SUPABASE_*` → `CAIRN_OIDC_*` for // the JWT verifier's settings (see the section on it below). // -// 🔴 THERE ARE TWO SPELLINGS OF THIS LEDGER AND THAT IS PACKAGING, NOT DUPLICATION. -// `packages.cairn` installs the Python client script and `lib/` under `libexec` and -// nothing else, so the Python side CANNOT import a file under `internal/`. The second -// spelling is `lib/env_aliases.py`, and `tests/test_env_aliases.py` pins the two against -// each other — failing when the pair set GROWS *or* SHRINKS, and comparing the rendered -// warnings as WHOLE NORMALISED STRINGS rather than by keyword, because a guard on words -// is walkable by rewording. That two-spellings-plus-a-gate shape is the precedent -// `AGENTS.md` already blesses for `server/Dockerfile` against `flake.nix`'s `serverEnv`. +// 🔴 THIS IS THE ONLY SPELLING OF THE LEDGER NOW. Until the Python client was retired it +// had a twin, `lib/env_aliases.py` (that client could not import `internal/`), pinned +// against this file by `tests/test_env_aliases.py`. The twin went with the client; that +// test now pins THIS file's pair set, anchor and warning texts against literals. // // # What the window is anchored to // -// The old names keep working until the PYTHON CLIENT (`packages.cairn`) is retired — -// the arc's P8 milestone. That is an anchor a reader can CHECK: `packages.cairn` either -// exists in `flake.nix` or it does not. A date could not be checked, there is no semver -// here to hang it on (`flake.nix`: `version = self.shortRev`), and `tests/leakscan.py` -// refuses a dated stamp in this tree anyway. +// 🔴 THE FIRST ANCHOR IS MET, AND THE OLD NAMES STILL WORK — DELIBERATELY. The window was +// "until the Python client (`packages.cairn`) is retired", the arc's P8 milestone, and the +// change that retired that client did NOT also remove the aliases: removing them is a +// BREAKING change for every deployment still exporting a `SUBSYSTEM_STORE_*` or +// `CAIRN_SUPABASE_*` name, and it gets its own change, announced in `CHANGELOG.md`, so an +// operator can read it before it lands. So the anchor moved to that announcement — still a +// thing a reader can CHECK (the entry exists or it does not), never a date: there is no +// semver here to hang one on (`flake.nix`: `version = self.shortRev`), and +// `tests/leakscan.py` refuses a dated stamp in this tree anyway. The next step is that +// change: delete every `Pair` here, the `Deprecations`/`WarnOnce` call sites, and this +// package's warning texts, together, with the CHANGELOG row. // // # 🔴 TWO PAIRS ARE NOT THE MECHANICAL PREFIX SWAP, AND ONE OF THEM WAS A LIVE COLLISION // @@ -63,11 +65,11 @@ // that refusal into a working alias. // // 🔴 ONE `RemovalAnchor` FOR THE WHOLE LEDGER, WHICH IS A WIDER PROMISE THAN THE OIDC PAIRS -// NEED AND IS NOT A CLAIM THAT THE PYTHON CLIENT READS THEM. The anchor is a single -// constant, so those pairs inherit "until `packages.cairn` is retired" — a milestone that -// has nothing to do with a pod-side verifier. Per-pair anchors were the honest alternative -// and were DECLINED: they would change `Pair`, both warning formats, the Python twin and the -// cross-language gate, in order to SHORTEN a deprecation window nobody has asked to shorten. +// NEED. The anchor is a single constant, so those pairs inherit the same one. Per-pair +// anchors were the honest alternative and were DECLINED (when the anchor was still the +// Python client's retirement, a milestone unrelated to a pod-side verifier): they would +// change `Pair`, both warning formats and their pinning test, in order to SHORTEN a +// deprecation window nobody has asked to shorten. // The cost is a warning that names a milestone some readers will find unrelated; what it buys // is one window, one sentence, and no mechanism change. // @@ -100,9 +102,10 @@ // AND IT IS READ BY BOTH HALVES. Spelled inline on each side, the two disagreed: // a whitespace-only OLD value resolved AND did not warn, which is the one combination // the sentence above rules out. -// 3. Warnings are emitted sorted by NEW name. `tests/parity/harness.py` compares the two -// clients' stderr BYTE-FOR-BYTE, so "whatever order the lookups happened in" is not -// an option: the order has to be a property of the ledger, not of the call sequence. +// 3. Warnings are emitted sorted by NEW name. The retired `tests/parity/harness.py` compared +// the two clients' stderr BYTE-FOR-BYTE, so "whatever order the lookups happened in" was +// not an option: the order has to be a property of the ledger, not of the call sequence. +// It still is, and `TestDeprecationsAreSortedByNewNameRegardlessOfInsertionOrder` pins it. // // 🔴 ONE CONSEQUENCE OF RULE 1 THAT IS NOT OBVIOUS, AND IS WHY NEITHER POD IMAGE SETS A // STORE VARIABLE AT ALL. An image's `ENV` and a Deployment's `env:` are not two sources: @@ -110,7 +113,7 @@ // decides between them — and the image half is a DEFAULT that is present whether or not the // manifest mentions it. An image setting `CAIRN_STORE_ROOT` would therefore outrank a // Deployment that explicitly sets `SUBSYSTEM_STORE_ROOT`, and for those variables the old -// name would stop working the day the image shipped rather than at P8. +// name would stop working the day the image shipped rather than at the announced removal. // // The images used to answer that by staying on `SUBSYSTEM_STORE_*`. They now answer it by // setting NEITHER spelling: the three values they baked were byte-identical to the code @@ -118,8 +121,8 @@ // lines per pod start that no manifest could clear — rule 2 sweeps the whole environment and // does not care who put a variable there. With no image default there is nothing to // outrank a manifest in either direction, which closes this consequence at the root rather -// than deferring it to P8. `flake.nix`'s `serverEnv`, `server/Dockerfile` and -// `tests/test_flake_image_matches_dockerfile.py` carry the measurement; this note exists so +// than deferring it. `flake.nix`'s `serverEnv` and `tests/test_server_deployment_defaults.py` +// carry the measurement; this note exists so // a reader who arrives at rule 1 first does not "restore" an image default here. // // 🔴 ONE BEHAVIOUR CHANGE, AND IT IS AN AUTHORISED EXCEPTION TO "DO NOT CHANGE THE @@ -185,8 +188,9 @@ var Ledger = []Pair{ } // RemovalAnchor is WHEN the old names stop being read, in the only terms this repo can -// state it: a milestone a reader can check, never a date. -const RemovalAnchor = "the Python client (packages.cairn) is retired" +// state it: a milestone a reader can check, never a date. (It read "the Python client +// (packages.cairn) is retired" until that happened; see the package doc.) +const RemovalAnchor = "a release whose CHANGELOG.md entry announces their removal" // envWarningFormat and fileWarningFormat are the two pinned warning texts. // @@ -219,9 +223,9 @@ const RemovalAnchor = "the Python client (packages.cairn) is retired" // double the ways the two spellings can drift. // // 🔴 `tests/test_env_aliases.py` EXTRACTS THESE TWO CONSTANTS FROM THIS FILE BY TEXT and -// compares the rendered result against `lib/env_aliases.py`'s. Editing one of them alone -// is a red test, which is the whole reason they are named constants rather than inline -// format strings at the two call sites below. +// compares the rendered result against WHOLE LITERAL SENTENCES. Editing one is a red test, +// which is the point: they are printed to operators. (Until the Python client was retired +// the comparison was against `lib/env_aliases.py`'s rendering instead.) const ( envWarningFormat = "$%s is a deprecated alias for $%s. Where both are set in the " + "environment, $%s is the one that is read. Both are accepted until " + RemovalAnchor + "." @@ -264,9 +268,8 @@ var news = func() map[string]string { // down. See the seam paragraph in the package doc for why that package keeps its own // predicate rather than taking this one's. // -// `lib/env_aliases.py`'s `old_name` was public throughout: Python has no unexport, and the -// cross-language gate pins the LEDGER, the anchor and the warning text, not the function -// set, so the two spellings never had to match here. +// (The retired Python twin's `old_name` was public too; the gate that pinned the two +// spellings compared the LEDGER, the anchor and the warning text, not the function set.) func OldName(newName string) string { return news[newName] } // Value is the resolved value of `newName` over `env`: the new name if it is present and @@ -286,8 +289,9 @@ func Value(env map[string]string, newName string) string { // resolves its config path through an injectable `func(string) string`, not a map, and the // first cut of this package offered only the map form — so that call site kept a plain // single-name lookup, the routing layer stopped seeing `SUBSYSTEM_STORE_CONFIG`, and a -// two-instance world silently collapsed to one. `tests/parity/harness.py` is what caught it, -// by diffing the two clients' bytes; nothing in the Go tree noticed. The remedy is the one +// two-instance world silently collapsed to one. `tests/parity/harness.py` (retired with the +// Python oracle) is what caught it, by diffing the two clients' bytes; nothing in the Go tree +// noticed. The remedy is the one // the rules name: not a second patch, but one predicate every shape delegates to. func ValueFrom(get func(string) string, newName string) string { if v := get(newName); !blank(v) { @@ -305,8 +309,8 @@ func ValueFrom(get func(string) string, newName string) string { // spellings. // // 🔴 IT IS A NAMED FUNCTION BECAUSE THE TWO HALVES OF THE RULE DISAGREED WHILE BOTH WERE -// SPELLED INLINE, AND THE DISAGREEMENT WAS INVISIBLE TO THE PARITY GATE BECAUSE -// `lib/env_aliases.py` HAD THE SAME ONE. `Deprecations` tested `TrimSpace(env[old]) != ""`; +// SPELLED INLINE, AND THE DISAGREEMENT WAS INVISIBLE TO THE (since retired) PARITY GATE +// BECAUSE THE PYTHON TWIN HAD THE SAME ONE. `Deprecations` tested `TrimSpace(env[old]) != ""`; // `ValueFrom` returned the old name's value raw. So `SUBSYSTEM_STORE_ROOT=" "` resolved to // `" "` — a pod would have taken a whitespace store root — and warned about nothing, while // the package doc said a blank value "changes no resolution, so it is not a deprecation". diff --git a/internal/envalias/envalias_test.go b/internal/envalias/envalias_test.go index e172168c..063f9b76 100644 --- a/internal/envalias/envalias_test.go +++ b/internal/envalias/envalias_test.go @@ -20,12 +20,11 @@ import ( // once-per-process rule — each of which is a property the parity harness can only observe // as "the bytes differed", after the fact and without saying which rule broke. // -// The behavioural claim — that the two languages emit the SAME BYTES in the SAME ORDER — -// is NOT made here and cannot be. `tests/test_env_aliases.py` pins the ledger and the -// warning TEXT across the two spellings; `tests/parity/harness.py` runs both real clients -// with a deprecated name exported and diffs their stderr byte-for-byte, which is the only -// instrument that can see a Go-side argument-ORDER mistake that still renders well-formed -// English. +// `tests/test_env_aliases.py` pins the ledger and the warning TEMPLATES against literals, +// reading this package as text. A Go-side argument-ORDER mistake that still renders +// well-formed English is invisible to a template read — it was caught by the retired parity +// harness diffing two real clients' stderr — so `TestTheRenderedWarningsAreTheWholeSentence` +// pins the RENDERED sentence for one pair, which is what an operator reads. func TestTheLedgerIsSortedByNewName(t *testing.T) { // 🔴 NOT COSMETIC. `Deprecations` sorts by new name so that two clients emitting the @@ -475,3 +474,21 @@ func TestTheScanIgnoresANestedCheckoutOfThisRepository(t *testing.T) { "a fact about the scan rather than about the tree.", old, len(offenders), offenders) } } + +func TestTheRenderedWarningsAreTheWholeSentence(t *testing.T) { + // 🔴 THE WHOLE NORMALISED STRING, NOT KEYWORDS: a guard on words is walkable by rewording, + // and an argument-order swap (`New, Old, Old`) renders well-formed English that a keyword + // guard and a template read both pass. The pair's two names are distinct, so every swap + // moves the sentence. + p := Pair{New: "CAIRN_URL", Old: "SUBSYSTEM_STORE_URL"} + if got, want := EnvWarning(p), "$SUBSYSTEM_STORE_URL is a deprecated alias for $CAIRN_URL. "+ + "Where both are set in the environment, $CAIRN_URL is the one that is read. Both are "+ + "accepted until a release whose CHANGELOG.md entry announces their removal."; got != want { + t.Fatalf("EnvWarning:\n got %q\nwant %q", got, want) + } + if got, want := FileWarning(p, "/x/config"), "SUBSYSTEM_STORE_URL in /x/config is a deprecated "+ + "alias for CAIRN_URL. Where both appear in that file, CAIRN_URL is the one that is read. "+ + "Both are accepted until a release whose CHANGELOG.md entry announces their removal."; got != want { + t.Fatalf("FileWarning:\n got %q\nwant %q", got, want) + } +} diff --git a/internal/identity/README.md b/internal/identity/README.md index 749ea4bc..af198fe4 100644 --- a/internal/identity/README.md +++ b/internal/identity/README.md @@ -291,9 +291,10 @@ name that was never implemented. 🔴 **THE RENAME GOES THROUGH `internal/envalias` AND NOWHERE ELSE**, so there is exactly one definition of "which spelling is read" — `written` in `config.go`. The deprecation window -closes at the ledger's single `RemovalAnchor`, which is `packages.cairn`'s retirement (P8); -that is a wider promise than these pairs need and is not a claim that the Python client -reads them. The one place this package's resolver and `envalias.Value` deliberately part is +closes at the ledger's single `RemovalAnchor`. That anchor was `packages.cairn`'s retirement +(P8) — a wider promise than these pairs needed, and never a claim that the Python client read +them; P8 has happened, the aliases were deliberately kept, and the anchor is now a release +whose `CHANGELOG.md` entry announces their removal (`internal/envalias`'s package doc). The one place this package's resolver and `envalias.Value` deliberately part is a **whitespace-only** current name, which is refused here rather than falling through to the deprecated spelling — see `written`'s comment, and `oidcrename_test.go`. @@ -720,8 +721,8 @@ callback deliberately does not count; its listeners (`internal/clientapi`, A request whose bearer token's signature verified — authenticated, or `claims-refused` — gets two fields **appended after `status=`**: `sub=` and `jti=` from the signed token (`-` when absent; a non-string `jti` reads as absent rather than refusing the token, since it was -ignored before). Every other line is byte-identical to before, which is what keeps -`tests/dualrun/`'s line-for-line comparison with the oracle unmoved. Values pass through +ignored before). Every other line is byte-identical to before, which is what kept the +retired `tests/dualrun/`'s line-for-line comparison with the oracle unmoved. Values pass through `auditField` (a space becomes `_`, a control character `?`), so a value cannot forge a field or a line. @@ -759,11 +760,11 @@ Pinned by `jwksrun_test.go`, which records the waits `Run` asks for rather than ⚠ **"REPORTABLE" IS THE WORD IT EARNS, NOT "REPORTED".** No deployed program prints `KeySetStatus`, for the same reason nothing prints `control.Staleness`: the one place to -put it is `cmd/cairn-server`'s startup banner, which `tests/dualrun/harness.py` compares -between the two servers, so a Go-only field there moves a gate. **CLOSING CONDITION:** the -same one `internal/control/README.md` states — a render (a `doctor` section, a status -route, or a banner field declared in `wire.NORMALIZATIONS`) that a `tests/dualrun/` run -exits 0 with. +put it is `cmd/cairn-server`'s startup banner, which the retired `tests/dualrun/harness.py` +compared between the two servers, so a Go-only field there would have moved a gate. That gate +went with the Python oracle; the render is simply unbuilt. **CLOSING CONDITION:** the same +one `internal/control/README.md` states — a render (a `doctor` section, a status route, or a +banner field) an operator can read. ### A key set from a file: the issuer leaves the startup path diff --git a/internal/identity/config_test.go b/internal/identity/config_test.go index a292c4c3..3aed7da4 100644 --- a/internal/identity/config_test.go +++ b/internal/identity/config_test.go @@ -1278,9 +1278,9 @@ func packageSourceFiles(t *testing.T) map[string]*ast.File { // TEST ABOVE CAN FAIL WHEN THE SET *GROWS*. A hand-written list is written by whoever // adds the constant, in the same edit, so it moves with the thing it is supposed to // pin — and the comparison is then between two copies of one decision. This repository -// already answers that shape the same way twice: `tests/test_cairn_doctor.py` walks the -// `cairn` script's AST for its exit codes, and `capability_ledger.cli_verbs_from_parser` -// asks argparse rather than restating the verbs. +// answered that shape the same way twice while the Python client lived: the retired +// `tests/test_cairn_doctor.py` walked the `cairn` script's AST for its exit codes, and +// `capability_ledger.cli_verbs_from_parser` asked argparse rather than restating the verbs. // // 🔴 `const` AND `var` BOTH, AND THE `var` HALF WAS THE SKIP THIS FUNCTION'S OWN SENTENCE // SAYS IT REFUSES. The walk filtered on `token.CONST`, so `var EnvSupabaseNonceZL = "…"` diff --git a/internal/identity/identity.go b/internal/identity/identity.go index 8e5a5bcf..4a84b000 100644 --- a/internal/identity/identity.go +++ b/internal/identity/identity.go @@ -175,13 +175,15 @@ type Authenticator interface { // earlier check rejects. // // ⚠ THE REASON IS NOT IN THE AUDIT LINE TODAY, AND SAYING SO IS THE POINT RATHER THAN -// LEAVING IT TO BE INFERRED. `tests/dualrun/harness.py` compares the two servers' audit -// records line for line, so a Go-only `status=` vocabulary item would move a gate in the -// same change that most needs it — the same reason `control.Cache.Staleness()` is +// LEAVING IT TO BE INFERRED. The retired `tests/dualrun/harness.py` compared the two servers' +// audit records line for line, so a Go-only `status=` vocabulary item would have moved a gate +// in the same change that most needed it — the same reason `control.Cache.Staleness()` is // reportable and unreported. **CLOSING CONDITION:** a `status=` spelling declared in // `wire.NORMALIZATIONS` that a `tests/dualrun/` run exits 0 with, or the retirement of -// the oracle that makes the comparison moot. Until then the reason is observable at this -// package's boundary and nowhere else, which is where its tests read it. +// the oracle that makes the comparison moot. ✅ The second arm is MET — the oracle and that +// gate are deleted — so nothing now blocks the field; it is unbuilt, and until it is built +// the reason is observable at this package's boundary and nowhere else, which is where its +// tests read it. type Refusal struct { // Backend names which authenticator refused. Never rendered to a caller. Backend string diff --git a/internal/identity/jwks.go b/internal/identity/jwks.go index c74b8fcd..745d21af 100644 --- a/internal/identity/jwks.go +++ b/internal/identity/jwks.go @@ -39,12 +39,12 @@ import ( // // ⚠ AND "REPORTABLE" IS THE WORD IT EARNS TODAY, EXACTLY AS `control.Cache.Staleness` // DOES. `Status()` is a value with a `String()`; no deployed program prints it, because -// the one place to print it is `cmd/cairn-server`'s startup banner, which -// `tests/dualrun/harness.py` compares between the two servers — so a Go-only field -// there would move a gate. **CLOSING CONDITION:** the same one `internal/control`'s -// README states for `Staleness` — a render (a `doctor` section, a status route, or a -// banner field declared in `wire.NORMALIZATIONS`) that a `tests/dualrun/` run exits 0 -// with. +// the one place to print it is `cmd/cairn-server`'s startup banner, which the retired +// `tests/dualrun/harness.py` compared between the two servers — so a Go-only field +// there would have moved a gate. That gate is gone with the Python oracle, so the reason +// is too; the render is simply unbuilt. **CLOSING CONDITION:** the same one +// `internal/control`'s README states for `Staleness` — a render (a `doctor` section, a +// status route, or a banner field) an operator can read. // // ⚠ WHAT A ROTATION COSTS IN THE OTHER DIRECTION IS SMALLER AND IS NOT THE SAME // PROBLEM. A key ADDED at the provider is unknown here until the next refresh, so diff --git a/internal/identity/oidcrename_test.go b/internal/identity/oidcrename_test.go index 07229065..664cc8fb 100644 --- a/internal/identity/oidcrename_test.go +++ b/internal/identity/oidcrename_test.go @@ -433,8 +433,8 @@ func TestADeprecatedVerifierNameWarnsNamingItsReplacement(t *testing.T) { if len(lines) != len(want) { t.Fatalf("got %d warning lines, want %d: %v", len(lines), len(want), lines) } - // Sorted by NEW name — ISSUER before JWKS_URL — which is the order `tests/parity/` - // diffs the two clients' stderr in. + // Sorted by NEW name — ISSUER before JWKS_URL — which is the order the retired + // `tests/parity/` gate diffed the two clients' stderr in. for i := range want { if lines[i] != want[i] { t.Errorf("line %d is %q, want %q", i, lines[i], want[i]) diff --git a/internal/pgstore/harness_pgtest_test.go b/internal/pgstore/harness_pgtest_test.go index 78a1c8c0..d13ac0cb 100644 --- a/internal/pgstore/harness_pgtest_test.go +++ b/internal/pgstore/harness_pgtest_test.go @@ -20,8 +20,8 @@ // nix derivations run in `doCheck`, in a sandbox that structurally cannot have a // database — compiles and passes without ever pretending to have measured SQL; // - WITH the tag and no DSN, [requireDSN] calls `t.Fatal`. Not a skip. The tier -// refuses to vouch, in the same words and for the same reason `tests/parity/`'s -// pre-flight does: "could not vouch" is a distinct outcome from "passed", and a +// refuses to vouch, in the same words and for the same reason the retired +// `tests/parity/` pre-flight did: "could not vouch" is a distinct outcome from "passed", and a // tier that cannot tell them apart is reporting the wrong one. // // ⚠ A BUILD TAG MOVES THE HAZARD RATHER THAN CLOSING IT, AND THAT IS SAID HERE RATHER @@ -63,7 +63,7 @@ const DSNEnv = "CAIRN_PGTEST_DSN" // refusal is what this tier says when it cannot measure anything. // -// 🔴 THE WORDING IS DELIBERATE AND MATCHES `tests/parity/harness.py`. "Could not vouch" +// 🔴 THE WORDING IS DELIBERATE AND MATCHED THE RETIRED `tests/parity/harness.py`. "Could not vouch" // is a third outcome beside pass and fail, and a reader who sees "FAILED" here would // reasonably go looking for a defect in the SQL. There is none; there is no database. const refusal = `REFUSING TO VOUCH: the Postgres tier ran with no database. diff --git a/internal/pytext/decodereplace_test.go b/internal/pytext/decodereplace_test.go index 0b1584ba..6cd2c316 100644 --- a/internal/pytext/decodereplace_test.go +++ b/internal/pytext/decodereplace_test.go @@ -30,8 +30,8 @@ import ( // // ⚠ WHAT IT CANNOT SEE. The fixture is a digest plus a named table, so it speaks // for the enumeration in `tests/pytext_decode_replace.py` and nothing else: no -// CALLER is exercised here, and no rendered byte. `internal/store`'s own tests and -// `tests/parity/harness.py` are what read this function through a caller. +// CALLER is exercised here, and no rendered byte. `internal/store`'s own tests are what +// read this function through a caller (the retired `tests/parity/harness.py` did too). type decodeReplaceCase struct { Name string `json:"name"` diff --git a/internal/pytext/pytext.go b/internal/pytext/pytext.go index 0923b646..93d033de 100644 --- a/internal/pytext/pytext.go +++ b/internal/pytext/pytext.go @@ -2,7 +2,7 @@ // writer depend on for BYTE-IDENTICAL behaviour, spelled once. // // 🔴 THESE ARE NOT CONVENIENCE HELPERS — EACH IS A CONTRACT THE GOLDENS PIN. -// `server/server.py` and the reader beside it make load-bearing decisions from +// The retired `server/server.py` and the reader beside it made load-bearing decisions from // `str.splitlines()` and `str.split()`: // // - `_bullet_request_problem` refuses a bullet whose text becomes more than @@ -58,7 +58,7 @@ const ( // LineBreaks is every character `str.splitlines()` treats as a line boundary: // seven C0 controls, the C1 NEL, and the two Unicode separators. It is the Go -// spelling of `server.py`'s `LINE_BREAK_CHARS`, and `TestLineBreaksIsTen` pins +// spelling of the retired `server.py`'s `LINE_BREAK_CHARS`, and `TestLineBreaksIsTen` pins // the count so a dropped entry cannot pass for the whole set. // // 🔴 TEN, NOT TWO. The Python validator this mirrors used to read diff --git a/internal/report/citationtoken_test.go b/internal/report/citationtoken_test.go index 12bd761d..245a62f5 100644 --- a/internal/report/citationtoken_test.go +++ b/internal/report/citationtoken_test.go @@ -128,9 +128,9 @@ func sectionBodies(rendered string) map[string][]string { // or one that annotated the wrong bullet, satisfies "the line ends in ` [cb:`" perfectly. // The expected id is taken from `store.ParseJournalBullets` over the same section body — // which is the derivation under test, so this is a POSITION claim rather than a hash claim; -// what pins the hash itself is `internal/store/citationid_test.go` against the PYTHON -// answers, and what pins the two renderers against each other is `reader_fixtures.json` and -// `tests/parity/`. +// what pins the hash itself is `internal/store/citationid_test.go` against the frozen PYTHON +// answers, and what pins the rendered bytes is the frozen `reader_fixtures.json` (the retired +// `tests/parity/` also compared the two renderers, until the oracle was deleted). // // 🔴 AND IT ASSERTS THE NEGATIVE HALF IN THE SAME PASS: a line that opens no bullet carries // no token. Without that, a renderer appending a token to EVERY line passes the positive diff --git a/internal/report/entry.go b/internal/report/entry.go index 22d7299c..0591ff8d 100644 --- a/internal/report/entry.go +++ b/internal/report/entry.go @@ -94,10 +94,9 @@ type RecalledEntry struct { // `refs: ` (see [RecallReport.RenderText]); both re-based the goldens, the reader // fixture and the parity byte diffs, the second on an operator ruling. So what is // deferred here needs no ruling and risks no rendered byte — it is a three-file - // mechanical edit (`store.Entry.Tasks`, this field, the oracle's - // `RecalledEntry.tasks`), worth doing when something else is already touching all - // three. ⚠ The oracle's JSON payload key `"tasks"` is a SEPARATE object with its own - // closing condition (P8), stated at the key itself; it is not this deferral. + // mechanical edit (`store.Entry.Tasks` and this field), worth doing when something + // else is already touching both. (The retired Python oracle's JSON payload key + // `"tasks"` went with it; the Go client's `--json` document spells the field `refs`.) Tasks []string // RequirementsOpen and RequirementsMet are the `## Requirements` bullets that DECLARE diff --git a/internal/report/reader_fixtures_test.go b/internal/report/reader_fixtures_test.go index d5983c26..600bc3dd 100644 --- a/internal/report/reader_fixtures_test.go +++ b/internal/report/reader_fixtures_test.go @@ -21,9 +21,16 @@ import ( // term, a `--max-hits` truncation, a malformed entry BESIDE readable ones, or a // `search-unreadable` scope. Every one is a branch here. // -// So the expectations are the ORACLE's own rendered bytes, generated by -// `tests/reader_fixtures.py` and replayed against this port. A hand-written expectation -// would assert what somebody believed the oracle does; these assert what it did. +// So the expectations are the ORACLE's own rendered bytes, recorded by the retired Python +// reader and replayed against this port. A hand-written expectation would assert what +// somebody believed the oracle does; these assert what it did. +// +// 🔴 THE FIXTURE IS NOW A FROZEN CONTRACT. The oracle was deleted, so nothing can regenerate +// `testdata/reader_fixtures.json`; it is frozen as recorded at +// ec1b756b15ea37469124c635d0d82f6e10d57899, the last commit that had the oracle — the same +// rule as `tests/conformance/README.md`'s frozen corpus. A renderer change that moves an +// expectation is a CONTRACT change, argued in review; never re-record it from this renderer, +// which would make the test agree with itself. // // 🔴 THE TWO THINGS THAT CANNOT BE COMPARED LITERALLY ARE PINNED RATHER THAN IGNORED. The // store path differs per run, so both sides substitute a placeholder for it; the host @@ -31,10 +38,10 @@ import ( // sides are handed the same synthetic literal. Nothing else is normalized — no header set, // no "ignore whitespace", no per-case exemptions. // -// ⚠ AND THE FIXTURE CANNOT GO STALE UNNOTICED: `tests/test_reader_fixtures.py` regenerates -// it and diffs against what is committed, so a reader change that moves the oracle's bytes -// fails there rather than leaving this test comparing against a snapshot of an older -// implementation. +// ⚠ IT CAN NO LONGER GO STALE IN THE OLD SENSE: there is no oracle left to drift from. Until +// the retirement, `tests/test_reader_fixtures.py` regenerated it from the oracle and diffed; +// that test now pins only that the committed file is the frozen one, and that its world is +// synthetic. type fixtureFile struct { Host string `json:"host"` diff --git a/internal/report/recall.go b/internal/report/recall.go index 19f556f1..57c531f6 100644 --- a/internal/report/recall.go +++ b/internal/report/recall.go @@ -348,15 +348,15 @@ func Recall(storeRoot string, opts RecallOptions, visible store.ScopeSet) (Recal // // ⚠ THAT RULE BINDS THE `ref-to-absent` BRANCHES TOO, AND THE ORACLE DISAGREED AT ONE OF // THEM. `lib/subsystem_recall.py` passed the SCOPE total on the membership-test branch - // below while this side passed the narrowed count. The oracle now matches this side, - // which is the one the rule names. + // below while this side passed the narrowed count. The oracle came to match this side, + // which is the one the rule names, before it was retired. // // ⚠ AND NO CONSUMER COULD HAVE OBSERVED IT — FIXED BEFORE IT HAD ONE, WHICH IS A NARROWER // CLAIM THAN THE DRAFT MADE. That draft called it a LIVE divergence on the grounds that // `report_json` serialises the field, and that does not follow: there is no Go JSON - // payload for a recall report at all, and the oracle's `report_json` has no caller outside - // `tests/` — `lib/subsystem_recall.py`'s own `--json` entrypoint passes no `ref_to`, so it - // cannot reach this branch, and `cairn` renders text. Nothing renders `TotalInScope` here + // payload for a recall report at all, and the oracle's `report_json` had no caller outside + // `tests/` — `lib/subsystem_recall.py`'s own `--json` entrypoint passed no `ref_to`, so it + // could not reach this branch, and `cairn` rendered text. Nothing renders `TotalInScope` here // either, so no byte-diff gate could see it. Worth keeping the two sides agreed on a // field's MEANING; not worth reading as a shipped defect. scopeTotal := len(entries) diff --git a/internal/report/refsbadge_test.go b/internal/report/refsbadge_test.go index 16882dc5..2949381e 100644 --- a/internal/report/refsbadge_test.go +++ b/internal/report/refsbadge_test.go @@ -19,8 +19,8 @@ import ( // NEITHER PINS THE PAIR. `internal/report/testdata/reader_fixtures.json` carries a 2-ref // entry, so a mutant that dropped `plural(...)` dies there; nothing in that fixture carries // ONE ref, so a mutant that hardcoded `"refs"` — always plural — survives it. The corpus -// and `tests/parity/` each reach the singular through a live store, which makes them the -// reachability proof; this test is what makes the PAIR readable in one place. +// reaches the singular through a live store (as the retired `tests/parity/` also did), which +// makes it the reachability proof; this test is what makes the PAIR readable in one place. // // 🔴 IT PINS THE WHOLE NORMALISED LINE, NOT A SUBSTRING, AND THE DIFFERENCE IS MEASURED // RATHER THAN STYLISTIC. The first version asserted `strings.Contains(line, "🔗 1 ref")` and diff --git a/internal/report/refto_clause_test.go b/internal/report/refto_clause_test.go index ff2c78c6..9e0b9aa6 100644 --- a/internal/report/refto_clause_test.go +++ b/internal/report/refto_clause_test.go @@ -61,8 +61,9 @@ func refToClauseWorld(t *testing.T) string { // The three WHOLE ref-to lines this fixture can produce, spelled out rather than rebuilt from // the renderer's own pieces: a contract test's expectation may not be derived from the // implementation it tests, and a guard on the clause's KEYWORDS is walkable by rewording the -// sentence around them. These bytes are also what `tests/parity/` and `tests/conformance/` -// compare against the oracle's. +// sentence around them. These bytes are also what `tests/conformance/` compares against the +// frozen oracle-recorded goldens (and what the retired `tests/parity/` compared against the +// oracle's live output). const ( clauseLineReports = " ref-to: `" + sharedRef + "` — 1 of 4 entries in `refto-clause/` " + "reference it, and everything below is about those 1. This is a NARROWING, not a " + diff --git a/internal/report/refto_test.go b/internal/report/refto_test.go index a653b69f..e7d10618 100644 --- a/internal/report/refto_test.go +++ b/internal/report/refto_test.go @@ -313,7 +313,8 @@ func TestRefToComposesWithRef(t *testing.T) { // printed "0 of 2 entries in `alpha-notes/` reference it" and "NO ENTRY REFERENCES …", // which is a claim about the STORE and it was wrong. Asserted as whole substrings rather // than by keyword: a guard on words is walkable by rewording, and these bytes are compared - // against the oracle's by `tests/parity/` and `tests/conformance/`. + // against the frozen oracle-recorded goldens by `tests/conformance/` (and were compared + // against the live oracle by the retired `tests/parity/`). // // 🔴 RED/GREEN MATRIX, MEASURED RATHER THAN CLAIMED: at `f806d6c1` (the pre-fix head) this // block fails on BOTH assertions — `RefToMatched()` short-circuited to 0 on this status, diff --git a/internal/report/searchtext.go b/internal/report/searchtext.go index 9912a9a0..c9bc3147 100644 --- a/internal/report/searchtext.go +++ b/internal/report/searchtext.go @@ -51,8 +51,8 @@ func (r SearchReport) RenderText(host string, extraHeader []string, instance str // sits above exactly three statuses — `scope-absent` returns before the operand is // parsed, so it never carries one — and `search-no-match` has THREE distinguishable // bodies, which makes FIVE cases. ⚠ IT SAID "two bodies / FOUR cases" AND THAT WAS - // MEASURED INCOMPLETE: `N == 0` is TWO bodies, not one, and the second is live in this - // change's own `tests/dualrun/` gate. The paragraph below says a new body must be added + // MEASURED INCOMPLETE: `N == 0` is TWO bodies, not one, and the second was live in that + // change's own `tests/dualrun/` gate (since retired with the Python oracle). The paragraph below says a new body must be added // to this list and checked BY HAND — so an incomplete list returns a false clean, which // is why the fourth row exists rather than being folded into the third. Each was // re-derived rather than covered by an absolute: diff --git a/internal/report/sources.go b/internal/report/sources.go index 934e68a4..45eb2994 100644 --- a/internal/report/sources.go +++ b/internal/report/sources.go @@ -12,8 +12,9 @@ import ( // RENDERER (`claudedocs/plan-cairn-scope-refs.md`, decision 10). The pod renders it through // `Reader`; nothing else renders a declaration, so there is no second rendering to drift. // -// 🔴 GO-ONLY BY DECISION (the arcs precedent): `server/server.py` does not serve it, the corpus rows -// addressing it are `go_only` CHANGE DETECTORS recorded from `cmd/cairn-server`, and the contract +// 🔴 GO-ONLY BY DECISION (the arcs precedent): the retired `server/server.py` never served it, the +// corpus rows addressing it are CHANGE DETECTORS recorded from `cmd/cairn-server` (once marked +// Go-only; the mark was folded away with the oracle), and the contract // witnesses are the literal bodies in `internal/api`'s sources tests — which also pin the two // states the one-boot corpus cannot send (unconfigured, and the 503 for an unreadable journal). // diff --git a/internal/report/tagfilter_test.go b/internal/report/tagfilter_test.go index 06487d2d..be9a1f80 100644 --- a/internal/report/tagfilter_test.go +++ b/internal/report/tagfilter_test.go @@ -571,8 +571,8 @@ func TestAMalformedTagIsRefusedByTheOptionLadder(t *testing.T) { // falsified BOTH: the numerator became the entries that reference the ref AND carry the tag, and // the denominator lost every entry the tag filter removed. That is the same class of defect as // the `search-unreadable` term one file over, in PROSE rather than in a status, and it would have -// been invisible to `tests/parity/` and `tests/conformance/` because both implementations would -// have derived it identically. +// been invisible to `tests/parity/` (since retired) and `tests/conformance/` because both +// implementations would have derived it identically. // // 🔴 AND THE REACH CLAUSE IS THE THIRD HALF. "Everything below is about those N" is false when a // further filter removes some of the N, so `reachClause` grew a third state rather than being diff --git a/internal/report/testdata/reader_fixtures.json b/internal/report/testdata/reader_fixtures.json index 9f982d7e..f97f7d2f 100644 --- a/internal/report/testdata/reader_fixtures.json +++ b/internal/report/testdata/reader_fixtures.json @@ -1,15 +1,14 @@ { "_comment": [ - "GENERATED BY tests/reader_fixtures.py -- DO NOT EDIT.", + "FROZEN CONTRACT -- DO NOT EDIT. Recorded by the retired Python oracle's reader, frozen", + "at ec1b756b15ea37469124c635d0d82f6e10d57899 (the last commit that had the oracle).", "", - "Every `expect` below is the ORACLE's own rendered bytes, so the Go test that", - "replays this file is a DIFFERENTIAL measurement against the implementation it", - "is a port of. The shapes here are the ones the HTTP conformance corpus cannot", - "send; see the module docstring for the list.", - "", - "Regenerate with `python3 tests/reader_fixtures.py generate`.", - "`tests/test_reader_fixtures.py` regenerates and diffs, so a stale fixture is a", - "test failure rather than a silently weaker comparison." + "Every `expect` below is the ORACLE's own rendered bytes over the synthetic world in", + "`scopes`/`entries`, so the Go test that replays this file measures the renderer", + "against the implementation it was ported from. The shapes here are the ones the HTTP", + "conformance corpus cannot send. Nothing can regenerate them now; a renderer change", + "that moves one is a contract change, argued in review, never a regeneration.", + "`tests/reader_fixtures.py build-store` materialises the world for uiaudit." ], "host": "fixture-host-000000000000", "store_placeholder": "", diff --git a/internal/report/text.go b/internal/report/text.go index c479c255..094b39c7 100644 --- a/internal/report/text.go +++ b/internal/report/text.go @@ -34,26 +34,29 @@ import ( // and rejected: 11.2% of rows, and it admits a 12.9 KB entry, which is not a tax anyone // needs warning about. // -// 🔴 IT IS DUPLICATED IN `lib/subsystem_recall.py` AS `NUANCE_BULLET_CEILING` BECAUSE -// `packages.cairn` CANNOT IMPORT `internal/` — the same packaging constraint `internal/envalias` -// lives under — and the two are pinned against each other by -// `tests/test_nuance_bullet_ceiling.py`. Two renderers that disagree about this number print -// different bytes for one entry, which is exactly the silent drift `tests/parity/` exists to -// catch; move both or neither. +// 🔴 IT WAS DUPLICATED IN `lib/subsystem_recall.py` AS `NUANCE_BULLET_CEILING` BECAUSE +// `packages.cairn` COULD NOT IMPORT `internal/` — the same packaging constraint `internal/envalias` +// lived under — and `tests/test_nuance_bullet_ceiling.py` pinned the two against each other: two +// renderers that disagree about this number print different bytes for one entry, which is the +// silent drift `tests/parity/` existed to catch. The Python client is retired, so this is the +// only spelling, and that test now pins it (and the badge) against literals. // // ⚠ IT IS ADVISORY AND IT IS NOT A GATE. Nothing refuses and nothing exits non-zero. It -// SURFACES the free variable `lib/entry_shape.py`'s `BULLET_TEXT_MAX` comment names; it does -// not BOUND it, and that comment is the one place the still-open read-budget question lives. +// SURFACES the free variable `lib/entry_shape.py`'s `BULLET_TEXT_MAX` comment named; it does +// not BOUND it. That comment was the one place the still-open read-budget question lived, and +// it is deleted with the Python oracle (read it at `ec1b756`); nothing in this tree restates it. // -// 🔴 TWO GATES ARE STRUCTURALLY BLIND TO THIS BADGE, AND BOTH ARE RUN AS ITS VALIDATION, SO -// NEITHER'S GREEN IS EVIDENCE ABOUT IT. Measured: `tests/conformance/`'s world tops out -// around ONE nuance bullet and `tests/dualrun/`'s generated world at FIVE, against a ceiling -// of 30 — so every row in both renders on the SILENT side and the branch is never evaluated. -// What DOES measure it: `internal/report`'s fixture replay (both sides of the boundary, in -// bytes) and `tests/parity/` (both real clients, with a desync control proven to go RED). -// Neither blind gate is seeded, deliberately: both compare implementations that reach this -// badge through the SAME `listing_line`/`listingLine` pair parity already compares, so a row -// in either would be a second sample of one unknown rather than a new claim. +// 🔴 TWO GATES WERE STRUCTURALLY BLIND TO THIS BADGE WHILE BOTH RAN AS ITS VALIDATION, SO +// NEITHER'S GREEN WAS EVIDENCE ABOUT IT. Measured: `tests/conformance/`'s world tops out +// around ONE nuance bullet and the retired `tests/dualrun/`'s generated world at FIVE, against +// a ceiling of 30 — so every row in both rendered on the SILENT side and the branch was never +// evaluated. What DOES measure it: `internal/report`'s fixture replay (both sides of the +// boundary, in bytes); `tests/parity/` (both real clients, with a desync control proven to go +// RED) did too until it was deleted with the oracle. Neither blind gate was seeded, +// deliberately: both compared implementations that reached this badge through the SAME +// `listing_line`/`listingLine` pair parity already compared, so a row in either would have +// been a second sample of one unknown rather than a new claim. `tests/conformance/` is still +// unseeded, so it is still blind here. const NuanceBulletCeiling = 30 // listingLine is ONE index line: ` N nuance [ ]`. ~60 @@ -134,14 +137,11 @@ func listingLine(entry RecalledEntry, width int) string { // INPUT spellings (`tasks:`, `task:`) are untouched; this is the rendered word. // // ⚠ THE BODY LABEL SPELLS `refs:` TOO, so nothing on this surface spells `task` any - // more. Two things DO still read `task`, and they are different from each other and - // from this. (a) The internal FIELD NAME — `RecalledEntry.Tasks`, - // `store.Entry.Tasks`, the oracle's `RecalledEntry.tasks` — which no reader sees; - // its own note is on [RecalledEntry.Tasks]. (b) The oracle's JSON payload key - // `"tasks"` in `report_json`, which has NO Go counterpart — `internal/report` - // renders text only — so it is outside the byte-identity contract these two - // renderers share. Its reason and its CLOSING CONDITION (P8) are written once, at - // the key itself in `lib/subsystem_recall.py`. + // more. One thing DOES still read `task`: the internal FIELD NAME — + // `RecalledEntry.Tasks`, `store.Entry.Tasks` — which no reader sees; its own note is + // on [RecalledEntry.Tasks]. (The retired Python oracle's JSON payload key `"tasks"` + // was the other, and it went with that oracle; the Go client's `--json` document + // spells the field `refs`.) badges = append(badges, "🔗 "+strconv.Itoa(len(entry.Tasks))+" ref"+plural(len(entry.Tasks))) } // 🔴 THE SIXTH BADGE, AND THE ONLY ONE WHOSE SUBJECT IS THE ENTRY'S COST RATHER THAN ITS @@ -483,10 +483,10 @@ func (r RecallReport) RenderText(host string, extraHeader []string, instance str // arrived by another route can still carry anything. Both remaining typo routes are // named because a zero here is still what each of them looks like. // - // ⚠ BYTE-IDENTICAL WITH `lib/subsystem_recall.py`'s `tag-absent` branch, which is not - // a style request: `tests/parity/`'s `recall-tag-absent` row diffs the two clients' - // stdout, and `tests/conformance/golden/recall-tag-absent.json` pins the served bytes. - // Reword one side alone and both go red. + // ⚠ BYTE-IDENTICAL WITH THE RETIRED `lib/subsystem_recall.py`'s `tag-absent` branch, + // which is not a style request: `tests/conformance/golden/recall-tag-absent.json`, frozen + // from that oracle, pins the served bytes, and rewording this goes red there. (The + // retired `tests/parity/`'s `recall-tag-absent` row also diffed the two clients' stdout.) extra := "" if n := len(r.Malformed); n > 0 { extra = " ⚠ BUT " + strconv.Itoa(n) + " entry file" + plural(n) + " in this scope " + diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index e512d18b..7475b5c0 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -105,8 +105,8 @@ func EntryAction(kind store.Kind) (store.Action, bool) { // genuinely empty store, which says `newest=NONE entry-files=0`. An absent block would // read as "this is the source", which is the exact confusion the block removes. // headerSafe reports whether every character is PRINTABLE ASCII (0x20..0x7E) — what a -// header value can carry identically in any implementation. It is `server.py`'s -// `_header_safe`, and the two must stay in step. +// header value can carry identically in any implementation. It was the twin of the retired +// `server.py`'s `_header_safe`; with the oracle gone there is no second copy to keep in step. // // 🔴 THE BOUND IS THE HEADER, NOT THE FILESYSTEM, and it is deliberately NARROWER than // "encodable". U+0000..U+001F and U+007F frame-break or vanish; U+0080..U+00FF is the @@ -283,14 +283,14 @@ type Result struct { // // 🔴 UNCOMPRESSED, AND THAT IS THE WHOLE DESIGN RATHER THAN AN IMPLEMENTATION // DETAIL. Gzip byte-identity between this server and the oracle is UNATTAINABLE — -// measured, for two independent reasons, which is why `tests/dualrun/` compares the -// EXTRACTED tar and `wire.py` drops `Content-Length` on this route. A validator over +// measured, for two independent reasons, which is why the retired `tests/dualrun/` compared +// the EXTRACTED tar and `wire.py` drops `Content-Length` on this route. A validator over // the compressed bytes would therefore differ per implementation: two pods serving one // store would hand a client two different tags for the same content, every failover // would re-download, and the cross-implementation comparison this repository is built // on would have to grow a licence to differ for the one header whose entire job is to -// be equal. The uncompressed tar is compared byte-for-byte across both servers today, -// so a digest of it is equal by construction. +// be equal. The uncompressed tar was compared byte-for-byte across both servers while the +// oracle lived, so a digest of it was equal by construction. // // 🔴 IT IS A DIGEST OF THE CONTENT, NEVER OF A COUNTER. The obvious alternative — // key it on the caller's principal plus the authorization epoch — was MEASURED wrong diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index 01c34c4b..8a8da9cf 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -45,7 +45,7 @@ func TestFormatPyFloat(t *testing.T) { // side and diffing BYTES. // // Reproduced by building the reference with `tarfile` configured exactly as -// `server.py:_serve_snapshot` configures it — `format=tarfile.PAX_FORMAT`, and per member +// the retired `server.py:_serve_snapshot` configured it — `format=tarfile.PAX_FORMAT`, and per member // `info.mtime = st.st_mtime` as a FLOAT, `mode=0o644`, `uid=gid=0`, `uname=gname=""`, // `type=REGTYPE` — over a member list carrying all four divergence classes: a whole second, // a `.25`, a `.5` on an EVEN second, a `.5` on an ODD one, a `.75`, a non-ASCII name and a diff --git a/internal/store/citationid_test.go b/internal/store/citationid_test.go index 38a8bd54..216a693a 100644 --- a/internal/store/citationid_test.go +++ b/internal/store/citationid_test.go @@ -8,24 +8,21 @@ import ( "testing" ) -// The citation-id seam, replayed against the PYTHON implementation's answers. +// The citation id, replayed against a FROZEN CONTRACT. // -// WHAT IT MEASURES. `JournalBullet.CitationID` exists twice — here and in -// `lib/subsystem_resolver.py` — because `packages.cairn` installs the Python client and -// its `lib/` under `libexec` and nothing else, so `lib/` CANNOT import `internal/`. -// That is packaging, not a choice anyone may undo here, and it is the shape `AGENTS.md` -// already blesses for `server/Dockerfile` against `flake.nix`'s `serverEnv`. -// -// Two independent implementations of a hash must agree FOREVER or the id stops being a -// shared name for a bullet and silently becomes two. Nothing about that agreement is -// checked by a compiler, and it cannot be checked by reading either source: the only -// instrument is running both over the same bodies and comparing strings. -// -// 🔴 THE FIXTURE IS THE ORACLE'S OUTPUT, NOT A SNAPSHOT OF THIS PACKAGE. It records what -// CPython answers, so nothing here can agree with itself. `tests/citation_ids.py` writes -// it and `tests/test_citation_ids.py` REGENERATES it from the live Python -// implementation on every pytest run, so the fixture cannot drift away from the code it -// claims to record — the same two-sided arrangement `markersweep_test.go` uses. +// 🔴 OPTION (a) OF THE RETIREMENT LEDGER WAS TAKEN: KEEP THE FIXTURE, RELABEL IT. The fixture +// `testdata/citation_ids.json` was generated from the PYTHON implementation of `citation_id` +// (`lib/subsystem_resolver.py`, by `tests/citation_ids.py`) while that twin existed — the +// retired Python client could not import `internal/` — and this test was the differential +// that kept the two equal. The Python client and its generator are retired. The fixture is +// therefore NOT a snapshot of this package and NOT an oracle any more: it is a FROZEN +// CONTRACT, recorded by CPython and frozen at ec1b756b15ea37469124c635d0d82f6e10d57899 (the +// last commit that had the generator; the file was last regenerated at d7e1fec). Every id +// ever printed into a report (` [cb:]`) is a name an agent may hand back later; if the +// derivation moves, those names stop resolving, and this test is what makes that red. +// `tests/test_citation_ids.py` pins the fixture's bytes, so it cannot be "fixed" by +// regenerating it from this package — that would be (c), a self-snapshot, and was declined; +// (b), deleting it, was declined because then only a consumer printing an id would notice. // // 🔴 AND IT COMPARES THE DECODE, NOT ONLY THE HASH. Each case carries the entry BYTES as // hex beside their `errors="replace"` decode, and this side decodes the hex with @@ -35,15 +32,9 @@ import ( // CPython emits one per maximal SUBPART, so one entry file produced two citation ids. // // ⚠ WHAT IT CANNOT SEE. The bodies are hand-written, so this says nothing about the LIVE -// corpus, and nothing about RENDERING. ⚠ THE SECOND HALF OF THAT SENTENCE USED TO READ "no -// surface prints an id yet", AND THAT IS NO LONGER TRUE: both text renderers now append -// ` [cb:]` to every surfaced section line that opens a bullet, so a rendered byte -// depends on this function. What measures that is still not here — -// `internal/report/testdata/reader_fixtures.json` compares the two renderers' bytes (138 -// of its lines carry a token), `internal/report/citationtoken_test.go` pins the POSITION -// and the verbatim body, and `tests/parity/harness.py` compares the two real clients. Said -// here rather than left to be discovered, because a reader who took this file for full -// coverage would stop looking. +// corpus, and nothing about RENDERING: `internal/report/citationtoken_test.go` pins the +// POSITION and the verbatim body, and the frozen `internal/report/testdata/ +// reader_fixtures.json` holds rendered bytes carrying tokens. type citationCase struct { Name string `json:"name"` @@ -96,7 +87,7 @@ func loadCitationFixture(t *testing.T) citationFixture { return fx } -func TestTheCitationIDAgreesWithThePythonOracle(t *testing.T) { +func TestTheCitationIDAgreesWithTheFrozenPythonContract(t *testing.T) { fx := loadCitationFixture(t) compared := 0 decoded := 0 diff --git a/internal/store/journal.go b/internal/store/journal.go index 04ad0745..727ca246 100644 --- a/internal/store/journal.go +++ b/internal/store/journal.go @@ -198,15 +198,15 @@ type JournalBullet struct { // 🔴 IT IS NOW PRINTED, AND THE CLOSING CONDITION THAT SAID SO IS MET. This comment read // "NOT PRINTED BY ANY SURFACE AT THIS COMMIT" and named the condition that would retire // that sentence: an `internal/report/testdata/reader_fixtures.json` row carrying `[cb:`. -// There are such rows. BOTH text renderers append [CitationToken] to every surfaced -// section line that OPENS a bullet — `internal/report`'s `RecallReport.RenderText` and -// `lib/subsystem_recall.py`'s `render_text`, which is also the oracle pod's — so this +// There are such rows. The text renderer appends [CitationToken] to every surfaced +// section line that OPENS a bullet — `internal/report`'s `RecallReport.RenderText`, and +// until it was retired `lib/subsystem_recall.py`'s `render_text`, the oracle pod's — so this // method is on the read path of every recall and its guards are no longer contract pins -// over a dead payload. ⚠ WHAT IS STILL NOT PRINTED: the oracle's `--json` payload carries -// `sections` as RAW bodies and is deliberately unannotated, and no browser surface reads -// `StartLine`. (That cross-reference read "`report_json`'s own note" and pointed at -// nothing — the function carried no such note; it is now written at its `"sections"` key -// in `lib/subsystem_recall.py`.) +// over a dead payload. ⚠ WHAT IS STILL NOT PRINTED: no browser surface reads `StartLine` +// (and the oracle's `--json` payload carried `sections` as RAW bodies, deliberately +// unannotated). (That cross-reference read "`report_json`'s own note" and pointed at +// nothing — the function carried no such note; it was then written at its `"sections"` key +// in `lib/subsystem_recall.py`, deleted with the oracle — read it at `ec1b756`.) // // 🔴 DERIVED FROM THE BULLET'S OWN BYTES, WHICH IS WHAT MAKES CROSS-LANGUAGE AGREEMENT // REACHABLE RATHER THAN DISCIPLINED. `sha256` over `Text()` — `Lines` joined with "\n" @@ -226,9 +226,9 @@ type JournalBullet struct { // 2. THE DECODE FORM, which is a property of the CALLER rather than of this method. // `Lines` hold whatever string the loader produced, and `store.DecodeReplace` is // what the reader uses — so the id is a function of the entry's bytes AS A -// `replace` DECODE SEES THEM. `lib/subsystem_resolver.py` coerces to the same form -// before hashing (see `_citation_hash_bytes` there), which is what makes the pod's -// `surrogateescape` decode answer the same id. ⚠ A caller that parsed bullets out +// `replace` DECODE SEES THEM. The retired `lib/subsystem_resolver.py` coerced to the +// same form before hashing (`_citation_hash_bytes`; read it at `ec1b756`), which is what made +// the oracle pod's `surrogateescape` decode answer the same id. ⚠ A caller that parsed bullets out // of RAW file bytes would get a different id for a malformed entry; // `internal/write` does exactly that, and it is safe only because it never calls // this method — it hashes `BulletContent`, not a citation id. @@ -254,8 +254,8 @@ type JournalBullet struct { // the first bullet is `608a5be6`, and over `"- first\n- second\n"` — the same bullet // after the absorbed line leaves — it is `6b4d8edb`. `0aa5fc48`'s commit message // paired `6b4d8edb` with `ad08c42d`; that second value is RETRACTED as -// unreproducible, and the retraction and its sweeps are recorded once, beside -// `lib/subsystem_resolver.py`'s copy of this list. +// unreproducible, and the retraction and its sweeps were recorded once, beside +// `lib/subsystem_resolver.py`'s copy of this list (deleted with the oracle; read it at `ec1b756`). // // 🔴 AND THE ID IS **NOT SCOPED**. Two byte-identical bullets in different entries, or // in different scopes, get the SAME id, deterministically — `write.AppendBullet` dedupes @@ -277,8 +277,8 @@ type JournalBullet struct { // 0.1% corpus-wide. Do not shorten it to fit a column. ⚠ THE 3,129 IS A DIFFERENT // POPULATION FROM THE 110 THIS STRUCT'S OWN COMMENT COUNTS — three sizes are in play // across the two implementations and none is a re-measurement of another; the -// reconciliation is written out once, in `citation_id`'s docstring in -// `lib/subsystem_resolver.py`. +// reconciliation was written out once, in `citation_id`'s docstring in +// `lib/subsystem_resolver.py` (deleted with the oracle; read it at `ec1b756`). func (b JournalBullet) CitationID() string { // `Text()` rather than a second `strings.Join`: ONE definition of "the bullet's // bytes", which is the rule the Python twin's docstring already states. Two diff --git a/internal/store/load.go b/internal/store/load.go index ff894716..b99db418 100644 --- a/internal/store/load.go +++ b/internal/store/load.go @@ -358,7 +358,7 @@ const ScopePolicySheet = "README.md" // // There is no such function: the archive's member list is built INLINE inside // `internal/snapshot.Build`, whose per-scope name filter is `strings.HasSuffix(name, ".md") -// && !strings.HasPrefix(name, ".")`. The oracle's is `server.py`'s `_snapshot`, filtering +// && !strings.HasPrefix(name, ".")`. The oracle's was the retired `server.py`'s `_snapshot`, filtering // `p.name.endswith(".md") and not p.name.startswith(".")`. MEASURED at this head by READING // both, and then BEHAVIOURALLY over a scope holding `README.md` beside one ordinary entry: // `Build` shipped `/README.md` and `/.md` (entries=2), and `GET @@ -458,12 +458,12 @@ func EntryUnreadable(path string, cause error) *EntryUnreadableError { // StoreUnreadable is the STORE-WIDE twin of `EntryUnreadable` — "I could not finish // reading this store", named by ROOT rather than by the file that stopped it. // -// 🔴 THESE BYTES ARE COMPARED ACROSS THE TWO CLIENTS, which is why the sentence lives -// behind a name rather than being spelled at its call site. The oracle's twin is +// 🔴 THESE BYTES WERE COMPARED ACROSS THE TWO CLIENTS, which is why the sentence lives +// behind a name rather than being spelled at its call site. The oracle's twin was // `subsystem_recall._store_unreadable`, and `tests/parity/harness.py`'s // `validate-unreadable-entry` / `recall-unreadable-entry` / `*-unreadable-scope-dir` rows -// diff the two clients' stderr byte for byte — so a second spelling here is a divergence -// waiting to happen. +// diffed the two clients' stderr byte for byte. Both are deleted with the oracle; the name +// still keeps this to ONE spelling, and a second one here would still drift. // // ⚠ ONE CALL SITE TODAY (`LoadStore`, below). Re-derive rather than trusting this sentence: // `grep -n 'StoreUnreadable(' internal/store/load.go`. diff --git a/internal/store/marker.go b/internal/store/marker.go index 48be3546..836b2d8a 100644 --- a/internal/store/marker.go +++ b/internal/store/marker.go @@ -166,10 +166,10 @@ func LineOpenness(line string) (openness, resolvedBy string) { // "the sweep below reports 0 divergences across all three populations" and there was no // sweep below — not in this file, not anywhere in the tree, and the figures it quoted // were unreproducible. The sweep is now -// `internal/store/markersweep_test.go`, over the corpus `tests/marker_corpus.py` -// generates and `internal/store/testdata/marker_oracle_sweep.json` carries; the -// oracle's side of it is re-derived from the LIVE patterns by -// `tests/test_marker_oracle_sweep.py` on every pytest run. +// `internal/store/markersweep_test.go`, over the corpus whose axes and CPython verdicts +// `internal/store/testdata/marker_oracle_sweep.json` carries — FROZEN since the Python +// reader that produced the verdicts was retired (it was re-derived from the live patterns +// on every pytest run until then). // // So, MECHANICALLY: widen `hasFoldedPrefix` to fold the four runes `foldsToASCIILetter` // names — `unicode.SimpleFold` alone will NOT do it, U+0130 and U+0131 have no simple diff --git a/internal/store/markersweep_test.go b/internal/store/markersweep_test.go index d3f4436a..82357d51 100644 --- a/internal/store/markersweep_test.go +++ b/internal/store/markersweep_test.go @@ -27,10 +27,13 @@ import ( // HOW THE ORACLE'S ANSWERS GET HERE. `internal/store/testdata/marker_oracle_sweep.json` // carries // the corpus AXES, the SHA-256 of the assembled corpus and the oracle's verdicts as two -// bit-strings. `tests/marker_corpus.py` writes it and `tests/test_marker_oracle_sweep.py` -// re-derives every one of those verdicts from the LIVE `lib/subsystem_resolver` patterns -// on every pytest run — so the fixture cannot drift away from the regexes it claims to -// record. This side assembles the SAME corpus from the SAME axes and checks the SHA-256 +// bit-strings. 🔴 IT IS A FROZEN CONTRACT NOW: it was written by `tests/marker_corpus.py` +// from the retired Python reader's patterns (and re-derived from them on every pytest run +// while they existed); both went with the Python client, and the fixture is frozen as it +// stood at ec1b756b15ea37469124c635d0d82f6e10d57899. The verdicts are still CPython's +// answers, which is what a hand-rolled transcription of a CPython regex must keep +// matching — so a mismatch here is a narrowing in THIS package, never a reason to +// re-record the fixture from it. This side assembles the SAME corpus from the SAME axes and checks the SHA-256 // before reading a single verdict: two assemblers in two languages is the seam that // drifts silently, and without the hash a comfortable zero here would be a zero over a // corpus the Python side never saw. @@ -55,7 +58,8 @@ type markerSweepFixture struct { } // loadMarkerSweep reads the fixture and rebuilds the corpus from its axes, in the ONE -// order `tests/marker_corpus.py` documents. The nesting is load-bearing: change it and +// order the retired Python generator (`tests/marker_corpus.py`, deleted with the client; +// read it at ec1b756) assembled it in. The nesting is load-bearing: change it and // the SHA-256 check below fires, which is the point of having one. func loadMarkerSweep(t *testing.T) (markerSweepFixture, []string) { t.Helper() @@ -93,7 +97,7 @@ func loadMarkerSweep(t *testing.T) (markerSweepFixture, []string) { " go sha256 %s over %d lines\n"+ " python sha256 %s over %d lines\n"+ "Every verdict below would then be compared against lines nobody ran. "+ - "Re-read the assembly order in tests/marker_corpus.py.", + "Re-read the assembly order in tests/marker_corpus.py at ec1b756.", got, len(lines), fx.CorpusSHA256, fx.CorpusLines) } if len(fx.Anywhere) != len(lines) || len(fx.NearMiss) != len(lines) { @@ -206,8 +210,8 @@ func hasFoldingRune(line string) bool { // over-guarding is never another guard, and its unique coverage was six mutations that // are inert by construction. What it did NOT uniquely cover, and what still guards every // consequential case: a fifth folding rune, or a moved target, fails -// `tests/test_marker_oracle_sweep.py::test_the_re_I_folding_runes_are_exactly_the_four_ -// the_code_names`, which sweeps the whole codepoint space; the U+017F entry — the only +// `tests/test_cpython_re_folding_runes.py::test_the_re_I_folding_runes_are_exactly_the_four_ +// the_code_names`, which sweeps the whole codepoint space against CPython's `re.I`; the U+017F entry — the only // reachable one — fails the Go sweep in this file; and the PRODUCTION enumeration // `foldsToASCIILetter` is killed on all four runes by that same sweep. #109's own F2 // body offers this paragraph as the sufficient alternative ("state plainly that three @@ -301,7 +305,7 @@ func reIFoldedPrefix(rs []rune, want string) bool { // divergence whose only cause WAS the declared fold stopped vanishing and got reported as // `1 divergence(s) outside the ONE declared residual` — a false alarm on the one clause // that exists to catch a real narrowing. MEASURED on `- Reſolved ſ: …`, now a corpus row -// (`tests/marker_corpus.py`): oracle True, walk false, whole-line respelling false, +// (in the frozen fixture's axes): oracle True, walk false, whole-line respelling false, // attributed UNDECLARED, the Go sweep RED. No row of that shape existed before, which is // why `210 / 0` held over a broken attribution. // diff --git a/internal/store/normalize.go b/internal/store/normalize.go index ac31510f..0790d450 100644 --- a/internal/store/normalize.go +++ b/internal/store/normalize.go @@ -1,5 +1,5 @@ -// Package store is the Go port of the reader `lib/subsystem_resolver.py` and -// the index half of `lib/subsystem_recall.py`: ref folding, front matter, entry +// Package store is the Go port of the retired reader `lib/subsystem_resolver.py` +// and the index half of `lib/subsystem_recall.py`: ref folding, front matter, entry // validation, the index, ref resolution, the path classifier and the journal // bullet parser. // diff --git a/internal/store/openness.go b/internal/store/openness.go index 242eb386..2505f3ab 100644 --- a/internal/store/openness.go +++ b/internal/store/openness.go @@ -284,8 +284,8 @@ func hasFoldedPrefix(rs []rune, want string) bool { // corpus, while the comment one function over read as though it were closed. Read a // convergence claim as being about the RUN it was measured on, never about a caller. // -// The ledger, measured by `internal/store/markersweep_test.go` over the corpus -// `tests/marker_corpus.py` generates: +// The ledger, measured by `internal/store/markersweep_test.go` over the frozen corpus in +// `testdata/marker_oracle_sweep.json`: // // `\d` in the date prefix (`looksISODate`) CLOSED — `unicode.IsDigit` // `\d` in the ref atoms (`refAtomEnds`) CLOSED — `unicode.IsDigit` diff --git a/internal/store/pyoserror.go b/internal/store/pyoserror.go index f61ec0ec..72b5a461 100644 --- a/internal/store/pyoserror.go +++ b/internal/store/pyoserror.go @@ -30,8 +30,8 @@ import ( // // ⚠ WHAT THIS IS NOT: a general `repr` of every OSError CPython can raise. An error carrying // no errno — a Go-level wrapper, a cancelled context — has no `[Errno N]` form, so the Go -// text is returned unchanged. That fallback is a NAMED residual difference rather than a -// silent one; see `tests/parity/README.md`. +// text is returned unchanged. That fallback was a NAMED residual difference rather than a +// silent one in `tests/parity/README.md` (deleted with the oracle; read it at `ec1b756`). func PyOSError(err error) string { var errno syscall.Errno if !errors.As(err, &errno) { diff --git a/internal/store/validate.go b/internal/store/validate.go index 2067c95f..2d5a911b 100644 --- a/internal/store/validate.go +++ b/internal/store/validate.go @@ -140,13 +140,13 @@ func nuanceBody(path string) (string, bool) { // `Action` is not `Take` either. What `ActionFor` buys here is the SHARED TABLE, // not the raised error. // - // ⚠ AND THE TWO CLIENTS DIVERGE ON THAT BRANCH. `lib/entry_shape.py`'s - // `_nuance_body` calls `action_for(...) != TAKE`, and `action_for` raises + // ⚠ AND THE TWO CLIENTS DIVERGED ON THAT BRANCH. The retired `lib/entry_shape.py`'s + // `_nuance_body` called `action_for(...) != TAKE`, and `action_for` raised // `AssertionError` on an unmapped kind with nothing catching it — so the oracle - // ABORTS where this returns "no nuance section". UNREACHABLE TODAY in both: - // `TestTheActionTablesAreTotal` here and `TestClassifierIsTotal` on the Python - // side pin the kind set against the loader table two-way, so no unmapped kind can - // exist to reach either branch. Recorded rather than closed — closing it means + // ABORTED where this returns "no nuance section". UNREACHABLE TODAY: + // `TestTheActionTablesAreTotal` pins the kind set against the loader table two-way + // (`TestClassifierIsTotal` did the same on the Python side), so no unmapped kind can + // exist to reach this branch. Recorded rather than closed — closing it means // giving this function an error return that both call sites would discard, which // is the same swallow one frame further out. // @@ -596,11 +596,12 @@ const AdvisoryQuoteMax = 120 // zero from an instrument that walked nothing, and it must not render anywhere near a // clean-looking count. // -// 🔴 THIS IS ONE HALF OF A PAIR KEPT BYTE-IDENTICAL BY `tests/parity/`. The oracle's -// spelling is `entry_shape.validation_advisory_lines`. Changing either alone IS a -// divergence, and the parity world seeds a scope carrying a dropped line, an -// out-of-reach marker, a renamed heading, a duplicated-and-empty heading and every -// open-action population precisely so a one-sided edit is RED rather than invisible. +// 🔴 THIS WAS ONE HALF OF A PAIR KEPT BYTE-IDENTICAL BY `tests/parity/`. The oracle's +// spelling was `entry_shape.validation_advisory_lines`, and the parity world seeded a scope +// carrying a dropped line, an out-of-reach marker, a renamed heading, a duplicated-and-empty +// heading and every open-action population so a one-sided edit was RED rather than +// invisible. Both are deleted with the oracle; nothing compares these lines against a +// second implementation any more. // // 🔴 EVERY FINDING SET IS A REQUIRED PARAMETER, NOT A VARIADIC OR AN OPTION STRUCT, and // that is the point of the signature. A caller that never wired a scanner would diff --git a/internal/store/validate_test.go b/internal/store/validate_test.go index 27cddc40..71a11104 100644 --- a/internal/store/validate_test.go +++ b/internal/store/validate_test.go @@ -17,10 +17,11 @@ import ( // The WRITE-PROTOCOL half of `validate`, ported. Every fixture is synthetic and // dated year 2000, per `AGENTS.md`. // -// 🔴 THESE MIRROR `tests/test_entry_shape_validate.py` CASE FOR CASE. The gate that -// makes the two agree BYTE-FOR-BYTE is `tests/parity/`, which runs both clients over -// one world; these are the unit half, and they exist because the parity harness -// compares two clients rather than either client against an expectation. +// 🔴 THESE MIRRORED `tests/test_entry_shape_validate.py` CASE FOR CASE. The gate that +// made the two agree BYTE-FOR-BYTE was `tests/parity/`, which ran both clients over +// one world; these were the unit half, and they exist because the parity harness +// compared two clients rather than either client against an expectation. Both Python +// halves are deleted with the oracle, so these are now the only coverage. func entryWithNuance(t *testing.T, dir, name, nuance string) string { t.Helper() diff --git a/internal/ui/README.md b/internal/ui/README.md index 9a2b5d2b..35be1183 100644 --- a/internal/ui/README.md +++ b/internal/ui/README.md @@ -1693,9 +1693,10 @@ for (d)"**. This is that line. — and renders the resulting VALUES as HTML. It does not render through `internal/report`, and it does not write a parser of its own.** Three reasons, in the order they bind: -1. **`internal/report` renders TEXT whose bytes are pinned against the Python oracle.** Its - whole contract is `RenderText`, and `tests/parity/` diffs those bytes byte-for-byte between - two clients. A browser needs a `
` per heading and an `
  • ` per bullet; getting +1. **`internal/report` renders TEXT whose bytes are a FROZEN contract recorded from the Python + oracle** (`internal/report/testdata/reader_fixtures.json`). Its whole contract is + `RenderText`, which the retired `tests/parity/` also diffed byte-for-byte between two + clients. A browser needs a `
    ` per heading and an `
  • ` per bullet; getting there through `report` would mean parsing its rendered output back apart — a second parser with extra steps, whose input is a format deliberately frozen for a different consumer. Worse, it would make every HTML change on this surface a change to something the parity gate @@ -2528,8 +2529,10 @@ pinned by spelling; `TestTheRemovedDefinitionCopyIsAbsentAndChipsArePresent` pin HAS one and that the old lines are absent. ⚠ **THE PAGE STILL DOES NOT ENUMERATE THE TAG SET,** for the reason that always held: the declared -terms live in `internal/write`'s `tagVocabulary` and in `lib/entry_shape.py`, pinned against each -other, and a third spelling on a page nothing gates against them is drift waiting to happen. +terms live in `internal/write`'s `tagVocabulary`, pinned against literals by +`tests/test_tag_vocabulary.py` (and, until the Python oracle was retired, against +`lib/entry_shape.py`), and another spelling on a page nothing gates against them is drift +waiting to happen. ## 🔴 A HOSTILE TAG IS IN THE ESCAPING DIFFERENTIAL EVEN THOUGH THE LOADER CANNOT PRODUCE ONE diff --git a/internal/write/citationtoken_test.go b/internal/write/citationtoken_test.go index ad6b38d6..a81648d2 100644 --- a/internal/write/citationtoken_test.go +++ b/internal/write/citationtoken_test.go @@ -30,8 +30,9 @@ import ( // go through `BulletContent`. // // Every test below was watched RED against the pre-fix source and the matrix is in -// the commit message. `tests/test_bullet_trailer_strip.py` is the Python twin; -// `tests/parity/` is what compares the two. +// the commit message. `tests/test_bullet_trailer_strip.py` was the Python twin (deleted +// with the oracle); what tied the two together was `trailerdigest_test.go`'s digest, not +// `tests/parity/` — see `revision.go`. const ( trailerProse = "the drill head overheats above 40C" diff --git a/internal/write/revision.go b/internal/write/revision.go index eb56acff..5041580b 100644 --- a/internal/write/revision.go +++ b/internal/write/revision.go @@ -145,11 +145,11 @@ var bulletOpenerRe = regexp.MustCompile(`\A[-*][ \t]+(?:\d{4}-\d{2}-\d{2}:[ \t]+ // CPython's backtracking engine whenever the trailer run does NOT reach end-of-line: // `re` retries the alternation from every start position, and each of the ~n positions // INSIDE the run matches its way to the final non-trailer word before failing — O(n) -// apiece (8.8s over a 224 KB line; `server.py`'s -// `_BULLET_TRAILER_PIECE_RE` carries the table). RE2 has no backtracking, so this +// apiece (8.8s over a 224 KB line; the retired `server.py`'s +// `_BULLET_TRAILER_PIECE_RE` carried the table — read it at `ec1b756`). RE2 has no backtracking, so this // side is linear on BOTH suffix shapes — measured in one process in one run, ×1.7-2.4 // per doubling out to n=64,000 / 896,048 bytes, AT-END 27.4ms and NOT-END 33.5ms, the -// per-n rows in `TestTheTrailerStripIsLinearRatherThanQuadratic`. `server.py` peels +// per-n rows in `TestTheTrailerStripIsLinearRatherThanQuadratic`. `server.py` peeled // the run one piece at a time instead. Two mechanisms, one answer, and the answer is // what `trailerdigest_test.go` compares — never the expression. // @@ -163,25 +163,24 @@ var bulletTrailersRe = regexp.MustCompile( // collapsed bullet, in ANY ORDER and ANY NUMBER, and nothing else. // // 🔴 ONE RULE, ONE PLACE: `BulletContent` is the only caller, and nothing else in -// this package or in `server/server.py` may re-spell "what a trailer is". The two -// languages carry one implementation each (`server.py`'s `_strip_bullet_trailers`) -// because `lib/` cannot import `internal/`. +// this package may re-spell "what a trailer is". While the Python oracle lived the two +// languages carried one implementation each (`server.py`'s `_strip_bullet_trailers`) +// because `lib/` could not import `internal/`; this is the only one now. // -// 🔴 AND WHAT COMPARES THEM IS `trailerdigest_test.go`, NOT `tests/parity/`. This +// 🔴 AND WHAT COMPARED THEM WAS `trailerdigest_test.go`, NOT `tests/parity/`. This // sentence read "`tests/parity/` is what compares them" until a round measured the -// claim: that harness diffs the two CLIENTS' rendered bytes, this is POD-side, and -// `tests/parity/README.md` contains ZERO occurrences of "trailer". It named a gate -// that does not see this function — a description claiming coverage the +// claim: that harness diffed the two CLIENTS' rendered bytes, this is POD-side, and +// `tests/parity/README.md` contained ZERO occurrences of "trailer". It named a gate +// that did not see this function — a description claiming coverage the // implementation does not provide, which is worse than none because it stops the // next reader looking. The real comparison is the digest below. // -// ⚠ AND IT IS NO LONGER A TRANSCRIPTION — THE TWO ARE TWO MECHANISMS OVER ONE +// ⚠ AND IT WAS NO LONGER A TRANSCRIPTION — THE TWO WERE TWO MECHANISMS OVER ONE // GRAMMAR, which is a stronger claim to hold up than a shared expression. This keeps -// the whole-run alternation because RE2 cannot backtrack; `server.py` peels the run +// the whole-run alternation because RE2 cannot backtrack; `server.py` peeled the run // one piece at a time because CPython's engine can and does. See `bulletTrailersRe` // for the measurement, and `trailerdigest_test.go` for the one constant both -// implementations are pinned to — which is what makes the equivalence measured rather -// than assumed now that there is no shared expression to read it off. +// implementations were pinned to — now a frozen contract, since the Python side is gone. // // One pass. `bulletTrailersRe` is anchored at `\z` and every alternative consumes at // least one bracketed token, so there is exactly one possible match and no empty one diff --git a/internal/write/tagvocab.go b/internal/write/tagvocab.go index ee406e55..ac3c66ad 100644 --- a/internal/write/tagvocab.go +++ b/internal/write/tagvocab.go @@ -35,15 +35,13 @@ import "slices" // later edit can wire into `parseTagsField`, and the refusal that edit produces is the // outage above. It is also unexported, so no consumer of this package can grow a second // copy of the check — `internal/client` imports `write.BulletTextMax` and could -// otherwise have grown a client-side pre-check, which `tests/parity/` would then need -// in BOTH clients to stay green. +// otherwise have grown a client-side pre-check, a second spelling of the refusal. // // ⚠ SORTED, AND THAT IS PART OF THE REFUSAL'S CONTRACT RATHER THAN TIDINESS. The -// refusal message joins this slice with `|`; `lib/entry_shape.py`'s `TAG_VOCABULARY` -// joins its own tuple the same way; `tests/conformance/` compares the two servers' -// response bytes for a `PUT` carrying an off-vocabulary tag. Reordering or extending -// one side alone is a RED corpus, not a review comment — -// `tests/test_tag_vocabulary.py` is the cheaper red that says which side moved. +// refusal message joins this slice with `|`, and `tests/conformance/` replays a `PUT` +// carrying an off-vocabulary tag against its frozen golden (recorded from the retired +// Python oracle, which joined its own copy the same way). Reordering or extending it is a +// RED corpus, not a review comment — `tests/test_tag_vocabulary.py` is the cheaper red. // // ⚠ AND THE BROWSER IS NOT A WRITER, WHICH IS WHY NO BROWSER-SIDE GATE EXISTS. Measured // rather than assumed: every state-changing route in `internal/ui/routes.go`'s dispatch diff --git a/internal/write/tagvocab_test.go b/internal/write/tagvocab_test.go index e9188368..0ece0419 100644 --- a/internal/write/tagvocab_test.go +++ b/internal/write/tagvocab_test.go @@ -40,7 +40,7 @@ func taggedEntry(tagsFlow string) string { // 🔴 A LITERAL, BECAUSE AN EXPECTATION DERIVED FROM THE IMPLEMENTATION ASSERTS NOTHING. // Interpolating `strings.Join(tagVocabulary, "|")` here would make this test pass under // a mutant that reorders the vocabulary, drops a term, or changes the separator — the -// exact three edits the conformance corpus would then catch on the oracle instead, one +// exact three edits the conformance corpus would then catch against its frozen goldens, one // gate and several minutes later. const wantRefusal = "tag 'marketing' is not one of infra|product|tooling — " + "the tag vocabulary is CLOSED on the WRITE path, so widening it is a code change. " + @@ -293,12 +293,10 @@ func TestAppendingToAnEntryCarryingAnOffVocabularyTagStillWorks(t *testing.T) { // TestTheVocabularyIsExactlyTheDeclaredThreeTerms pins the set and its ORDER. // // 🔴 THE ORDER IS PART OF THE WIRE CONTRACT, NOT TIDINESS. The refusal joins this slice -// with `|`, the oracle joins its own tuple the same way, and `tests/conformance/` -// compares the two servers' bytes. +// with `|`, and `tests/conformance/` replays it against a frozen golden. // // ⚠ AN INVARIANT GUARD, NOT REGRESSION COVERAGE: no defect ever reordered this slice. -// It is here so a term added on one side alone is red in this package rather than three -// gates away. +// It is here so a term added is red in this package rather than three gates away. // // 🔴 IT DELIBERATELY DOES **NOT** ALSO ASSERT SORTEDNESS AND UNIQUENESS, AND DELETING // THOSE TWO ASSERTIONS IS THE POINT RATHER THAN A TRIM. They stood here for one round @@ -315,8 +313,8 @@ func TestTheVocabularyIsExactlyTheDeclaredThreeTerms(t *testing.T) { want := []string{"infra", "product", "tooling"} if !slices.Equal(tagVocabulary, want) { t.Fatalf("tagVocabulary=%q, want %q — if a term was added or removed on purpose, "+ - "move `lib/entry_shape.py`'s TAG_VOCABULARY in the same commit, regenerate the "+ - "`tests/conformance/` goldens, and move the other hand-typed expectations "+ + "argue the contract change against the frozen `tests/conformance/` goldens, and "+ + "move the other hand-typed expectations "+ "`README.md` enumerates — this literal is only one of them", tagVocabulary, want) } } diff --git a/internal/write/trailerdigest_test.go b/internal/write/trailerdigest_test.go index 6db38373..87c01305 100644 --- a/internal/write/trailerdigest_test.go +++ b/internal/write/trailerdigest_test.go @@ -6,23 +6,27 @@ import ( "testing" ) -// THE CROSS-LANGUAGE HALF OF THE TRAILER STRIP — the GO side. +// THE CROSS-LANGUAGE HALF OF THE TRAILER STRIP — the GO side. ⚠ The Python side +// (`tests/test_bullet_trailer_strip.py`, `server.py`'s `_strip_bullet_trailers`) is +// deleted with the oracle; read it at `ec1b756`. The digest below now records what both +// sides agreed on, and this side must keep producing it. The paragraphs below +// describe the comparison as it ran. // -// 🔴 THE TWO STRIPS ARE NO LONGER ONE EXPRESSION IN TWO SPELLINGS. This side keeps -// the whole-run `(?:[ \t]*(?:ATTR|TOKEN))+\z` alternation; `server.py` peels the run +// 🔴 THE TWO STRIPS WERE NO LONGER ONE EXPRESSION IN TWO SPELLINGS. This side keeps +// the whole-run `(?:[ \t]*(?:ATTR|TOKEN))+\z` alternation; `server.py` peeled the run // one piece at a time, because the same shape is QUADRATIC under CPython's // backtracking engine on any suffix the run does not end, and RE2 cannot backtrack — // see `bulletTrailersRe` for both measurements. So "they agree" stopped being readable // off a shared pattern and became a property that has to be MEASURED. // -// This file is where it is measured: both languages enumerate the SAME declared axes, -// hash their own strip's output over them, and assert the SAME hex constant. One -// constant, two independent implementations — if either drifts on any enumerated -// input, both sides go red. +// This file is where it was measured: both languages enumerated the SAME declared axes, +// hashed their own strip's output over them, and asserted the SAME hex constant. One +// constant, two independent implementations — if either drifted on any enumerated +// input, both sides went red. Only this side remains. // // ⚠ A DIGEST NAMES NO INPUT. It answers "do the two agree", never "where do they -// differ" — when it goes red, `citationtoken_test.go`'s per-row tests and -// `tests/test_bullet_trailer_strip.py`'s oracle comparison are what name rows. A +// differ" — when it goes red, `citationtoken_test.go`'s per-row tests are what name rows +// (as `tests/test_bullet_trailer_strip.py`'s oracle comparison also did). A // digest is what makes this affordable in two languages without shipping a 10 MB // fixture. // @@ -66,10 +70,12 @@ const trailerStripAxisInputs = 84210 // trailerStripAxisDigest is sha256 over `stripBulletTrailers(input) + "\x00"` for // every enumerated input, in enumeration order. // -// 🔴 `tests/test_bullet_trailer_strip.py` PINS THE SAME STRING for -// `_strip_bullet_trailers`, and that is the whole point: this constant is the only -// place the two implementations meet. Re-derive it by running either side, never by -// copying the other's failure message — a message quotes what the code DID. +// 🔴 `tests/test_bullet_trailer_strip.py` PINNED THE SAME STRING for +// `_strip_bullet_trailers`, and that was the whole point: this constant was the only +// place the two implementations met. The Python side is deleted with the oracle, so the +// constant can no longer be re-derived independently: moving it is a CONTRACT change, +// argued in review, and never a copy of this side's failure message — a message quotes +// what the code DID. const trailerStripAxisDigest = "a5f4c2e4116e202169a3d00cc1c39f9e4fc3e6380d4c5f128d7a8ab9212e970e" // trailerStripAxisEach walks the declared enumeration in the order the digest is diff --git a/lib/cairn_doctor.py b/lib/cairn_doctor.py deleted file mode 100644 index d55112de..00000000 --- a/lib/cairn_doctor.py +++ /dev/null @@ -1,709 +0,0 @@ -#!/usr/bin/env python3 -"""`cairn doctor` — one call that answers what a reader otherwise checks by hand. - -🔴 WHY THIS EXISTS. Every fact below was previously established by a human -running four or five commands and holding the results in their head: is the pod -up, is my token any good, is my cache stamped, does my cache agree with the pod, -is anything on this disk invisible to my credential, and does this host's READER -resolve to the synced cache or to the frozen pre-cutover mirror. Nothing joined -them, so the answers were assembled differently every time and the joins that -matter — cache count vs pod count, local scopes vs visible scopes — were the -ones nobody made. - -🔴 FOUR STATES, AND THE FOURTH IS THE WHOLE POINT. This subsystem's recurring -defect is a reassuring zero: an output that cannot distinguish "there is nothing -there" from "I could not look". So every check reports one of - - OK measured, and the answer is fine - PROBLEM measured, and the answer is not fine - UNMEASURED I tried and could not — the reason is mandatory - NOT-OBSERVABLE this cannot be answered from a client AT ALL, structurally, - and the detail names who can answer it and how - -`NOT-OBSERVABLE` is separate from `UNMEASURED` on purpose. Folding the two would -make the exit code permanently non-zero — the deployed API exposes no identity -route and never will from here — and `claude/RULES.md` says a permanently-red -gate is worse than no gate because it trains everyone to click through. - -🔴 DOCTOR NEVER INSTALLS A SNAPSHOT. It fetches, reads the headers and the member -list, and throws the bytes away. A diagnostic that repaired the cache as a side -effect would destroy the staleness it was run to measure — and it would be the -one command you must not run twice. - -🔴 THE HOLE IT CANNOT CLOSE, STATED RATHER THAN LEFT TO BE FOUND. A scope this -host holds but the pod's snapshot does not contain is EITHER a scope the store -has never held OR a scope outside this token's allowlist. The API answers those -two identically **by design** — `server.py` closes an enumeration oracle by -making a refused scope byte-identical to an absent one — so no client can tell -them apart, and this module does not pretend to. It reports the set and names -both readings. -""" - -from __future__ import annotations - -import hashlib -from collections.abc import Callable, Iterable -from dataclasses import dataclass, field -from pathlib import Path - -__all__ = [ - "OK", - "PROBLEM", - "UNMEASURED", - "NOT_OBSERVABLE", - "STATES", - "TOKEN_FINGERPRINT_CHARS", - "Check", - "PodFacts", - "token_fingerprint", - "store_entry_files", - "store_scopes", - "writable_entry_files", - "collect", - "render", - "exit_code", -] - -#: The four verdicts a check may carry. Written out once; `render` and -#: `exit_code` both read this tuple rather than restating the list. -OK = "OK" -PROBLEM = "PROBLEM" -UNMEASURED = "UNMEASURED" -NOT_OBSERVABLE = "NOT-OBSERVABLE" -STATES: tuple[str, ...] = (OK, PROBLEM, UNMEASURED, NOT_OBSERVABLE) - -#: How many hex characters of `sha256(token)` identify a credential. -#: -#: 🔴 THIS MIRRORS `subsystem-store-api/server.py::token_id`, WHICH IS WHAT THE -#: POD'S AUDIT LOG CARRIES. The value is what makes the fingerprint printed here -#: matchable against a `token=` line in the pod's log, so the two agreeing is -#: a wire fact and not an implementation detail. `cairn` cannot import -#: `server.py` — that module inserts paths, pulls in the whole reader and exists -#: to be run as a daemon — so the rule is spelled twice and pinned once: -#: `test_cairn_doctor.py::test_the_fingerprint_is_the_SERVERS_token_id` imports -#: both and requires they agree on a fixture whose expected digest is written out -#: as a literal in the test. -TOKEN_FINGERPRINT_CHARS = 12 - - -def token_fingerprint(token: str) -> str: - """A stable, non-reversible handle for a credential. NEVER the token.""" - return hashlib.sha256(token.encode("utf-8")).hexdigest()[:TOKEN_FINGERPRINT_CHARS] - - -@dataclass(frozen=True) -class Check: - """One diagnosed fact. - - `detail` is mandatory and is not decoration: for `UNMEASURED` it carries the - reason, and for `NOT-OBSERVABLE` it carries the command that CAN answer it. - A state with an empty detail is refused at construction, because a bare - `UNMEASURED` is the reassuring zero wearing a different word. - """ - - name: str - state: str - detail: str - - def __post_init__(self) -> None: - if self.state not in STATES: - raise ValueError(f"unknown check state {self.state!r}; expected one of {STATES}") - if not self.detail.strip(): - raise ValueError( - f"check {self.name!r} has an empty detail — a state with no " - f"reason cannot be acted on" - ) - - -@dataclass(frozen=True) -class PodFacts: - """What one non-installing snapshot fetch established, or why it did not. - - 🔴 `reached` IS NOT DERIVED FROM THE COUNTS. A store that genuinely holds - zero entries and a fetch that never happened both leave the counts at 0, so - the counts may only be read when `reached` is True — and every consumer below - branches on `reached` first. - """ - - reached: bool - #: Set when `reached` is False. Mandatory in that case. - reason: str = "" - #: The HTTP status when the server ANSWERED but refused. `None` when there - #: was no answer at all, which is what separates unauthorised from - #: unreachable without parsing a message. - http_status: int | None = None - #: `X-Store-Entries` — what THIS token's snapshot contained. - visible_entries: int | None = None - #: `entry-files=` out of `X-Store-Snapshot` — the STORE-WIDE total, which the - #: server emits unfiltered (a documented, deliberate residual count leak). - store_wide_entries: int | None = None - #: Scope directory names present in the fetched archive. - visible_scopes: tuple[str, ...] = () - #: The raw `X-Store-Snapshot` header, relayed verbatim. - snapshot_header: str = "" - - def __post_init__(self) -> None: - """🔴 THE MANDATORY REASON, ENFORCED — it was only DOCUMENTED before. - - `Check` refuses an empty detail at construction; this dataclass said - "Mandatory in that case" about `reason` and checked nothing. The - asymmetry is the defect, in the module whose whole thesis is that a bare - UNMEASURED is the reassuring zero wearing a new word: a future - `PodFacts(reached=False)` renders `the store's state could not be - established — .` and walks straight past `Check`'s guard, because the - empty string is wrapped in literal f-string text before it gets there. - Not reachable from today's three call sites; that is what makes now the - cheap time to close it. - """ - if not self.reached and not self.reason.strip(): - raise ValueError( - "PodFacts(reached=False) requires a reason — an unmeasured " - "store with no stated cause is the silent zero this module " - "exists to prevent" - ) - - -# --------------------------------------------------------------------------- # -# Disk facts. Each one is a plain function so a test can drive it directly. -# --------------------------------------------------------------------------- # - -def _scope_dirs(root: Path) -> list[Path]: - """`//` directories, dot-directories excluded. - - Raises `OSError` rather than returning `[]` on an unreadable root: an empty - list and an unreadable directory are the two things this whole module exists - to keep apart, so the failure has to reach a caller that can name it. - """ - return sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith(".")) - - -def store_scopes(root: Path) -> tuple[str, ...]: - """The scope names a store root holds.""" - return tuple(p.name for p in _scope_dirs(root)) - - -def store_entry_files(root: Path) -> int: - """`/.md` files under a store root. - - The SAME shape `server.snapshot_freshness` counts — depth 2, `*.md`, no - dot-directories and no dot-files — so this number and the pod's - `entry-files=` are answers to one question rather than two. - """ - total = 0 - for scope in _scope_dirs(root): - for entry in scope.iterdir(): - if entry.is_file() and entry.name.endswith(".md") and not entry.name.startswith("."): - total += 1 - return total - - -def writable_entry_files(root: Path) -> tuple[str, ...]: - """Entry files under `root` that any mode bit still allows WRITING. - - 🔴 THE FREEZE IS A PROPERTY OF EVERY FILE, NOT OF THE DIRECTORY. The cutover - chmods the pre-cutover mirror read-only so nothing can write to a store that - no longer feeds anybody. A partially-frozen mirror still accepts a write, - and that write then lives on one host and is invisible to the pod — the - exact stranding the cutover exists to prevent. So this counts FILES, and a - non-empty answer is a PROBLEM even when the directory looks frozen. - """ - loose: list[str] = [] - for scope in _scope_dirs(root): - for entry in sorted(scope.iterdir()): - if not (entry.is_file() and entry.name.endswith(".md")): - continue - if entry.stat().st_mode & 0o222: - loose.append(f"{scope.name}/{entry.name}") - return tuple(loose) - - -@dataclass(frozen=True) -class Reading: - """One disk fact, or the structured reason there is none. - - 🔴 `absent` IS A FLAG, NOT A SENTENCE. The first version had callers ask - `reason.endswith("does not exist")` to tell a missing directory from an - unreadable one — a guard SPELLED rather than STRUCTURAL, which `claude/RULES.md` - names directly: reword the message and the branch silently stops firing, with - an unreadable mirror then reported as "nothing pre-cutover on this host". - """ - - value: object | None - reason: str - absent: bool - - @property - def ok(self) -> bool: - return self.reason == "" - - -def _describe(root: Path, what: Callable[[Path], object]) -> Reading: - """Read one fact off disk, or say why not. Never a silent zero. - - 🔴 `absent` MEANS THE ROOT IS ABSENT — it is re-checked, not inferred from - the exception type. Mapping ANY `FileNotFoundError` to `absent=True` is wrong - in a way that produces a confident OK: a file vanishing MID-WALK raises the - same exception, and this store has two writers that do exactly that — the - hourly `analyze-service-index-commit.service`, and `cairn sync`, which - replaces the cache root by rename. The report would have read - `frozen-mirror OK … does not exist` for a directory that was right there, - with a false reason attached. Same shape as the defect `dd8411ca` fixed, one - level in: a state derived from a proxy instead of from the thing itself. - """ - try: - return Reading(what(root), "", absent=False) - except FileNotFoundError as exc: - if not root.exists(): - return Reading(None, f"{root} does not exist", absent=True) - return Reading( - None, - f"{root} exists but something under it vanished while it was being " - f"read ({exc}) — a concurrent writer, not an absent store", - absent=False, - ) - except OSError as exc: - return Reading(None, f"{root} could not be read: {exc}", absent=False) - - -# --------------------------------------------------------------------------- # -# The checks -# --------------------------------------------------------------------------- # - -def collect( - *, - resolved_root: Path, - stamp_lines: Iterable[str] | None, - stamp_reason: str | None, - cache_root: Path, - mirror_root: Path | None, - pod: PodFacts, - token: str | None, - token_reason: str = "", - identity_remedy: str, -) -> list[Check]: - """Every check, in the order a reader should read them. - - Takes FACTS, not sources: the caller does the network and the config load, so - every branch here is reachable from a test with no server, no `$HOME` and no - clock. - """ - checks: list[Check] = [] - - # 1. WHICH DIRECTORY does this host's reader resolve, and can it date itself? - # This is `subsystem_read_store`'s question, asked out loud. - if stamp_lines is not None: - checks.append(Check( - "reader-resolution", - OK, - f"the reader resolves {resolved_root}, which carries a sync stamp", - )) - else: - checks.append(Check( - "reader-resolution", - PROBLEM, - f"the reader resolves {resolved_root}, which cannot date itself — " - f"{stamp_reason}. A read against it refuses (exit 4, the READER's " - f"EXIT_UNSTAMPED_READ_STORE). Fix: `cairn sync`.", - )) - - # 2. THE STAMP'S OWN FIELDS, relayed unparsed. - if stamp_lines is None: - checks.append(Check( - "cache-stamp", PROBLEM, - f"no readable stamp in {resolved_root} — {stamp_reason}", - )) - else: - rendered = "; ".join(stamp_lines) - checks.append(Check("cache-stamp", OK, rendered or "(the stamp is empty)")) - - # 3. THE FROZEN MIRROR. Absent is fine — a fresh host never had one. Present - # and fully read-only is fine. Present with a WRITABLE entry is not. - # - # 🔴 OPTIONAL, AND `None` IS NOT THE SAME AS ABSENT. A migrating deployment - # freezes its old local store and points this at it; a deployment that never - # had one has nothing to name. Saying "does not exist" about a path the - # operator never configured would be a claim about their disk that this code - # cannot support — so an unconfigured mirror is NOT-OBSERVABLE, not OK. - mirror = None if mirror_root is None else _describe(mirror_root, writable_entry_files) - loose = None if mirror is None else mirror.value - if mirror is None: - checks.append(Check( - "frozen-mirror", NOT_OBSERVABLE, - "no mirror is configured, so there is nothing to check. Set " - "CAIRN_MIRROR_ROOT if you migrated from a local store and want its " - "entry files confirmed read-only.", - )) - elif not mirror.ok: - if mirror.absent: - checks.append(Check( - "frozen-mirror", OK, - f"{mirror_root} does not exist — nothing pre-cutover on this host", - )) - else: - checks.append(Check("frozen-mirror", UNMEASURED, mirror.reason)) - elif loose: - shown = ", ".join(list(loose)[:5]) + ("…" if len(loose) > 5 else "") - checks.append(Check( - "frozen-mirror", PROBLEM, - f"{len(loose)} entry file(s) under {mirror_root} are still WRITABLE " - f"({shown}). The mirror is frozen so nothing writes to a store the " - f"pod does not read; a write to one of these lives on this host " - f"only. Re-run `cairn-cutover.py --freeze --apply`.", - )) - else: - checks.append(Check( - "frozen-mirror", OK, - f"every entry file under {mirror_root} is read-only", - )) - - # 4. THE POD. Unreachable, unauthorised and refused are three answers. - if pod.reached: - checks.append(Check( - "pod", OK, f"answered a snapshot request — {pod.snapshot_header or 'no stamp header'}", - )) - elif pod.http_status in (401, 403): - checks.append(Check( - "pod", PROBLEM, - f"the store ANSWERED and refused this credential (HTTP " - f"{pod.http_status}) — {pod.reason}. This is NOT an outage: the host " - f"is up. A 403 can also be the edge refusing the User-Agent rather " - f"than the token being wrong.", - )) - elif pod.http_status is not None: - checks.append(Check( - "pod", PROBLEM, - f"the store ANSWERED HTTP {pod.http_status} — {pod.reason}", - )) - else: - # 🔴 THE PREFIX IS NEUTRAL ON PURPOSE. It used to read "no answer from the - # store", which CONTRADICTS one of the reasons that arrives here: a - # snapshot the pod served and the client could not unpack is an answer. - # A heading that argues with the reason beneath it is a comment the code - # falsifies, which is the same defect class one layer up. - checks.append(Check( - "pod", UNMEASURED, - f"the store's state could not be established — {pod.reason}. Nothing " - f"below that needs the pod could be measured.", - )) - - # 5. CACHE vs POD. Only readable once the pod answered; otherwise UNMEASURED - # with the reason, never a zero. - cache = _describe(cache_root, store_entry_files) - cached = cache.value - if not pod.reached: - checks.append(Check( - "cache-vs-pod", UNMEASURED, - f"the pod was not reached ({pod.reason}), so the cache's " - f"{cached if cache.ok else 'unreadable'} entry file(s) " - f"could not be compared against anything", - )) - elif not cache.ok: - checks.append(Check("cache-vs-pod", UNMEASURED, cache.reason)) - elif pod.visible_entries is None: - checks.append(Check( - "cache-vs-pod", UNMEASURED, - "the store answered without an `X-Store-Entries` header, so its own " - "count of what it sent is unknown", - )) - elif cached == pod.visible_entries: - checks.append(Check( - "cache-vs-pod", OK, - f"{cached} entry file(s) here, {pod.visible_entries} in the store's " - f"answer to this token — they agree", - )) - else: - checks.append(Check( - "cache-vs-pod", PROBLEM, - f"{cached} entry file(s) here but {pod.visible_entries} in the " - f"store's answer to this token. Fix: `cairn sync`.", - )) - - # 6. WHAT THIS TOKEN CANNOT SEE. Two independent readings, both reported. - checks.append(_visibility_check(pod, cache_root, mirror_root)) - - # 7. THE CREDENTIAL. A fingerprint is measurable here; the IDENTITY behind it - # is not, from any client, and says so rather than going quiet. - if token is None: - checks.append(Check( - "token", PROBLEM, - token_reason or "no token is configured, so no request can be authenticated", - )) - else: - checks.append(Check( - "token", NOT_OBSERVABLE, - f"fingerprint {token_fingerprint(token)} (sha256[:{TOKEN_FINGERPRINT_CHARS}], " - f"the handle the pod's audit log carries). The IDENTITY and the " - f"declared scope allowlist behind it live in the pod's token file and " - f"the API exposes no route that returns them — see the scope check " - f"above for what this credential can actually reach. To read the " - f"declared row: {identity_remedy}", - )) - - return checks - - -def _visibility_check(pod: PodFacts, cache_root: Path, mirror_root: Path | None) -> Check: - """Scopes and entries on this disk that the store's answer did not carry. - - 🔴 `mirror_root` IS OPTIONAL AND UNSET IS THE DEFAULT. When the mirror - became configurable this signature was not widened with it, so `_describe` - was handed `None` and `doctor` died with `AttributeError: 'NoneType' object - has no attribute 'iterdir'` — zero stdout, exit 1 — for every deployment - that had never set `CAIRN_MIRROR_ROOT` and had a synced cache, which is the - ordinary state of a new one. The `frozen-mirror` check above had already - been widened; this one had not, and nothing joined the two. - - 🔴 AN UNCONFIGURED MIRROR IS NOT AN UNREADABLE ROOT. It contributes no - scopes and it is not a hole in this check's coverage, so it must NOT land in - `unread` — doing so would downgrade a complete answer to UNMEASURED on every - default deployment, which is the same false-alarm-forever failure in the - opposite direction. - """ - if not pod.reached: - return Check( - "token-scopes", UNMEASURED, - f"the pod was not reached ({pod.reason}), so nothing is known about " - f"which scopes this credential can reach", - ) - - # 🔴 PROVENANCE PER SCOPE, NOT ONE MERGED SET. The two roots mean different - # things and lead to different actions: a scope in the SYNCED CACHE that the - # pod no longer sends is a credential or a deletion; a scope in the FROZEN - # MIRROR only is a pre-cutover leftover that may never have reached the pod - # at all. The first version merged them and said "N scope(s) exist on this - # disk", offering two remedies that were both about the live store — so an - # operator could not tell which they were looking at. Measured: the two it - # named on the workbench were mirror-only. - where: dict[str, list[str]] = {} - unread: list[str] = [] - roots = [("cache", cache_root)] + ([] if mirror_root is None else [("mirror", mirror_root)]) - for label, root in roots: - reading = _describe(root, store_scopes) - if not reading.ok: - # An ABSENT root contributes nothing and is not a failure; an - # UNREADABLE one is a hole in this check's own coverage and is named - # in the detail, so a clean-looking answer cannot come from a walk - # that could not see half its input. - if not reading.absent: - unread.append(reading.reason) - continue - for name in reading.value: # type: ignore[union-attr] - where.setdefault(name, []).append(label) - - local = set(where) - visible = set(pod.visible_scopes) - missing = sorted(local - visible) - - hidden_entries = "" - if pod.store_wide_entries is not None and pod.visible_entries is not None: - gap = pod.store_wide_entries - pod.visible_entries - if gap > 0: - hidden_entries = ( - f" The store reports {pod.store_wide_entries} entry file(s) " - f"store-wide but sent this token {pod.visible_entries}, so " - f"{gap} live in scopes this credential cannot reach." - ) - - unread_note = (" Some local roots were unreadable: " + "; ".join(unread)) if unread else "" - - if not missing and not hidden_entries: - # 🔴 AN UNREADABLE LOCAL ROOT MAKES THIS UNMEASURED, NOT OK-WITH-A-NOTE. - # "every scope on this disk is among them" is a claim about a set this - # walk could not finish building, and an OK carrying a caveat in its tail - # is exactly how a partial answer gets read as a clean one. The note - # alone was the first version; it stated the hole and still graded the - # check green. - if unread: - return Check( - "token-scopes", UNMEASURED, - f"the {len(visible)} scope(s) the store sent are all reachable, but " - f"this host's own scope set could not be fully read, so nothing is " - f"established about scopes present locally.{unread_note}", - ) - return Check( - "token-scopes", OK, - f"this credential reaches all {len(visible)} scope(s) the store sent, " - f"and every scope on this disk is among them.", - ) - if not missing: - return Check("token-scopes", PROBLEM, hidden_entries.strip() + unread_note) - named = ", ".join(f"{s} [{'+'.join(where[s])}]" for s in missing) - mirror_only = [s for s in missing if where[s] == ["mirror"]] - leftover_note = ( - f" 🔴 {len(mirror_only)} of them exist ONLY in the frozen pre-cutover " - f"mirror ({', '.join(mirror_only)}) — those may never have reached the " - f"pod, so the question is whether they were ever seeded, NOT whether " - f"access was lost." - if mirror_only else "" - ) - return Check( - "token-scopes", PROBLEM, - f"{len(missing)} scope(s) exist on this disk and are NOT in the store's " - f"answer to this token, each tagged with WHERE it was found: {named}. " - f"For a scope the store should hold, the API cannot tell you which of " - f"two things you are seeing — a refused scope is byte-identical to one " - f"the store has never held, deliberately, so that an error cannot " - f"enumerate the store. Both readings are actionable: seed the scope, or " - f"add it to this token's allowlist.{leftover_note}" - f"{hidden_entries}{unread_note}", - ) - - -# --------------------------------------------------------------------------- # -# Rendering and the verdict -# --------------------------------------------------------------------------- # - -#: 🔴 THE EXIT CODES, OWNED BY THE COMMAND AND DOCUMENTED BY IT. `render` prints -#: the legend below on every run, so a caller never has to find a skill to learn -#: what a number meant. -#: -#: 🔴 THEY ARE SCOPED PER COMMAND, NOT GLOBALLY UNIQUE, AND 9 IS SHARED ON -#: PURPOSE. `doctor` returns 0/9/10. The client returns 0/3/4/5 for read outcomes, -#: 6/7/8/9 for write outcomes, and 2 for USAGE — which is a third bucket, not a -#: read outcome. An earlier draft of this sentence folded 2 in with the reads, and -#: the argparse bullet further down this same comment says the opposite, so the -#: block contradicted itself; the distinction is the point of that bullet. -#: So two numbers are shared: 0, which -#: means success in both because that is what 0 means, and 9, which is this -#: command's "a check MEASURED a problem" and `create`'s `EXIT_WRITE_EXISTS`. -#: Neither is ambiguous where a code is actually read — at ONE call site, which -#: already knows the verb it invoked. `doctor` never creates an entry and -#: `create` never runs diagnostics, so no caller can receive a 9 whose meaning is -#: in doubt. Nor is 9 the first such overlap: `cairn`'s `EXIT_REFRESH_FAILED` and -#: the reader's `lib/subsystem_read_store.EXIT_UNSTAMPED_READ_STORE` are both 4, -#: across two tools, for the same reason. Globally unique numbers were never the -#: design. -#: -#: 🔴 WHAT THE PER-COMMAND SCOPING DOES NOT COVER IS THE ONLY THING TO PROTECT -#: HERE: a code that a `doctor` invocation can return ALONGSIDE these. TWO more -#: are returned deliberately, so the codes a `doctor` caller may be handed BY -#: DESIGN are 0/1/2/9/10. 🔴 THAT IS A LIST OF WHAT THIS CLI CHOOSES TO RETURN, -#: NOT AN EXHAUSTIVE LIST OF WHAT A CALLER CAN OBSERVE — two earlier drafts -#: claimed exhaustiveness and were wrong, each time for a member nobody had -#: measured (0/2/9/10, then 0/1/2/9/10 with the 120 below missing). Treat any -#: future "the set is" here as a claim needing a measurement: -#: -#: - **2 — usage.** argparse exits 2 on a bad flag for every subcommand -#: (measured: `cairn doctor --bogus-flag` -> 2). -#: - **1 — an uncaught exception.** 1 is the interpreter's own code for any -#: traceback that reaches the top, so this is not one mechanism but a class. -#: One route is reachable BY DESIGN: `cairn`'s lazy `_cairn_doctor()` import -#: is deliberately unguarded at its `cmd_doctor` call site — see the docstring -#: at `cairn:_doctor_epilog`, which states that the help-string import fails -#: soft FOR AN `ImportError` ONLY while `cmd_doctor` still fails LOUDLY — so -#: with `lib/cairn_doctor.py` absent, `cairn doctor` exits 1 with -#: `ModuleNotFoundError` from `cairn:cmd_doctor`. Measured at a second point -#: too: a module present but unparseable raises `SyntaxError`, which is not an -#: `ImportError`, so `_doctor_epilog`'s `except ImportError` does not catch it -#: and it takes `build_parser` — and therefore EVERY verb — down at exit 1 -#: (measured on a tree with this file replaced by `def broken(`: -#: `cairn doctor`, `cairn ls-entries`, `cairn ls-entries --help` and -#: `cairn --help` all 1, all `SyntaxError`; with the file merely ABSENT the -#: same four are 1 / 3 / 0 / 0, and the 3 is the ordinary no-cache read -#: outcome an untouched tree gives). And the `AttributeError` recorded in -#: `AGENTS.md` under `checks.client-resolves-its-lib` was a third. -#: -#: ⚠ AND ONE MORE THE INTERPRETER RETURNS, WHICH IS WHY THE LIST IS NO LONGER -#: CLAIMED EXHAUSTIVE: **120**, CPython's code for a stdout it could not FLUSH at -#: shutdown. `cairn doctor | ` is an ordinary -#: invocation; the departed reader turns the final flush into a `BrokenPipeError`, -#: printed as `Exception ignored in: <_io.TextIOWrapper name='' …>` and -#: exited 120. 🔴 THE MECHANISM IS A PIPE WHOSE READER LEFT, NOT "NO STDOUT", and -#: the two read differently — measured at four points rather than one, because the -#: first draft of this note named the wrong one: `| true` -> **120** (5/5 runs); -#: `--json | true` -> 120; stdout genuinely CLOSED with `1>&-` -> **9** (5/5), -#: because `sys.stdout` is then `None`, nothing is written and so nothing can fail -#: to flush; `| head -1` -> **9** (5/5), because doctor's 2,016 bytes fit the -#: 64 KiB pipe buffer and the write lands before `head` exits — that point would -#: INVERT for an output larger than the buffer, so it is a fact about this output -#: size, not a general one. Nor is it doctor-specific: `cairn --help | true` is -#: 120 as well. 120 stays OUT of the operative instruction below because no doctor -#: code could be chosen to avoid it and it cannot collide with a plausible one; it -#: is recorded so the enumeration above stops reading as a claim about everything -#: a caller can see. -#: -#: 1 and 2 are both clear of this block today because doctor's own codes are -#: 0/9/10, and BOTH must stay clear: a doctor code of 1 would be indistinguishable -#: from a crash, exactly as a doctor code of 2 would be from a usage error. 1 is -#: the more insidious of the two, because it is not any `cairn` constant — nothing -#: in the client's nine codes is 1 — so a set-intersection ledger against the -#: client cannot see it and it is asserted separately. The write codes cannot -#: reach this call site at all. -#: -#: 🔴 SO DO NOT RENUMBER THE 9 TO MAKE IT UNIQUE, and do not read the overlap as -#: licence to add another. Renumbering changes a contract this command PRINTS, to -#: remove a collision that was never a defect. A NEW overlap is safe only if it -#: too is unreachable from any one call site, which is a fact about the dispatcher -#: and not about which numbers happen to look free. -#: `tests/test_cairn_doctor.py` pins the shared set as a ledger: it DISCOVERS both -#: operands — doctor's `EXIT_DOCTOR_*` ∪ `EXIT_LEGEND`, and the client's `EXIT_*` -#: read out of `cairn` — so it goes red when the shared set GROWS from EITHER side -#: and when it SHRINKS. 🔴 IT WAS NOT THAT WHILE IT HAND-LISTED BOTH OPERANDS, and -#: the first version of this sentence called it "the authority on which codes -#: overlap" anyway. Nine client names and three doctor ones were written out, so a -#: TENTH client code colliding with the 10 left the intersection at {0, 9} and the -#: file green at 60 passed — the exact case the failure message advertised -#: catching. What discovery still does not see is named in that file: a code -#: spelled without the `EXIT_`/`EXIT_DOCTOR_` prefix, and — on the client side, -#: which is read by AST — one whose value is computed rather than an integer -#: literal; the second is cross-checked against the exec'd module's own namespace -#: rather than assumed away. It carries a second, separate assertion that 1 is not -#: one of doctor's codes, because the ledger structurally cannot: 1 is not in the -#: client's set, so an `EXIT_DOCTOR_* = 1` leaves the intersection at {0, 9} and -#: the ledger green. -EXIT_DOCTOR_OK = 0 -EXIT_DOCTOR_PROBLEM = 9 -EXIT_DOCTOR_UNMEASURED = 10 - -EXIT_LEGEND: tuple[tuple[int, str], ...] = ( - (EXIT_DOCTOR_OK, "every check measured, and every answer is fine"), - (EXIT_DOCTOR_PROBLEM, "at least one check MEASURED a problem"), - (EXIT_DOCTOR_UNMEASURED, - "no problem measured, but at least one check COULD NOT LOOK — " - "this is not a clean bill of health"), -) - - -def exit_code(checks: Iterable[Check]) -> int: - """PROBLEM outranks UNMEASURED outranks OK. - - 🔴 `NOT-OBSERVABLE` CONTRIBUTES NOTHING, and that is deliberate. It marks a - fact no client can reach, so escalating on it would make this command - non-zero on every healthy run forever — the permanently-red gate - `claude/RULES.md` says trains everyone to click through. - """ - states = {c.state for c in checks} - if PROBLEM in states: - return EXIT_DOCTOR_PROBLEM - if UNMEASURED in states: - return EXIT_DOCTOR_UNMEASURED - return EXIT_DOCTOR_OK - - -_MARKER = {OK: " ", PROBLEM: "🔴", UNMEASURED: "⚠ ", NOT_OBSERVABLE: "· "} - - -def render(checks: list[Check]) -> str: - """The report, plus the exit legend, plus a one-line verdict.""" - width = max((len(c.name) for c in checks), default=0) - lines = [f"{_MARKER[c.state]} {c.name.ljust(width)} {c.state:<14} {c.detail}" - for c in checks] - code = exit_code(checks) - counts = {s: sum(1 for c in checks if c.state == s) for s in STATES} - lines.append("") - lines.append( - "checks: " - + " ".join(f"{s}={counts[s]}" for s in STATES) - + f" -> exit {code}" - ) - lines.append("exit codes: " + "; ".join(f"{n} = {why}" for n, why in EXIT_LEGEND)) - return "\n".join(lines) - - -def to_dict(checks: list[Check]) -> dict: - return { - "checks": [{"name": c.name, "state": c.state, "detail": c.detail} for c in checks], - "counts": {s: sum(1 for c in checks if c.state == s) for s in STATES}, - "exit": exit_code(checks), - "exit_legend": {str(n): why for n, why in EXIT_LEGEND}, - } diff --git a/lib/cairn_instances.py b/lib/cairn_instances.py deleted file mode 100644 index 3ce08250..00000000 --- a/lib/cairn_instances.py +++ /dev/null @@ -1,568 +0,0 @@ -#!/usr/bin/env python3 -"""WHICH INSTANCE does a scope live on, and where is each instance configured? - -A deployment may point one client at more than one cairn. This module owns the -three questions that creates — what is configured, which instance a scope -belongs to, and whether the two agree — and it owns them for a client that -knows NOTHING about who routes where: the scope->alias table is an INPUT (a -file), never a constant in this repository. A public tool that shipped somebody's -taxonomy would be publishing their org chart. - -🔴 AN UNROUTED SCOPE REFUSES. It does not fall back to the first instance, the -default instance, or the one that happens to answer. A default silently -recreates the shape that has already cost entries in this system's history — -writes landing in a store nobody reads, discovered days later by a diagnostic -built for something else. A refusal costs one error message, and it names the -scope so the remedy is a single line in the table. - -🔴 ONE INSTANCE IS NOT ROUTING, AND THAT IS THE WHOLE COMPATIBILITY STORY. -With a single configured instance there is no second place a scope could go, -so an unregistered scope answers with it and NOTHING about the single-instance -client changes — no label, no table, no refusal. The alternative — refusing -until a table exists — would break every existing deployment on upgrade in -exchange for a guarantee nobody needs while there is one store. - -🔴 AND "IS THIS HOST ROUTING?" IS NOT ONE QUESTION, WHICH IS THE CORRECTION -THIS MODULE CARRIES. It used to be, and the single boolean was -`routes is not None or len(instances) > 1` — table presence counted as routing. -That is wrong in both directions on a ONE-instance host that has a table, which -is the state an operator reaches the moment they write one: - - case (ONE instance configured) | what must happen - ----------------------------------------|------------------------------------ - no table at all | resolve to the sole instance - a table, and the scope is NOT in it | resolve to the sole instance - a table entry naming an UNCONFIGURED | REFUSE — the table names where the - alias | scope lives and this host cannot - | reach it - -Rows 2 and 3 need OPPOSITE answers from the same configuration, so no single -`active` flag can decide both: with the old predicate row 2 refused (a scope -nobody had added to the table yet became unreadable), and simply deleting the -`routes is not None` disjunct makes row 3 resolve to the sole instance — a -SILENT MISROUTE, a write landing in a store nobody decided on, which is worse -than the refusal it replaces. So there are two predicates: `multi_instance` -decides what is LABELLED, and `alias_for` consults the TABLE FIRST and falls -back to the sole instance only when the table said nothing at all. - -🔴 THE DEFAULT INSTANCE IS THE EXISTING CONFIG FILE, UNMOVED. `~/.config/ -subsystem-store/env` keeps its name, its contents and its environment-variable -precedence, and becomes the alias `personal`. Additional instances are ADDITIVE -files under `instances/.env` beside it. Nothing migrates; an upgrade -that adds no file changes nothing. - -🔴 THE ENVIRONMENT OVERRIDES THE DEFAULT INSTANCE ONLY. `CAIRN_URL` / -`CAIRN_TOKEN` — and their deprecated `SUBSYSTEM_STORE_*` aliases, which -`env_aliases` resolves — have always pointed the client at a throwaway server, -and every test relies on it. Applying them to EVERY instance would point all of -them at one store — a fan-out that reads N instances and measures one, reporting -agreement it never observed. A non-default alias reads its own file and nothing -else. -""" - -from __future__ import annotations - -import json -import os -from dataclasses import dataclass -from pathlib import Path -from typing import Mapping - -import env_aliases -from subsystem_read_store import DEFAULT_ALIAS, valid_alias - -__all__ = [ - "CONFIG_ENV", - "ROUTES_ENV", - "INSTANCE_DIR_NAME", - "INSTANCE_SUFFIX", - "ROUTES_FILE_NAME", - "Instance", - "Routing", - "RoutingConfigError", - "UnroutedScope", - "config_path", - "discover", - "instance_dir", - "load_routes", - "routes_file", - "routing_for", -] - -#: The environment variable naming the DEFAULT instance's config file. It -#: predates instances and keeps its meaning exactly. `SUBSYSTEM_STORE_CONFIG` -#: still resolves to it through `env_aliases`; this module never spells the old -#: name, which is what keeps the ledger in one place. -CONFIG_ENV = "CAIRN_CONFIG" - -#: The environment variable naming the routing table. Set it and the table is -#: MANDATORY — a missing file is an error, never "routing is off". An operator -#: who named a table meant to use one, and silently ignoring the name is how a -#: typo'd path turns a fail-loud design into a fail-open one. -ROUTES_ENV = "CAIRN_ROUTES" - -#: Additional instances live beside the default config file, one file each. -INSTANCE_DIR_NAME = "instances" -INSTANCE_SUFFIX = ".env" - -#: The table's default name, beside the config file. Absent => no routing. -ROUTES_FILE_NAME = "routes.json" - - -class RoutingConfigError(Exception): - """The instance configuration or the routing table cannot be read. - - Separate from `UnroutedScope` because the remedies differ: this one means a - FILE is wrong (malformed JSON, an alias that cannot be a directory name, two - sources claiming one alias), and no scope is involved. - """ - - -class UnroutedScope(Exception): - """This scope cannot be resolved to an instance, and nothing was guessed. - - 🔴 THE SCOPE IS AN ATTRIBUTE, NOT ONLY A SUBSTRING OF THE MESSAGE. A caller - that has to grep an f-string to learn which scope failed has pinned prose; - the structural fact is carried so a consumer can act on it and a test can - assert it without pinning a sentence. - """ - - def __init__(self, scope: str, detail: str) -> None: - super().__init__(detail) - self.scope = scope - self.detail = detail - - -@dataclass(frozen=True) -class Instance: - """One configured cairn: its alias and the file its URL and token come from. - - 🔴 NO URL AND NO TOKEN HERE. This module enumerates and routes; it never - reads a credential. Keeping the secret out of the object that gets printed, - logged and rendered is what stops it being printed, logged and rendered. - """ - - alias: str - config_path: Path - - @property - def is_default(self) -> bool: - return self.alias == DEFAULT_ALIAS - - -def config_path(env: Mapping[str, str] | None = None) -> Path: - """The DEFAULT instance's config file — `$CAIRN_CONFIG` or the long-standing - `~/.config/subsystem-store/env`.""" - env = os.environ if env is None else env - raw = env_aliases.value(env, CONFIG_ENV).strip() - if raw: - return Path(raw).expanduser() - return Path.home() / ".config" / "subsystem-store" / "env" - - -def instance_dir(env: Mapping[str, str] | None = None) -> Path: - """Where additional instances live: `instances/` beside the config file. - - 🔴 DERIVED FROM THE CONFIG PATH, NOT A SECOND ENVIRONMENT VARIABLE. One - variable moves the whole configuration — which is what a test needs, and - what keeps `$CAIRN_CONFIG` pointing somewhere while the instances - it should sit beside are read from the operator's real home directory. - """ - return config_path(env).parent / INSTANCE_DIR_NAME - - -def routes_file(env: Mapping[str, str] | None = None) -> tuple[Path, bool]: - """`(path, explicitly_configured)` for the routing table. - - The second element is the difference between "the operator named this file" - and "this is where a table would live if there were one". An explicit path - that does not exist is an ERROR; a default path that does not exist means - there is no routing table, which is the ordinary single-instance state. - """ - env = os.environ if env is None else env - raw = env.get(ROUTES_ENV, "").strip() - if raw: - return Path(raw).expanduser(), True - return config_path(env).parent / ROUTES_FILE_NAME, False - - -def load_routes(path: Path) -> dict[str, str]: - """The scope->alias table, as a flat JSON object of strings. - - 🔴 ONE SHAPE, AND EVERYTHING ELSE IS REFUSED. A table is read by a machine - to decide where a durable write lands, so "we accepted something odd and did - our best with it" is the wrong failure mode: a nested object, a list, a - non-string value or a non-object document each raise rather than silently - contributing zero routes. A table that parsed to nothing would leave every - scope unrouted, which LOOKS like a deliberate refusal and is not. - """ - try: - raw = path.read_text(encoding="utf-8") - except OSError as exc: - raise RoutingConfigError(f"the routing table `{path}` could not be read: {exc}") from exc - try: - parsed = json.loads(raw) - except ValueError as exc: - raise RoutingConfigError(f"the routing table `{path}` is not valid JSON: {exc}") from exc - if not isinstance(parsed, dict): - raise RoutingConfigError( - f"the routing table `{path}` must be a JSON object mapping each scope " - f"to an instance alias, e.g. {{\"alpha-notes\": \"personal\"}} — got " - f"{type(parsed).__name__}" - ) - table: dict[str, str] = {} - for scope, alias in parsed.items(): - if not isinstance(alias, str) or not scope: - raise RoutingConfigError( - f"the routing table `{path}` maps scope `{scope}` to " - f"{alias!r}, which is not an instance alias. Every value must be " - f"the alias of a configured instance." - ) - if not valid_alias(alias): - raise RoutingConfigError( - f"the routing table `{path}` maps scope `{scope}` to the alias " - f"`{alias}`, which is not a usable alias. An alias becomes a " - f"directory name under the cache root, so it is lowercase " - f"letters, digits and hyphens only." - ) - table[scope] = alias - return table - - -@dataclass(frozen=True) -class Routing: - """What is configured on this host, and the routing decision it supports.""" - - instances: tuple[Instance, ...] - routes: Mapping[str, str] | None - routes_source: Path | None - - @property - def aliases(self) -> tuple[str, ...]: - return tuple(i.alias for i in self.instances) - - @property - def multi_instance(self) -> bool: - """Is there more than one PLACE on this host an answer could come from? - - 🔴 THE LABELLING PREDICATE, AND IT IS DELIBERATELY NOT THE ROUTING ONE. - Every place the client says WHICH instance it read — the banner label, - `doctor`'s per-instance rows, `ls-entries`' prefix, the `--all-scopes` - fan-out, the caveat's extra clause — asks THIS, so they cannot drift - into disagreeing about whether this host has more than one store. - - 🔴 IT ASKS THE INSTANCE COUNT AND NOT THE TABLE, AND THAT IS THE FIX. - The predicate used to be `routes is not None or len(instances) > 1`, so - writing a routing table on a ONE-instance host switched every label on: - each recall then asserted "with more than one instance configured, an - absence here is also explainable by the scope living on another - instance" — a sentence that is FALSE on that host, printed on every - call, which is precisely the always-false caveat the caveat rewrite - exists to eliminate. A table is a statement about where scopes live, - not about how many stores this machine can reach. - - ⚠ IT IS NOT THE ROUTING DECISION EITHER — see `alias_for`, which - consults the table whatever this returns. A one-instance host with a - table still REFUSES a scope routed to an alias it has no config for. - """ - return len(self.instances) > 1 - - def get(self, alias: str) -> Instance: - for instance in self.instances: - if instance.alias == alias: - return instance - raise RoutingConfigError( - f"no instance `{alias}` is configured on this host " - f"(configured: {', '.join(self.aliases)})" - ) - - def alias_for(self, scope: str) -> str: - """The instance `scope` belongs to, or raise. NEVER a guess. - - 🔴 THE TABLE IS CONSULTED FIRST, WHATEVER `multi_instance` SAYS, AND THE - ORDER IS THE WHOLE POINT. Three cases share one configuration — a - one-instance host with a table — and two of them must answer - DIFFERENTLY, so a single "is this host routing" boolean cannot decide - them. Measured, on a host with ONE instance configured: - - table state for this scope | today | `active = len(instances)>1` - -----------------------------|--------|---------------------------- - (1) no table at all | sole | sole - (2) table, scope ABSENT | sole | sole - (3) table -> UNCONFIGURED | REFUSE | sole <- SILENT MISROUTE - alias | | - - Row 3 is a table explicitly routing a scope to an alias this host has no - config for. Resolving it to the sole instance is a write landing in a - store nobody decided on — the exact failure the refusal exists to - prevent — so it refuses at ONE instance and at many. Rows 1 and 2 are - the opposite: the table said nothing about this scope, and with one - instance there is exactly one answer to "where did that go?", which is - the same reasoning the no-table case has always used. - - The refusals, each reachable by an input no earlier one rejects: - 1. a table naming an alias this host has no config for (any count) - 2. two or more instances and no table -> nothing can decide - 3. two or more instances and a table without `scope` - - 🔴 THE COMPARISON IS EXACT. The table's keys are scope names exactly as - `entry_shape.derive_scope` produces them. A case or spelling mismatch - therefore falls through to the rows above rather than resolving to - something adjacent, which is the safe direction for a value that decides - where a write lands. - """ - alias = None if self.routes is None else self.routes.get(scope) - if alias is not None: - if alias not in self.aliases: - raise UnroutedScope( - scope, - f"the routing table `{self.routes_source}` routes scope " - f"`{scope}` to instance `{alias}`, which is not configured on " - f"this host (configured: {', '.join(self.aliases)}). REFUSING " - f"rather than falling back: the table names where this scope " - f"lives, and this host cannot reach it. Add " - f"`{instance_dir()}/{alias}{INSTANCE_SUFFIX}`.", - ) - return alias - # The table decided NOTHING about this scope — it has no entry, or there - # is no table. With one instance that has exactly one answer. - if not self.multi_instance: - return DEFAULT_ALIAS - if self.routes is None: - raise UnroutedScope( - scope, - f"{len(self.instances)} instances are configured " - f"({', '.join(self.aliases)}) and no routing table says which one " - f"scope `{scope}` belongs to. REFUSING rather than picking one: a " - f"write to the wrong instance lands in a store nobody reads. " - f"Write a scope->alias table to " - f"`{routes_file()[0]}`, or set ${ROUTES_ENV} to one.", - ) - raise UnroutedScope( - scope, - f"scope `{scope}` is not in the routing table " - f"`{self.routes_source}`. REFUSING rather than defaulting to an " - f"instance: an unregistered scope is a scope nobody decided about, " - f"and guessing is how a write lands in a store nobody reads. Add " - f"`\"{scope}\": \"\"` to that table (configured instances: " - f"{', '.join(self.aliases)}).", - ) - - def check(self, scopes: Mapping[str, str] | set[str] | tuple[str, ...] | list[str] - ) -> tuple[tuple[str, ...], tuple[str, ...]]: - """Grade this host's routing table against reality, IN BOTH DIRECTIONS. - - Returns `(problems, notes)`, each a tuple of strings in a stable order. - A PROBLEM is a defect this check can actually decide, and it is what - takes `routes --check` to exit 11. A NOTE is something worth printing - that the available evidence CANNOT decide; it never changes the exit - code. Callers must not read a truthy/falsy bare return, which is why - both halves are strings rather than a bool. - - 🔴 BOTH DIRECTIONS, BECAUSE EACH MISSES A DIFFERENT DEFECT. A scope with - no entry is a scope whose next write REFUSES — annoying but loud. An - entry naming a scope that does not exist is the silent one: it reads as - coverage, survives the scope being renamed or retired, and is exactly - what a table accumulates when it is edited by hand. A one-way check - would report a clean table over either. - - A third direction is graded here too because it is the same class: an - entry naming an alias no instance provides. 🔴 IT IS NOT RE-DERIVED — it - ASKS `alias_for`, which already owns that refusal. This method used to - recompute `alias not in aliases` from the same two inputs, so the rule - had two implementations and the second one could have drifted without - any test noticing; one rule, one place. - - 🔴 AND DIRECTION TWO IS A **NOTE**, NOT A PROBLEM, BECAUSE THE SCOPE SET - IT SUBTRACTS FROM CANNOT SEE AN EMPTY SCOPE. The caller's scope set is a - cache's DIRECTORY LISTING, and a snapshot ships entry FILES — no - directory member — so a scope holding no entries is absent from the - cache whether it has been retired, pre-registered before its first - write, or simply pruned back to nothing. Measured, one instance, a table - naming `hollow-set`: - - routes --check rc=11 "…exists on no configured instance" - recall --scope hollow-set rc=0 "scope-empty — reached the store" - - Grading that at exit 11 makes the check unusable as the TWO-WAY REGISTRY - it exists to be — a table is supposed to name a scope BEFORE the first - write lands — and the remedy the sentence implies (delete the line) is - actively wrong: with more than one instance the next write to that scope - then REFUSES. So the observation is kept and the verdict is dropped. - - ⚠ THIS COSTS REAL TEETH AND SAYING SO IS THE POINT: a genuinely stale - entry now reads as a note. **Closing condition** — the discriminator - exists, it is just not in the snapshot: the SERVER reads the real store, - where `subsystem_resolver.build_index` registers a scope directory it - found empty (`extra_scopes`), so `GET /api/v1/recall/` answers - `scope-empty` - for a live-but-empty scope and `scope-absent` for one that does not - exist. When this check probes the ROUTED instance per table entry and - both clients do it identically with a parity row over it, direction two - can become a problem again. It is not done here because it turns a - two-request command into an O(table) one and that is a separate decision - from the one this fixes. - """ - if self.routes is None: - raise RoutingConfigError( - "there is no routing table on this host to grade. A caller that " - "reached here read an absent table as an empty one, which would " - "report every scope as unrouted." - ) - scope_set = set(scopes) - problems: list[str] = [] - notes: list[str] = [] - # 🔴 DIRECTION ONE ASKS THE RESOLVER, IT DOES NOT SUBTRACT KEY SETS. The - # finding this raises is "a write to it will REFUSE", which is a claim - # about what `alias_for` does — and on a ONE-instance host it does not - # refuse: an unnamed scope resolves to the sole instance. Grading by the - # table's keys alone printed that refusal warning on every unnamed scope - # of every one-instance host, which is a confident statement about - # behaviour that will not happen. - for scope in sorted(scope_set - set(self.routes)): - try: - self.alias_for(scope) - except UnroutedScope: - problems.append( - f"scope `{scope}` exists but the routing table does not name " - f"it — a write to it will REFUSE" - ) - # ⚠ DIRECTION TWO IS NOT A RESOLVER QUESTION, DELIBERATELY. `alias_for` - # resolves a stale entry perfectly well — it names a configured alias — - # so asking it here would grade this direction clean. What the resolver - # cannot see is whether the scope EXISTS; what the SCOPE SET cannot see - # is whether it exists but holds nothing. Hence a NOTE: see the - # docstring for the measurement and the closing condition. - for scope in sorted(set(self.routes) - scope_set): - notes.append( - f"the routing table names scope `{scope}`, which holds no entry " - f"on any configured instance — a stale entry reads as coverage, " - f"but a scope pre-registered before its first write or pruned " - f"back to nothing looks IDENTICAL here, because a snapshot ships " - f"entry files and not directories. Check it rather than deleting " - f"the line: with more than one instance, deleting it makes the " - f"next write to `{scope}` REFUSE." - ) - for scope in sorted(self.routes): - try: - self.alias_for(scope) - except UnroutedScope: - # 🔴 THE ONLY REFUSAL `alias_for` CAN RAISE FOR A SCOPE THE TABLE - # NAMES is the unconfigured-alias one: the other two arms are - # reached only when the table said nothing about the scope, and - # this loop iterates the table's own keys. The short line here is - # the FINDING's wording; the PREDICATE is `alias_for`'s. - problems.append( - f"the routing table routes `{scope}` to instance " - f"`{self.routes[scope]}`, which is not configured on this host" - ) - return tuple(problems), tuple(notes) - - -def discover(env: Mapping[str, str] | None = None) -> Routing: - """Everything configured on this host: instances first, then the table. - - 🔴 THE DEFAULT INSTANCE ALWAYS EXISTS, FILE OR NO FILE. `load_config` has - always accepted a URL and token from the environment with no file at all, - and every test in this repository does exactly that. Making the default - instance conditional on a file would have deleted that path — the client - would have reported "no instances configured" on a host that is perfectly - well configured, which is a statement about a file rather than about the - store. - """ - env = os.environ if env is None else env - instances = [Instance(alias=DEFAULT_ALIAS, config_path=config_path(env))] - - directory = instance_dir(env) - extra: list[Instance] = [] - try: - entries = sorted(directory.iterdir()) - except FileNotFoundError: - entries = [] - except OSError as exc: - raise RoutingConfigError( - f"the instance directory `{directory}` could not be read: {exc}. It is " - f"not the same fact as 'no extra instances are configured', so this " - f"refuses rather than reporting one instance." - ) from exc - for path in entries: - if not path.name.endswith(INSTANCE_SUFFIX) or path.is_dir(): - continue - # 🔴 AN EDITOR LOCK FILE IS NOT A FILE THE OPERATOR WROTE, AND THE - # REFUSAL BELOW TOOK EVERY VERB TO EXIT 11 WHILE ONE WAS OPEN. Emacs' - # lock file for `secondary.env` is `.#secondary.env`: it ends in `.env`, - # its stem `.#secondary` is not a usable alias, and it is a DANGLING - # SYMLINK, so `is_dir()` is False and it reached the hard error — so - # every `cairn` invocation on that host refused to run until the buffer - # was closed. The snapshot builder already learned this one suffix over - # (`.#entry.md` 503'd the whole store); the rule there is the rule - # here — NAME rules are separate from TYPE rules. - # - # 🔴 `.#`, NOT `.` — AND THE WIDER PREDICATE WAS SHIPPED AND MEASURED - # WRONG. Skipping every dotted name also skipped `instances/.env`, - # whose stem is the EMPTY string: an operator who wrote that file got - # `instances: personal` at exit 0 and no message anywhere, which is - # precisely the outcome the refusal below exists to prevent. `.#` is - # the only in-suffix name a TOOL writes (a vim swapfile is - # `.secondary.env.swp` and an Emacs autosave is `#secondary.env#` — - # both fail the `.env` suffix test above and never reach here), so - # every other dotted name is one a human could have chosen and stays - # an ERROR. The refusal's stated intent — "a file the operator wrote - # and would otherwise get no message about" — is what picks the - # boundary, and the `.` version did not honour it. - if path.name.startswith(".#"): - continue - alias = path.name[: -len(INSTANCE_SUFFIX)] - # 🔴 A FILE THAT CANNOT BE AN INSTANCE IS AN ERROR, NOT A SKIP. Skipping - # it would leave the operator with a file they wrote, a store they think - # is configured, and no message anywhere — and the scopes they routed to - # it would refuse later, naming the ALIAS, which points at the table - # rather than at the file that was ignored. - if not valid_alias(alias) or alias == DEFAULT_ALIAS: - raise RoutingConfigError( - f"`{path}` does not name a usable instance alias. An alias becomes " - f"a directory name under the cache root, so it is lowercase " - f"letters, digits and hyphens only, and `{DEFAULT_ALIAS}` is " - f"reserved for the default instance's own config file — one alias " - f"with two config sources is a store nobody can point at." - ) - extra.append(Instance(alias=alias, config_path=path)) - - instances.extend(extra) - - path, explicit = routes_file(env) - routes: dict[str, str] | None = None - source: Path | None = None - if path.exists(): - routes = load_routes(path) - source = path - elif explicit: - raise RoutingConfigError( - f"${ROUTES_ENV} names `{path}`, which does not exist. A configured " - f"table that cannot be read is an error, not an absence of routing — " - f"treating it as 'no table' would silently turn a fail-loud " - f"configuration into a fail-open one." - ) - return Routing(instances=tuple(instances), routes=routes, routes_source=source) - - -def routing_for( - routes: Mapping[str, str], - aliases: tuple[str, ...] | set[str] | list[str], -) -> Routing: - """A `Routing` over an alias list and a table, with no filesystem involved. - - 🔴 IT EXISTS SO THE GRADER AND THE RESOLVER CANNOT BE TESTED SEPARATELY. - `Routing.check` asks `Routing.alias_for` for the unconfigured-alias - direction, so a test that wanted to grade a table without discovering a host - would otherwise have had to re-implement one of them. The config paths are - the placeholders they are because nothing on either path reads them: an - `Instance` carries an alias and the file its credentials come from, and - routing never opens that file. - """ - return Routing( - instances=tuple(Instance(alias=a, config_path=Path(os.devnull)) - for a in sorted(set(aliases))), - routes=dict(routes), - routes_source=None, - ) diff --git a/lib/entry_shape.py b/lib/entry_shape.py deleted file mode 100644 index ec32a9aa..00000000 --- a/lib/entry_shape.py +++ /dev/null @@ -1,1414 +0,0 @@ -#!/usr/bin/env python3 -"""The vocabulary a cairn READER and any WRITER must agree on. - -🔴 THIS MODULE EXISTS SO THERE IS ONE SPELLING, NOT TWO. A reader and a writer -that disagree about which scope directory they mean is a silent, total failure: -the writer accrues entries under one name and the reader surfaces an empty scope -under another, which renders as "nothing recorded yet" and is indistinguishable -from the ordinary case. Everything here is imported by both halves rather than -re-typed in each. - -It holds the scope-derivation rule, the per-host caveat, the entry headings, and -the error taxonomy. It deliberately holds no I/O policy and no store layout: a -writer decides where it writes, and this module only decides what things are -called. -""" -from __future__ import annotations - -import os -import re -import subprocess -from dataclasses import dataclass -from pathlib import Path -from typing import Iterable, Sequence - -from host_identity import this_host -from subsystem_resolver import ( - NUANCE_HEADING, - POINTERS_HEADING, - TAKE, - UNREACHABLE_MARKER, - WHAT_HEADING, - action_for, - classify_path, - extract_sections, - line_mentions_marker, - line_openness, - normalize_ref, - parse_journal_bullets, - scan_headings, -) -# 🔴 THE LOADER'S OWN ACTION TABLE, IMPORTED PRIVATE RATHER THAN RE-DECIDED — see -# `_nuance_body`. The advisories must read EXACTLY the set of paths `load_index` -# reads: narrower and they print a zero over a file the loader counted, wider and -# they `open()` a fifo the loader refused. Either way the second copy of the rule -# is what drifts, so there is no second copy. -from subsystem_resolver import _LOADER_ENTRY_ACTIONS # noqa: E402 -# 🔴 THE READER'S OWN FENCE PREDICATE, IMPORTED PRIVATE RATHER THAN RE-SPELLED. -# `_is_fence` knows both ``` and ~~~; a hand-spelled copy that knew only the -# first would report a ~~~-fenced sample line as lost content, and the -# scanners below would then disagree with `parse_journal_bullets`, which is the -# function that decides what a reader can actually see. Importing an underscore -# name across modules is deliberate here: a second copy of this predicate is the -# duplicated rule, and the Go port makes the same call (`store.IsFence`). -from subsystem_resolver import _is_fence # noqa: E402 - -__all__ = [ - "CairnError", "GitError", "RepoPathMissingError", "StoreMissingError", - "BULLET_TEXT_MAX", "SHAPE_HEADINGS", "STORE_IS_PER_HOST", - "STORE_IS_ONE_INSTANCE", - "TAG_VOCABULARY", "tag_outside_vocabulary", - "DROPPED_LINE", "UNREACHABLE_MARKER", - "SHAPE_ABSENT", "SHAPE_RENAMED", "SHAPE_DUPLICATED", "SHAPE_EMPTY", - "SHAPE_INVENTORY_SHOWN", - "DroppedLineFinding", "UnreachableMarkerFinding", "ShapeFinding", "OpenAction", - "derive_scope", "repo_path_missing_message", "scope_for_repo", - "store_caveat", "store_host", "store_host_line", - "line_carries_marker", "scan_dropped_lines", "scan_unreachable_markers", - "scan_entry_shape", "scan_open_actions", - "validation_advisory_lines", -] - - -# -------------------------------------------------------------------------- -# Errors -# -------------------------------------------------------------------------- - -class CairnError(Exception): - """Base for every error this module raises.""" - - -#: Kept as an alias because the writer half historically raised `TouchError` and -#: callers match on the class. Renaming without an alias would be a silent -#: behaviour change for any `except` clause naming the old spelling. -TouchError = CairnError - - -class GitError(CairnError): - """A git invocation failed. Sentinel: 'git command failed'. - - 🔴 `stderr` IS CARRIED AS AN ATTRIBUTE, NOT ONLY INSIDE THE MESSAGE, so a - WRAPPING error can quote git's own words WITHOUT embedding this class's - sentinel in its own text. Without that, a wrapper's message carries two - sentinels at once and "which guard fired" stops being measurable. - """ - - def __init__(self, message: str, *, stderr: str = "") -> None: - super().__init__(message) - self.stderr = stderr - - -class StoreMissingError(CairnError): - """The store root does not exist. Sentinel: 'store root not found'.""" - - -class RepoPathMissingError(CairnError): - """`--repo` names something that is not a directory. - - Sentinels: 'repo path does not exist' when nothing is there, 'repo path is - not a directory' when something is. TWO, because they are two mistakes with - two next moves — see `repo_path_missing_message`. - - 🔴 ITS OWN SENTINEL, NOT `git command failed`. "The repo path does not exist" - is a first-class READING the caller can act on, while `GitError`'s sentinel - is a true statement about the subprocess and a useless one about the - argument. `--repo` takes a PATH resolved against the cwd, so a bare repo NAME - silently becomes `$PWD/` — and a raw git error names neither that rule - nor the way out. It matters more than wording usually does: this is the - store's primary read surface, and a prescribed first command that answers - with a git internals dump is how a store goes unread. - """ - - -# -------------------------------------------------------------------------- -# Entry shape -# -------------------------------------------------------------------------- - -#: The two headings every entry is built from. Re-exported here so a writer does -#: not import them from the renderer, and pinned as a tuple so a reader can -#: assert the set rather than two separate strings. -SHAPE_HEADINGS: tuple[str, ...] = (POINTERS_HEADING, NUANCE_HEADING) - -#: The longest `text` an append may carry, in characters. -#: -#: 🔴 WHAT THIS IS **NOT**, BECAUSE BOTH READINGS ARE AVAILABLE AND BOTH ARE -#: WRONG — AND THE VALUE SAT HERE UNJUSTIFIED LONG ENOUGH THAT "RAISE IT" READ AS -#: THE OBVIOUS FIX: -#: -#: * NOT an integrity constraint. Nothing about a long `text` can corrupt the -#: bullet or its attribution trailer; that hazard is one bullet becoming two, -#: or a trailer that reads as somebody else's, and it is closed by the -#: line-break and character-category predicates in the server — measured -#: failures, each with its own comment. Length breaks nothing. -#: * NOT a resource bound. The request body is already capped (1 MiB) and -#: bounded in time by the server's drain deadline, and this value is three -#: orders of magnitude below that cap. Deleting it would not widen the -#: server's exposure by one byte. -#: * NOT a bound on what a READ costs, which is the plausible one. A recall -#: prints an entry's nuance bullets in FULL and the bullet COUNT is STILL -#: uncapped — re-measured on one live store of 331 entries: median 5, p90 21, -#: **one entry holds 151** — so worst-case read cost is count × this value and -#: the count is the free variable. Capping the text cannot bound a product -#: whose other factor is unbounded. -#: ⚠ THAT FREE VARIABLE IS NOW SURFACED BUT STILL NOT BOUND, AND THE -#: DISTINCTION IS THE WHOLE POINT. `subsystem_recall.NUANCE_BULLET_CEILING` -#: (30) renders an ADVISORY index badge on an entry over it — it refuses -#: nothing, rewrites nothing and caps nothing, so every sentence above stays -#: true. What changed is only that a reader can SEE the count is extreme; the -#: product is as unbounded as it was. The earlier `111` is kept nowhere: it -#: was a measurement of the same class and the store grew past it, which is -#: itself the argument against treating either number as a bound. -#: -#: 🔴 WHAT IT IS: an EDITORIAL tripwire on the tail, and the number is the p99 of -#: the corpus the store already holds. Measured over 2,211 dated bullets: median -#: 629, p90 1,418, p95 1,746, **p99 2,049**, longest 4,015. So this value fires -#: on roughly the densest 1% and on nothing else, and what it says to a writer is -#: "a bullet this long is a document, and a document belongs in an entry's prose -#: or its own entry, not in one line of work-history". That is a curation -#: judgement rather than a safety property — which is exactly why it has to be -#: WRITTEN DOWN as one. An unexplained constant invites being raised to a second -#: unexplained constant. -#: -#: ⚠ THE UNIT IS THE CALLER'S `text`, AND MEASURING THE STORED BULLET INSTEAD -#: OVERSTATES THE TAIL BY ~2×. The server prepends `- : ` and appends the -#: attribution trailer, so a stored line is longer than the `text` that produced -#: it: over this same corpus, 27 bullets (1.2%) exceed 2,000 characters measured -#: as `text`, against 48 (2.2%) measured as stored bytes. A reading of "how many -#: existing bullets would this cap reject" must use the former; the latter counts -#: characters no caller ever sent. -#: -#: Existing over-cap bullets are GRANDFATHERED, deliberately and permanently: -#: this value gates WRITES only, nothing in the API rewrites a bullet that is -#: already stored, and those bullets are the densest records in the store. -#: Shortening them to satisfy a constant would be the cap deciding the content. -#: -#: To justify a DIFFERENT number, the thing to measure is not the corpus again — -#: it is whether a reader's comprehension actually falls off somewhere, or a -#: per-entry read budget with the bullet count capped alongside. Re-measuring the -#: same distribution can only ever re-derive a percentile. -#: ⚠ HALF OF THAT SECOND OPTION NOW HAS A MEASUREMENT AND THE OTHER HALF DOES -#: NOT. The bullet-count distribution is measured, and the cost curve it implies -#: is written at `subsystem_recall.NUANCE_BULLET_CEILING` / `report.NuanceBulletCeiling` -#: — read it there rather than re-deriving it. What is still unmeasured is the -#: READ BUDGET itself: nothing bounds a digest, which prints the whole index plus -#: ONE featured body in full, and on a real store that single body measured 97.6% -#: of the read. So "a per-entry read budget with the bullet count capped -#: alongside" remains OPEN as stated; only the distribution behind it is settled. -BULLET_TEXT_MAX = 2000 - -#: The CLOSED set of `tags:` front-matter values a WRITE may land. The axis is the -#: technical DOMAIN an entry belongs to, which is deliberately a different question -#: from `KINDS` (service/process/org/doc — what SHAPE of thing the entry describes); -#: an entry carries one value from each, and neither set refines the other. -#: -#: 🔴 IT WAS FOUR TERMS FOR ONE ROUND, AND THE FOURTH FALSIFIED THE SENTENCE ABOVE. -#: `client-work` shipped in the first draft beside these three and is REMOVED: `infra`, -#: `product` and `tooling` all answer "what KIND of work is this", while `client-work` -#: answers "WHO is it for" — a second axis. Under the one-tag-per-entry rule -#: (`entry_has_tag`'s scalar operand) a set mixing two axes makes both unassertable, -#: which is the identical objection this repository already records against putting the -#: category axis into `kind:`. The "who" question was also already answered elsewhere: -#: the SCOPE name carries it, so the fourth term largely restated the directory an entry -#: lives in. Dropping a term is the direction that can refuse a write somebody used to -#: be able to make, so it was taken on an operator decision with the live store -#: re-tagged first. -#: -#: 🔴 IT LIVES IN THE WRITER'S MODULE AND NOT IN `subsystem_resolver`, AND THE REASON -#: IS A MEASURED OUTAGE RATHER THAN TASTE. `SubsystemEntry.from_mapping` is the READER. -#: A refusal there makes the entry MALFORMED, and a malformed entry is out of the -#: index, out of `--ref`, out of `--search` AND UNWRITABLE — every write route resolves -#: its target THROUGH the index, so `PUT` and `POST .../bullets` answer 404 for it. A -#: vocabulary check in the reader would therefore take every entry already carrying an -#: off-vocabulary tag and make it unreadable and unrepairable in the same stroke: a -#: store-wide outage caused by the guard, not by the data. -#: -#: 🔴 AND THE SPLIT IS ENFORCED BY THE IMPORT GRAPH RATHER THAN BY THIS COMMENT. This -#: module imports `subsystem_resolver` at module scope, so a back-import is a CYCLE and -#: the reader cannot reach this tuple. That is the whole reason it is not a sibling of -#: `KINDS`: a constant the reader can see is a constant a later edit can wire into -#: `from_mapping`, and the refusal that edit produces is the outage above. -#: -#: ⚠ SORTED, AND THAT IS PART OF THE REFUSAL'S CONTRACT RATHER THAN TIDINESS. The -#: message joins this tuple with `|`; `internal/write`'s `tagVocabulary` joins its own -#: slice the same way; `tests/conformance/` compares the two servers' response bytes -#: for a `PUT` carrying an off-vocabulary tag. Reordering or extending one side alone is -#: a RED corpus, not a review comment — `tests/test_tag_vocabulary.py` is the cheaper -#: red that says which side moved. -TAG_VOCABULARY: tuple[str, ...] = ("infra", "product", "tooling") - - -def tag_outside_vocabulary(tags: "Sequence[str]") -> str | None: - """The FIRST tag not in `TAG_VOCABULARY`, or `None` if every tag is in it. - - 🔴 IT TAKES THE FOLDED SET, NEVER THE RAW FRONT MATTER, so `tags: [Infra]` and - `tags: [infra]` are the same write. `SubsystemEntry.from_mapping` has already - lowercased, folded through `normalize_ref`, deduped and SORTED by the time this - sees it — which is also what makes "the first offender" deterministic: one body - cannot name one tag on this run and a different one on the next, and the two - servers handed one body name the same tag. There is no separate operand normaliser - here for the same reason `entry_has_tag` has none: one fold, applied once, on the - side that owns the spelling. - - ⚠ ONE TAG REPORTED, NOT THE SET. An operator fixes the front matter one line at a - time and the next write re-runs this check, so a list adds bytes to the refusal - without adding a decision to it. - """ - for tag in tags: - if tag not in TAG_VOCABULARY: - return tag - return None - -#: 🔴 PRINTED UNDER EVERY `store:` LINE, AND IT IS LOAD-BEARING. The CACHE is -#: per-host: two machines can hold the same scope with different entries in it -#: at any given instant, because each converges on the hosted store only when -#: `cairn sync` runs there. A verdict printed without naming the host it read is -#: therefore not a smaller claim than the truth — it is a different, false one -#: ("the store has no X" instead of "this disk has no X, as of its last sync"). -#: -#: 🔴 THE FIRST CLAUSE USED TO READ "PER-HOST AND UNREPLICATED", AND THAT IS THE -#: DEFECT THIS WORDING EXISTS TO CORRECT. Since the Cairn cutover the hosted pod -#: is the canonical datastore and `~/.cache/subsystem-store` is a SYNCED -#: READ-THROUGH CACHE of it, so content written on one machine does reach the -#: other. Observed, not inferred from config: within one session that wrote -#: nothing, the pod's own snapshot moved `entry-files=232` -> `239` between two -#: reads about an hour apart. "Unreplicated" told readers an absence here was an -#: absence everywhere, and that false sentence propagated into a downstream -#: handoff doc before it was caught. -#: -#: The SECOND clause is untouched and still exactly true: the reader is offline -#: against the local cache and contacts no pod and no peer. What bounds it is -#: FRESHNESS, not isolation — an entry written elsewhere and not yet synced here -#: is invisible, and that is the honest caveat to print. -#: -#: 🔴 THE MULTI-INSTANCE CASE IS NOW HANDLED, AND IT IS HANDLED BY -#: `store_caveat`, NOT BY EDITING THIS STRING. The warning that used to sit here -#: said "whoever adds multi-instance routing must rewrite this string in the -#: same change", and the FIRST half of that is right: with several instances -#: configured an absence is also explainable by "that scope lives on another -#: instance", and a reader told only that the cache is per-host draws the wrong -#: conclusion. The second half — rewrite THIS constant — is what the code -#: measured wrong, and the reason is worth keeping because it is not obvious: -#: -#: * this sentence is BYTE-MIRRORED across the tree, and the count is bigger -#: than it looks. Enumerated over `git ls-files` at `38b358d`: **25 files, -#: 92 occurrences** — the Go port (`internal/hostid/hostid.go`), the reader -#: fixture the Go renderer is compared against -#: (`internal/report/testdata/reader_fixtures.json`, 64 of those -#: occurrences), **20 of the 98** `tests/conformance/golden/*.json` (24), -#: this file, `server/README.md` and `tests/test_subsystem_recall.py`. Two -#: of those are regenerate-and-diff gates and one is prose in an operator -#: README, which no gate covers at all. -#: -#: ⚠ THIS COMMENT SAID "a four-place change" AND THAT WAS WRONG BY 2×, in -#: the direction that makes the change look cheap: it counted the four -#: mirror KINDS and read as a count of SITES. Re-derive rather than trusting -#: the number — it moves whenever a golden is regenerated: -#: git ls-files | xargs grep -c 'PER-HOST CACHE' 2>/dev/null | grep -v ':0$' -#: (use a real `grep` binary; a `.gitignore`-aware wrapper is blind to -#: generated trees, and `git ls-files` is what makes the population the -#: TRACKED one rather than whatever is on disk); -#: * and it would change the bytes of every SINGLE-instance recall, on every -#: host, to warn about a second instance that does not exist there. -#: -#: So the caveat became a FUNCTION of the instance context: unchanged where -#: there is one instance (the server, the goldens, every existing host), and -#: extended — at the point of rendering — where there is more than one. The -#: clause below is the extension. -STORE_IS_PER_HOST = ( - "the store is read through a PER-HOST CACHE, only as fresh as its last sync; " - "this run read THIS machine's disk and consulted no other" -) - -#: The clause the caveat gains when this host is configured with more than one -#: instance. `{instance}` is the alias this run read. -#: -#: 🔴 IT NAMES THE INSTANCE, NOT JUST THE FACT OF ROUTING. "several instances -#: exist" leaves the reader with the same question they started with; the alias -#: is what makes an absence actionable — it says which store was consulted, so -#: "look on the other one" is a command they can type. -STORE_IS_ONE_INSTANCE = ( - "and this run read the `{instance}` instance ONLY — with more than one " - "instance configured, an absence here is also explainable by the scope " - "living on another instance, so it is NOT an absence from the fleet" -) - - -def store_host() -> str: - """THIS machine's identity — the ONE call site of `host_identity.this_host`. - - 🔴 A SINGLE SEAM FOR EVERY CONSUMER. Callers import THIS rather than - `this_host` itself, so the name is looked up in this module's globals - wherever it is called from: one injection point makes reader and writer - agree, and a test needing byte-stable output patches one thing instead of - two that can drift apart. - """ - return this_host() - - -def store_caveat(instance: str | None = None) -> str: - """The per-host caveat, extended when this host reads more than one instance. - - 🔴 `None` IS THE SINGLE-INSTANCE CASE AND MUST STAY BYTE-IDENTICAL. The - server renders with no instance context, and so does every client on a host - with one instance configured; both produce exactly the sentence this - module's readers, its Go port and two generated corpora already agree on. - A caller passes an alias only when there IS more than one place the answer - could have come from. - """ - if instance is None: - return STORE_IS_PER_HOST - return f"{STORE_IS_PER_HOST}, {STORE_IS_ONE_INSTANCE.format(instance=instance)}" - - -def store_host_line(indent: str = " ", *, instance: str | None = None) -> str: - """`host: ()` — printed under every `store:` line.""" - return f"{indent}host: {store_host()} ({store_caveat(instance)})" - - -# -------------------------------------------------------------------------- -# Scope derivation -# -------------------------------------------------------------------------- - -def _git(repo: Path, args: Sequence[str]) -> str: - argv = ["git", "-C", str(repo), *args] - env = dict(os.environ) - # Read-only invocations must not take the index lock: another process in the - # same checkout is a normal case, and a helper that can block someone else's - # commit is not read-only in the way that matters. - env["GIT_OPTIONAL_LOCKS"] = "0" - proc = subprocess.run(argv, capture_output=True, text=True, env=env) - if proc.returncode != 0: - raise GitError( - f"git command failed ({' '.join(argv)}): exit {proc.returncode}: " - f"{proc.stderr.strip() or '(no stderr)'}", - stderr=proc.stderr.strip(), - ) - return proc.stdout - - -def _toplevel(repo: str | Path) -> Path: - """The repo ROOT for a directory that may be anywhere inside it. Runs git. - - 🔴 ONE FRAME, ONE CALL SITE. Open-coding this is how two callers end up with - two different path frames in one path set: `diff`/`diff-tree` are always - repo-root-relative while `ls-files --others` is cwd-relative AND cwd-scoped, - so a caller passing a subdirectory gets components both manufactured and lost. - """ - return Path(_git(Path(repo), ["rev-parse", "--show-toplevel"]).strip()) - - -def derive_scope(repo_root: str | Path, git_common_dir: str | Path) -> str: - """The store scope for a repo, normalized. Worktree-stable. - - `git_common_dir` is `git rev-parse --path-format=absolute --git-common-dir`: - for BOTH a base clone and any worktree of it that is the base clone's `.git`, - so its parent is the repo everyone means. `--show-toplevel` is not used for - this because in a worktree it is the worktree's own directory. - - Fallback: when the common dir is not literally named `.git` — a bare repo, or - a submodule whose common dir is `/.git/modules/` — the parent - basename would be meaningless (`modules`), so the repo root's basename is - used instead. Stated because the fallback is otherwise silent. - """ - common = Path(git_common_dir) - if common.name == ".git": - return normalize_ref(common.parent.name) - return normalize_ref(Path(repo_root).name) - - -def repo_path_missing_message( - given: str | Path | None, - resolved: str | Path, - *, - store_root: str | Path | None = None, -) -> str: - """The ONE spelling of "that `--repo` value is not a directory". READ-ONLY. - - 🔴 ONE PLACE, EVERY CLI — the same reason the scope RULE lives in one - function: a reader and a writer that disagree here send two operators to two - different remedies for one mistake. - - `given` is the RAW value the caller typed and `resolved` is what it became. - Both are printed when they differ, because the cwd-join is the whole defect: - seeing only the resolved path leaves "where did that prefix come from?" - unanswered, and that is the question the reader actually has. `given` is None - for internal callers that never had a raw string. - """ - given_s = str(given) if given is not None else str(resolved) - resolved_s = str(resolved) - # 🔴 TWO SPELLINGS, because they are two different mistakes. A path that is - # absent and a path that exists as a FILE need different next moves, and - # telling someone their `notes.md` "does not exist" while they are looking at - # it is the kind of confidently-wrong line that makes a reader distrust the - # rest of the message. - lead = ( - "repo path does not exist" if not Path(resolved_s).exists() - else "repo path is not a directory" - ) - # 🔴 THE PARENTHETICAL IS ABOUT A *RELATIVE* INPUT — not about the two strings - # merely differing. They also differ when an ABSOLUTE path resolves through a - # SYMLINK, and telling that caller their absolute path "is resolved against - # the current directory" is a false statement in the one message whose entire - # job is to be accurate about their mistake. - joined_from_cwd = not Path(given_s).is_absolute() - if given_s == resolved_s: - head = f"{lead}: '{resolved_s}'." - elif joined_from_cwd: - head = ( - f"{lead}: '{given_s}' → '{resolved_s}' " - f"(a bare name is resolved against the current directory)." - ) - else: - head = f"{lead}: '{given_s}' → '{resolved_s}'." - remedy = ( - "--repo takes a PATH, not a repo NAME. Pass an absolute path, or " - "--scope , which names the store directory directly and runs no " - "git at all." - ) - hint = "" - if store_root is not None: - candidate = normalize_ref(Path(given_s).name) - if (Path(store_root) / candidate).is_dir(): - hint = f" Did you mean --scope {candidate}?" - return f"{head} {remedy}{hint}" - - -def scope_for_repo( - repo: str | Path, - *, - store_root: str | Path | None = None, - given: str | Path | None = None, -) -> str: - """Ask git where `repo` really lives, then `derive_scope` it. Runs git. - - 🔴 ONE SCOPE-DERIVATION CALL SITE, not two. The READ half and any WRITE half - need exactly the same answer; see this module's docstring for what disagreeing - costs. - - 🔴 THE NON-DIRECTORY CASE IS CHECKED BEFORE GIT RUNS, and belongs HERE for the - same reason the scope rule does — this is the one seam both halves cross, so a - guard placed in the reader alone would leave the writer answering the identical - mistake with an identical git dump. `store_root` and `given` exist only for the - message: `given` carries the raw pre-`resolve()` string so the cwd-join is - visible, and `store_root` is what lets the refusal name the scope the caller - probably wanted. Both default to None so every call site keeps working, at a - slightly poorer message rather than a TypeError. - """ - repo = Path(repo) - if not repo.is_dir(): - raise RepoPathMissingError( - repo_path_missing_message(given, repo, store_root=store_root) - ) - common = _git( - repo, ["rev-parse", "--path-format=absolute", "--git-common-dir"] - ).strip() - return derive_scope(_toplevel(repo), common) - - -# -------------------------------------------------------------------------- -# The WRITE-PROTOCOL advisories: content a reader cannot reach -# -------------------------------------------------------------------------- -# -# 🔴 THESE CHECKS ARE WHY `validate` IS THE POST-WRITE CHECK AND NOT ONLY A -# PARSE CHECK. The count line above them answers "would the loader accept these -# files?", and a file can pass that while holding text NO reader will ever -# surface. `dropped lines:` is the half that means content is ALREADY LOST. -# -# 🔴 NOT ONE OF THEM MOVES THE VERDICT, AND THAT IS NOT TIMIDITY. `validate` -# answers one question and the write protocol branches on its EXIT CODE to mean "write -# NOTHING". Failing here would stop a session recording anything into an entry -# whose only defect is that an OLDER write lost a line — which makes the store -# lossier, not safer. They are reported loudly and change no code. - -DROPPED_LINE = "dropped-line" -"""The reason token for a nuance line that reaches NO bullet. - -A population of its own, and the one furthest from every other: the openness -shapes are all readings OF a bullet, so each is about content a reader can at -least see. This is content the file HOLDS and no reader can reach at all — -`parse_journal_bullets` drops text that precedes the first bullet, so those lines -are in the entry, in the store, in the backup, and in no consumer's output. -""" - - -@dataclass(frozen=True) -class UnreachableMarkerFinding: - """One bullet carrying a correctly-spelled marker where no parser looks. - - 🔴 DELIBERATELY NOT AN OPENNESS POPULATION. `JournalBullet.openness_population` - partitions bullets by a reading of their OPENING line; this is a fact about - lines 2..n, and the bullet it is about is usually `none` — a bullet that - declared nothing. Carried in its own field, counted in its own key and - rendered in its own block, so there is no place it could be added to a - near-miss total: a near-miss is a marker MIS-SPELLED where the parser looks - and is fixed by editing that line, this is a marker spelled CORRECTLY where - the parser never looks and is fixed by promoting it to a bullet of its own. - One count covering both would send half the readers to the wrong remedy. - """ - - filename: str - bullet_first_line: str - """The bullet's OPENING line — what a reader will search the file for.""" - - offset: int - """1-based line index WITHIN the bullet. Always >= 2.""" - - line: str - """The continuation line carrying the marker, verbatim.""" - - openness: str - """`open` | `resolved` — what it would have declared at a bullet's head.""" - - -@dataclass(frozen=True) -class DroppedLineFinding: - """One `## Nuance / work-history` line that belongs to no parsed bullet. - - 🔴 THE SHAPE, AND WHY IT IS NOT `UnreachableMarkerFinding`. That one is a - marker on a line that IS inside a bullet — the bullet is read, the marker is - not. This is a line inside NO bullet: nothing about it is read, marker or - otherwise. The remedies differ for the same reason the populations do — an - unreachable marker is fixed by PROMOTING one line, a dropped line by - restoring the bullet opening that used to sit above it. - - 🔴 MEASURED IN THE FIELD, NOT HYPOTHETICAL. Over every committed version of - every entry file in a live store of several hundred entries, seven versions - carried dropped lines — two entries whose whole bullet block had been - indented, each broken for days. One of them held a `OPEN:` that raised no - badge for the whole of that window, and would still raise none, because every - marker reader here anchors at position 0; see `line_carries_marker`. - """ - - filename: str - offset: int - """1-based line index within the `## Nuance / work-history` section body.""" - - line: str - """The dropped line, verbatim.""" - - carries_marker: bool = False - """The line looks like it declared `OPEN:`/`RESOLVED:`. - - Recorded because it changes the URGENCY and nothing else: a dropped line is - lost content either way, but a dropped DECLARATION is an open action the - store is actively failing to report. It is never counted as an open action — - the bullet it belonged to no longer exists, so there is nothing to declare - it ON. - """ - - -def line_carries_marker(line: str) -> bool: - """Does this dropped line carry an `OPEN:`/`RESOLVED:` declaration? - - 🔴 IT RESTATES NO GRAMMAR. It asks `line_openness` — which runs the same - `_bullet_openness` that `parse_journal_bullets` calls for a bullet's line 1 — - and falls back to `line_mentions_marker` for a declaration sitting mid-line. - A hand-spelled copy could not stay in step with the real pattern: the - pre-extraction original WAS one, and measured against all seven historical dropped-line - blobs in a live store it was `False` on every one of them, including the - `OPEN:` this feature's own motivating incident cites — while returning True - for the prose `resolved upstream in 1.2.3.`. - - ⚠ `line_mentions_marker` IS THE ONLY PLACE IN EITHER CLIENT THAT LOOKS FOR A - MARKER MID-LINE, and that is deliberate rather than a gap elsewhere: every - marker READER anchors at position 0, so a mid-line `OPEN:` declares nothing - anywhere and did not declare anything while its bullet was intact either. - Widening a reader to match would make this one flag disagree with every - other surface. It may ONLY rank urgency — a dropped line is a finding on its - own and this flag never gates reporting, so a miss costs a word of emphasis, - never a silent pass. - """ - openness, _sha = line_openness(line) - return openness is not None or line_mentions_marker(line) - - -def _scanner_reads_path(path: Path) -> bool: - """Will the advisory scanners OPEN this path? Every one of them, through - `_entry_text`. - - 🔴 THE GATE AND THE DENOMINATOR, SPELLED ONCE, BECAUSE AS TWO THINGS THEY - DISAGREED. `_nuance_body` has always asked the loader's own table before - `open()`; the printed denominator was `len(entry_files_in(...))`, an - unfiltered listing, so the advisories counted files they never read. - """ - return action_for(classify_path(path), _LOADER_ENTRY_ACTIONS) == TAKE - - -def scanned_entry_count(paths: Iterable[str | Path]) -> int: - """How many of `paths` the advisory scanners actually open. - - ⚠ NOT `len(paths)`, AND THE GAP IS THE POINT. A FIFO, a dangling symlink, a - directory or a device inside a scope directory is listed as an entry file and - REFUSED before `open()`. It belongs in the parse line's denominator — the - loader really did try it, and really did report it malformed — and it must - not appear in a denominator that claims text was read. - """ - return sum(1 for path in paths if _scanner_reads_path(Path(path))) - - -def _nuance_body(path: Path) -> str | None: - """The `## Nuance / work-history` body of one entry file, or None. - - 🔴 THE PATH'S KIND IS DECIDED BEFORE IT IS OPENED, THROUGH THE LOADER'S OWN - TABLE. `try: read_text` is NOT tolerance for a path that is not a regular - file, and measuring it was the point: `except OSError` cannot catch a FIFO, - because reading one does not raise — it BLOCKS until somebody writes, and - `validate` never returns. A character device does not raise either; it - streams until the process dies of `MemoryError`, which is not an `OSError` - and propagates. Measured on this tree at the CLI, both clients, against a - cache holding one such path: the FIFO wedged until a `timeout 20` killed it - (124), and a symlink to `/dev/zero` under an address-space limit exited 1 - (Python, bare traceback) and 2 (Go, runtime out-of-memory) — in each case - abandoning every scope after the bad one, where the same tree one commit - earlier reported the file as malformed and exited 5. - - `load_index` never had that exposure: it refuses `other`, `link-to-other`, - `broken-link`, `directory` and `link-to-dir` before `open()`, for exactly - this reason (a fifo measured wedging a request thread for 25s). This gate is - that same table — `_LOADER_ENTRY_ACTIONS`, not a fresh predicate — so the - advisories read precisely the paths the loader reads and no others. - - ⚠ THAT SENTENCE IS ABOUT THE SCANNERS, AND IT USED TO BE READ AS COVERING THE - PRINTED DENOMINATOR TOO. It did not: the clients passed the unfiltered - listing to `validation_advisory_lines`, so a scope holding one entry beside a - FIFO printed `0 across 2 entry file(s)` over a file nothing opened. - `scanned_entry_count` is the denominator now, built from this same predicate. - - ⚠ AND THE UNMAPPED-KIND BRANCH DIVERGES FROM THE GO CLIENT. `action_for` - RAISES `AssertionError` here, uncaught; `internal/store.nuanceBody` folds the - same condition into "no nuance section". UNREACHABLE in both — - `TestClassifierIsTotal` and Go's `TestTheActionTablesAreTotal` pin the kind - set against the table two-way — so it is recorded rather than closed. - - ⚠ THE RESIDUAL IS THE LOADER'S RESIDUAL, AND IT IS NOT EMPTY. The kinds the - table TAKES are `regular-file`, `link-to-file`, `indeterminate` and `absent`; - on the last three the read can still fail, and `except OSError` is what turns - that into "contributes nothing". What it does NOT cover is a REGULAR file - whose read is unbounded — a `/proc` file reached through a symlink, say. That - is the loader's own residual ledger (`load_index`), unchanged here and not - widened: this function is now exactly as exposed as the reader beside it, - which is the property worth having. It is not a claim that nothing can raise. - - Deliberately tolerant otherwise: a file with no nuance section yields None. - Every scanner runs BESIDE the parse check, never in front of it — a malformed - file's own rejection is the finding that matters, and an advisory computed - from its half-parsed body would bury it. - - ⚠ EACH ENTRY IS READ FIVE TIMES PER `validate` — once by `load_index` and - once by each of the FOUR scanners — AND THAT IS A DECISION, NOT AN OVERSIGHT. - It was THREE until the shape and open-action scanners landed, and this - comment said so for as long as it took an audit to read it; the DECISION - survived the re-measurement and the numbers did not. - - RE-MEASURED over the same shape of corpus — a synthetic cache of 300 entries - carrying 30 bullets apiece, `validate --no-sync` over one scope, medians of - 27 runs per client interleaved on one loaded dev host:: - - reads/entry 3.00 -> 5.00 (strace `openat`, both clients, identical) - oracle 155.7 ms -> 190.1 ms (+22%) - Go client 39.8 ms -> 62.5 ms - - The earlier figures (118 ms here, 36 ms for the Go client) did NOT reproduce - as absolute numbers — this host is slower and busier than whatever measured - them — so they are replaced rather than adjusted. Caching the body would put - mutable state into functions whose whole contract is READ-ONLY and - independent, to save a few tens of milliseconds on a store an order of - magnitude larger than any real one. The re-read also has one honest property - a cache would remove: each scanner sees the file as it is when IT runs, so a - body that changed mid-command cannot be reported under offsets taken from an - earlier read. - """ - text = _entry_text(path) - if text is None: - return None - return extract_sections(text, (NUANCE_HEADING,)).get(NUANCE_HEADING) or None - - -def _entry_text(path: Path) -> str | None: - """The WHOLE entry file, or None when no scanner may open this path. - - 🔴 THE GATE AND THE READ, SPELLED ONCE FOR EVERY SCANNER. `_nuance_body` - carried both inline until a scanner appeared that needs the whole file rather - than one section (`scan_entry_shape`, which has to see headings the nuance - body cannot contain). A second copy of the gate is the shape this module - already refuses everywhere else: the FIFO and character-device hazards - `_nuance_body` documents are properties of the OPEN, not of the section - extraction, so a scanner that reads the file by a different route inherits - none of the protection. Read `_nuance_body`'s docstring for the measurements - — they apply verbatim to every caller of this function. - """ - if not _scanner_reads_path(path): - return None - try: - return path.read_text(encoding="utf-8", errors="replace") - except OSError: - return None - - -def scan_unreachable_markers( - paths: Iterable[str | Path], -) -> tuple[UnreachableMarkerFinding, ...]: - """Markers typed into a bullet's BODY, where the marker parser never reads. - - 🔴 IT IS A SEPARATE WALK FROM ANY OPEN-ACTION SCAN BY CHOICE. Merging them - would mean deciding what to do with a bullet that declared nothing on its - opening line, and the answer there is "report it, but never as an open - action" — a second population inside a function whose whole contract is a - one-branch precedence. - """ - out: list[UnreachableMarkerFinding] = [] - for p in paths: - path = Path(p) - body = _nuance_body(path) - if body is None: - continue - for b in parse_journal_bullets(body): - for m in b.unreachable_markers: - out.append( - UnreachableMarkerFinding( - filename=path.name, - bullet_first_line=b.first_line, - offset=m.offset, - line=m.line, - openness=m.openness, - ) - ) - return tuple(out) - - -def scan_dropped_lines( - paths: Iterable[str | Path], -) -> tuple[DroppedLineFinding, ...]: - """Nuance lines present on disk that reach no bullet. READ-ONLY. - - 🔴 IT ASKS THE READER'S OWN PARSER AND DERIVES NOTHING ITSELF. The set of - reachable lines is taken from `parse_journal_bullets`' output rather than - re-deduced from a bullet pattern here, so this check cannot drift away from - what consumers actually see. Re-deriving it would be a duplicated predicate - with the checker's worst failure mode: blessing lines the reader drops. - - 🔴 WHAT IT STRUCTURALLY CANNOT SEE — THREE CASES, NOT ONE, and an earlier - version of this paragraph named only the first. The printed zero names all - three (`_dropped_lines_block`), because a caveat the operator never reads is - not a caveat. Each is pinned by an invariant guard in - `tests/test_entry_shape_validate.py` and its Go twin. - - 1. ABSORBED TAIL. A bullet that loses its opening line while ANOTHER - bullet sits above it is not detectable — `parse_journal_bullets` appends - every non-bullet line to the bullet above, so the orphaned tail is - absorbed into it and inherits its date, and the resulting file is - BYTE-IDENTICAL to one where that bullet legitimately wrapped. No check - can separate the two. - 2. UNCLOSED FENCE. `_is_fence` toggles, so an odd count leaves everything - after the last fence marked fenced — and fenced lines are deliberately - skipped as sample text (see below). A bullet swallowed that way yields - NO dropped-line finding and NO bullet, so its `OPEN:` is reported by - nothing at all. This is the one case where the zero is actively - misleading rather than merely partial, which is why it is named first - in the printed caveat's remedy order. - 3. DUPLICATED `## Nuance / work-history` HEADING. `extract_sections` - concatenates same-named sections into one body, so an orphan under the - SECOND heading is absorbed by a bullet from the FIRST, and the offsets - this function reports index the concatenation rather than the file. - - What it DOES cover is the case where the drop is decidable — text before the - first bullet, which includes every entry whose NEWEST bullet lost its head, - the store being newest-first. - """ - out: list[DroppedLineFinding] = [] - for p in paths: - path = Path(p) - body = _nuance_body(path) - if body is None: - continue - # 🔴 REACHABILITY IS KEYED ON (OFFSET, LINE), NOT ON THE LINE ALONE. A - # `set[str]` masks an orphan whose text is byte-identical to any line - # inside any bullet of the same file — and a read-modify-write race, - # which is the shape that produces a decapitated bullet in the first - # place, is exactly what duplicates a block. - reachable: set[tuple[int, str]] = set() - lines = body.splitlines() - cursor = 0 - for b in parse_journal_bullets(body): - for ln in b.lines: - # `parse_journal_bullets` preserves order and never reorders or - # rewrites a line, so a forward scan re-attaches each bullet line - # to its own offset. Trailing blanks it stripped are simply not - # looked for; the skip below treats them as reachable anyway. - while cursor < len(lines) and lines[cursor] != ln: - cursor += 1 - if cursor < len(lines): - reachable.add((cursor + 1, ln)) - cursor += 1 - in_fence = False - for i, line in enumerate(lines, 1): - # 🔴 FENCES ARE SKIPPED, as in the sibling scanner and in - # `parse_journal_bullets` itself. A fenced snippet BEFORE the first - # bullet is sample text, and reporting it would hand the operator the - # remedy "restore the bullet opening line" for content that never had - # one. - if _is_fence(line): - in_fence = not in_fence - continue - if in_fence or not line.strip() or (i, line) in reachable: - continue - out.append( - DroppedLineFinding( - filename=path.name, - offset=i, - line=line, - carries_marker=line_carries_marker(line), - ) - ) - return tuple(out) - - -# -------------------------------------------------------------------------- -# The entry's SHAPE, as opposed to whether its front matter parses -# -------------------------------------------------------------------------- -# -# 🔴 WHY A SHAPE CHECK EXISTS AT ALL. `validate` returned `OK` at exit 0 for an -# entry with all three spine headings renamed, for one with no headings at all, -# and for one whose sections were all empty. Only a missing `service:` went red. -# So the spine every consumer depends on was enforced by NOTHING: it held because -# two skills happen to describe it and one template happens to emit it. -# -# 🔴 AND IT IS NOT COSMETIC. `subsystem_recall` computes an entry's bullet count -# and its `🔴 N OPEN` badge from `extract_sections(...)[NUANCE_HEADING]`, so a -# heading that is renamed — or given a trailing colon, or shifted off column 0 — -# yields an empty body, and the index row a resume consumes renders an entry with -# genuine open actions as a well-formed empty one. The reader names a missing -# heading ON READ; this catches the same thing ON WRITE, in the turn that wrote -# it, which is the difference between "someone eventually notices" and "the -# writer is told". -# -# 🔴 WHICH HEADINGS, AND WHY STILL NOT `## What it is`. The checked set is -# `SHAPE_HEADINGS` — the set whose absence makes a NUMBER wrong. `## What it is` -# IS read: `subsystem_recall` surfaces it in every printed body. But it feeds no -# bullet count and no index badge, so a missing one cannot turn a parse failure -# into a well-formed empty entry the way a missing `## Nuance / work-history` -# can. Flagging it would report a convention with no numeric consequence beside -# two whose consequence is measured, and a writer cannot tell those apart in a -# list. The reader names its absence under the entry's own body, where the person -# reading that entry is already looking. - -SHAPE_ABSENT = "absent" -SHAPE_RENAMED = "renamed" -SHAPE_DUPLICATED = "duplicated" -SHAPE_EMPTY = "empty" - -#: Cap on the heading inventory printed beside an ABSENT finding. A bound, not a -#: filter — the remainder is always counted in the line. -SHAPE_INVENTORY_SHOWN = 6 - - -def _heading_key(heading: str) -> str: - """The LOOSE form, used ONLY to pair a heading with the schema one it missed. - - 🔴 IT NEVER ACCEPTS A HEADING. `extract_sections` matches the exact string and - keeps doing so; folding `## Pointers` and `## pointers` together there would - quietly widen what the store is allowed to look like, which is the opposite of - what this check is for. This exists so the report can say "you wrote - `## pointers`" instead of "the section is absent" — the difference between a - finding a writer can act on in one edit and one that sends them looking for - prose that is already on disk. - - Folds exactly three near-misses: the `#` level, the case and surrounding - whitespace, and a trailing colon. - """ - return re.sub(r"\s+", " ", heading.lstrip("#").strip().rstrip(":").strip()).lower() - - -@dataclass(frozen=True) -class ShapeFinding: - """One way an entry's spine departs from the schema. FOUR DISJOINT KINDS. - - 🔴 THEY ARE NEVER SUMMED, for the same reason `OpenAction`'s populations are - not: they are different facts with different remedies. `renamed` and `absent` - are the same missing section reported at different resolutions — the writer - typed something we can show them, or they did not — and collapsing them would - throw away the only half that is actionable. `duplicated` is a section that IS - parsed, twice, silently merged. `empty` is a section present and unfilled, - which `extract_sections` tracks separately from absent precisely so this can. - - 🔴 `duplicated` AND `empty` ARE NOT MUTUALLY EXCLUSIVE, and neither branch in - `scan_entry_shape` excludes the other: a heading written twice whose merged - body is still blank is BOTH, and reporting one of the two would hand the - writer half a remedy. - """ - - filename: str - heading: str - """The SCHEMA heading this finding is about, always — never the typo.""" - - kind: str - found: tuple[str, ...] = () - """For `renamed`, the near-miss heading(s) actually written; for `absent`, the - file's whole heading inventory, so the writer sees what they wrote instead.""" - - count: int = 0 - """For `duplicated`, how many times the exact heading appears.""" - - -def scan_entry_shape(paths: Iterable[str | Path]) -> tuple[ShapeFinding, ...]: - """Report each entry's spine against `SHAPE_HEADINGS`. READ-ONLY. - - Tolerant in exactly the way the sibling scanners are, and gated the same way: - a path the loader's own table refuses is never opened (`_entry_text`), and a - file that cannot be read contributes nothing rather than raising, because this - runs BESIDE the parse check and never in front of it — a malformed file's own - rejection is the finding that matters. - - 🔴 IT REUSES `extract_sections` AND `scan_headings` AND PARSES NOTHING ITSELF. - Both are views over one walker in `subsystem_resolver`, so this cannot come to - a different conclusion about what a heading is than the reader does — which - would be the worst possible defect in a checker whose entire job is to predict - what the reader will see. - """ - out: list[ShapeFinding] = [] - for p in paths: - path = Path(p) - text = _entry_text(path) - if text is None: - continue - present = extract_sections(text, SHAPE_HEADINGS) - headings = scan_headings(text) - for h in SHAPE_HEADINGS: - if h not in present: - near = tuple(x for x in headings if _heading_key(x) == _heading_key(h)) - out.append( - ShapeFinding( - filename=path.name, - heading=h, - kind=SHAPE_RENAMED if near else SHAPE_ABSENT, - found=near or headings, - ) - ) - continue - # 🔴 BOTH REMAINING KINDS CAN BE TRUE OF ONE HEADING AT ONCE — a - # duplicated heading whose merged body is still empty — so neither - # branch excludes the other and neither is an `elif`. - n = sum(1 for x in headings if x == h) - if n > 1: - out.append( - ShapeFinding( - filename=path.name, heading=h, kind=SHAPE_DUPLICATED, count=n - ) - ) - if not present[h].strip(): - out.append(ShapeFinding(filename=path.name, heading=h, kind=SHAPE_EMPTY)) - return tuple(out) - - -# -------------------------------------------------------------------------- -# Unfinished business: the four openness populations, as a writer sees them -# -------------------------------------------------------------------------- - -@dataclass(frozen=True) -class OpenAction: - """One bullet `validate` is reporting as unfinished business. - - 🔴 FOUR POPULATIONS, AND THEY MUST NEVER BE ADDED TOGETHER INTO ONE NUMBER. - A `OPEN:` bullet is a claim the WRITER made and is exact, while an unmarked - one is this tool's guess from two measured phrasings and has unknown recall. - Merging them would let a floor masquerade as a count. - """ - - filename: str - declared: bool - """The writer typed `OPEN:`. Exact — not a guess about the prose.""" - - date: str | None - first_line: str - near_miss: bool = False - """The bullet tried to declare a marker and missed the grammar. - - A THIRD population, never folded into either other one: it is not an open - action and not a guess about one, it is a write that did not land. - """ - - unverifiable_closure: bool = False - """A `RESOLVED:` that names no sha, so its claim cannot be checked. - - A FOURTH population. Not a problem — closing an action is the outcome this - whole design wants — but the sha is what separates "closed, and here is the - commit" from an assertion, and only a branch on `resolved_by` makes the field - mean anything. - """ - - -def scan_open_actions(paths: Iterable[str | Path]) -> tuple[OpenAction, ...]: - """Read each entry's journal and collect its unfinished business. READ-ONLY. - - Deliberately tolerant, exactly as the sibling scanners are: a file no scanner - may open, one that cannot be read, or one with no `## Nuance / work-history` - section contributes nothing rather than raising. This runs BESIDE the parse - check, never in front of it. - """ - out: list[OpenAction] = [] - for p in paths: - path = Path(p) - body = _nuance_body(path) - if body is None: - continue - for b in parse_journal_bullets(body): - # 🔴 ONE BRANCH, ON THE RESOLVER'S SINGLE PRECEDENCE SOURCE. - # Re-deriving membership from the individual predicates here is what - # let a bullet be both a near-miss and an unmarked action on one - # surface while being one thing on another — the duplicated predicate - # `openness_population` exists to remove. - pop = b.openness_population - if pop in ("none", "resolved"): - continue - out.append( - OpenAction( - filename=path.name, - declared=pop == "open", - near_miss=pop == "near-miss", - unverifiable_closure=pop == "unverifiable", - date=b.date, - first_line=b.first_line, - ) - ) - return tuple(out) - - -#: The longest a quoted line runs before it is cut. A finding names a FILE and a -#: LINE NUMBER; the quote is there to recognise it by, and an entry may hold a -#: 4,000-character bullet. -ADVISORY_QUOTE_MAX = 120 - - -def validation_advisory_lines( - *, - n_scanned: int, - shape: Sequence[ShapeFinding], - dropped: Sequence[DroppedLineFinding], - open_actions: Sequence[OpenAction], - unreachable: Sequence[UnreachableMarkerFinding], -) -> tuple[str, ...]: - """The four write-protocol advisory blocks, as lines. UNPREFIXED. - - Each client prefixes every line with its own `cairn: : `, because - `validate` with no `--scope` walks every scope the cache holds and an - unprefixed block would not say which one it is about. - - 🔴 EVERY FINDING SET IS A REQUIRED KEYWORD, NOT A DEFAULT, and that is the - point of the signature. A defaulted `shape=()` would let a client that never - wired the scanner print a confident `entry shape: … each present exactly once` - over files nothing examined — the reassuring zero from an instrument wired to - nothing, arriving through a forgotten argument instead of an empty directory. - Required, a missed call site is a `TypeError` here and a compile error in the - Go port. - - 🔴 THE ORDER IS LOAD-BEARING, IN BOTH ADJACENT PAIRS: - - * `entry shape:` COMES FIRST OF ALL. A renamed `## Nuance / work-history` - makes every one of the three blocks below read an empty section, so their - zeros are facts about a section the parser never reached. Read in the - other order, `open actions: 0 declared` is simply false. - * `dropped lines:` COMES BEFORE `open actions` AND `marker reachability:`. - A dropped line is content NO reader reaches, so neither of those scans - ever sees it — a zero printed above a `🔴 N DROPPED LINE(S)` reads as a - reassurance it cannot support. - - 🔴 EVERY BLOCK PRINTS ITS DENOMINATOR EVEN WHEN IT FINDS NOTHING. A bare zero - is indistinguishable from a scanner wired to nothing, and three of these four - have a SECOND way to be vacuous that the zero must not hide: they read only - `## Nuance / work-history`, so an entry whose heading is renamed contributes - zero to all three for a reason only the SHAPE block can state. The shape - block's own zero carries the SET it checked for the mirror-image reason — a - reader who assumes the third spine heading was checked would take it as a - claim about a heading nothing examined. - - 🔴 AND WHEN NOTHING WAS CHECKED THE BLOCKS DO NOT PRINT AT ALL — one - `NOT CHECKED` line prints instead, naming all four. "0 across 0 entry - file(s)" is the reassuring zero from an instrument that walked nothing, and it - must not render anywhere near a clean-looking count. - """ - if n_scanned == 0: - return ( - f"write-protocol advisories: NOT CHECKED — 0 entry file(s) scanned, so " - f"a zero here would be a zero over nothing. This withholds ALL FOUR " - f"blocks — entry shape, dropped lines, open actions and marker " - f"reachability. [{DROPPED_LINE}] [{UNREACHABLE_MARKER}]", - ) - return tuple( - _entry_shape_block(n_scanned, shape) - + _dropped_lines_block(n_scanned, dropped) - + _open_actions_block(n_scanned, open_actions) - + _reachability_block(n_scanned, unreachable) - ) - - -def _entry_shape_block( - n_scanned: int, shape: Sequence[ShapeFinding] -) -> list[str]: - """The SHAPE advisory. Prints on every path that SCANNED something. - - 🔴 IT PRINTS ITS DENOMINATOR EVEN WHEN IT FINDS NOTHING, AND IT PRINTS WHICH - HEADINGS IT LOOKED FOR. A reassuring zero is indistinguishable from an - instrument wired to nothing unless it carries the size of what it looked at — - and here it must also carry the SET it looked at, because a reader who assumes - the third spine heading was checked would take this zero as a claim about a - heading nothing examined. - - 🔴 THE FOUR KINDS ARE RENDERED SEPARATELY AND NEVER SUMMED — see - `ShapeFinding`. Each KIND names its own remedy, and `renamed`'s ("you wrote - this, the schema says that") is the only one a writer can act on in a single - edit. - """ - spine = ", ".join(f"`{h}`" for h in SHAPE_HEADINGS) - absent = [s for s in shape if s.kind == SHAPE_ABSENT] - renamed = [s for s in shape if s.kind == SHAPE_RENAMED] - duplicated = [s for s in shape if s.kind == SHAPE_DUPLICATED] - empty = [s for s in shape if s.kind == SHAPE_EMPTY] - if not shape: - return [ - "", - f"entry shape: {n_scanned} entry file(s) checked for {spine} — each " - f"present exactly once and non-empty. 🔴 `{WHAT_HEADING}` is NOT checked " - f"here: the reader DOES surface it, but it feeds no count and no badge, " - f"so its absence changes nothing this zero is about — `subsystem_recall` " - f"names a missing one under that entry's own body instead." - ] - out = [ - "", - f"entry shape across {n_scanned} entry file(s), checked for {spine} " - f"(NOT `{WHAT_HEADING}`, which feeds no count and no badge):" - ] - if renamed: - out.append( - f" 🔴 {len(renamed)} section(s) RENAMED — the heading is close but not " - f"exact, so NO reader reaches the section. Matching is exact-string after " - f"a right-strip, case-sensitive, at column 0. On that entry's index row " - f"this reads as `0 nuance` with no `OPEN` badge: PARSE FAILURE, not an " - f"empty entry." - ) - for s in renamed: - wrote = ", ".join(f"`{h}`" for h in s.found) - out.append(f" {s.filename}: `{s.heading}` is written as {wrote}") - if absent: - out.append( - f" 🔴 {len(absent)} section(s) ABSENT — the heading is not in the file at " - f"all, under any spelling this tool can pair with it. Whatever the entry " - f"says on that subject is invisible to every default read. Read the " - f"inventory below against the schema heading: a section retitled far " - f"enough that no folding pairs it lands here rather than under RENAMED." - ) - for s in absent: - shown = list(s.found[:SHAPE_INVENTORY_SHOWN]) - rest = len(s.found) - len(shown) - inventory = ", ".join(f"`{h}`" for h in shown) if shown else "(none at all)" - if rest > 0: - inventory += f", … {rest} more" - out.append( - f" {s.filename}: no `{s.heading}`; the file's headings are {inventory}" - ) - if duplicated: - out.append( - f" 🔴 {len(duplicated)} heading(s) DUPLICATED — the sections silently " - f"MERGE into one body and anything written under a heading BETWEEN them is " - f"dropped from the read entirely. Fold them into one section." - ) - for s in duplicated: - out.append(f" {s.filename}: `{s.heading}` appears {s.count} times") - if empty: - out.append( - f" ⚠ {len(empty)} section(s) PRESENT AND EMPTY — the heading is there " - f"with nothing under it. Not a parse failure and not the same as absent: " - f"the reader finds the section and prints a blank." - ) - for s in empty: - out.append(f" {s.filename}: `{s.heading}`") - out.append( - " (Advisory, and it changes no verdict: the loader accepts a file whose " - "sections it cannot find, which is precisely the silent failure this block " - "exists to make loud. Fix the heading, not the exit code.)" - ) - return out - - -def _open_actions_block( - n_scanned: int, open_actions: Sequence[OpenAction] -) -> list[str]: - """The UNFINISHED-BUSINESS advisory. Prints on every path that SCANNED something. - - 🔴 IT PRINTS ITS DENOMINATOR EVEN WHEN IT FINDS NOTHING, like every sibling. - "0 declared across 29 entry file(s)" is a reading; a blank space is not. - - 🔴 THE FOUR POPULATIONS ARE RENDERED SEPARATELY AND NEVER SUMMED — see - `OpenAction`. `declared` is exact and the unmarked guess is a FLOOR with - unknown recall; one total over both would let the floor masquerade as a count. - """ - declared = [a for a in open_actions if a.declared] - near = [a for a in open_actions if a.near_miss] - unverifiable = [a for a in open_actions if a.unverifiable_closure] - guessed = [ - a for a in open_actions - if not a.declared and not a.near_miss and not a.unverifiable_closure - ] - if not open_actions: - return [ - "", - f"open actions: 0 declared across {n_scanned} entry file(s), 0 " - f"attempted-but-unparsed, 0 `RESOLVED:` naming no sha, and 0 unmarked " - f"bullets matched the two phrasings this tool can recognise. 🔴 The last " - f"of those is a FLOOR with unknown recall, not a clean bill of health — " - f"an unfinished action phrased any other way is invisible here.", - ] - out = ["", f"open actions across {n_scanned} entry file(s):"] - if declared: - out.append( - f" 🔴 {len(declared)} declared `OPEN:` — exact, the writer said so. " - f"Re-check against the repo; if it landed, rewrite as `RESOLVED :`." - ) - for a in declared: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - if near: - out.append( - f" 🔴 {len(near)} bullet(s) look like an ATTEMPTED marker that did not " - f"parse — they declare nothing and show no badge. Fix the line: the " - f"marker follows `YYYY-MM-DD: `, is upper-case, carries no emphasis or " - f"parenthetical, and ends in `:`." - ) - for a in near: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - if guessed: - out.append( - f" ⚠ {len(guessed)} unmarked bullet(s) that READ like an open action. " - f"AT LEAST this many — two measured phrasings, unknown recall." - ) - for a in guessed: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - if unverifiable: - out.append( - f" ⚠ {len(unverifiable)} `RESOLVED:` bullet(s) name no sha, so the " - f"closure cannot be checked. Not a defect — closing is the point — but " - f"`RESOLVED :` is what makes it verifiable rather than asserted." - ) - for a in unverifiable: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - out.append( - " (Advisory. None of this changes the verdict: an entry with unfinished " - "business is still well-formed, and failing it here would be a red gate " - "nobody could turn green by fixing the file.)" - ) - return out - - -def _dropped_lines_block( - n_scanned: int, dropped: Sequence[DroppedLineFinding] -) -> list[str]: - """The DROPPED-LINE advisory — the half that means content is ALREADY LOST. - - 🔴 THE ZERO CARRIES ITS OWN BLIND SPOT IN WORDS. This check is knowingly - PARTIAL — the absorbed-tail case is undecidable, see `scan_dropped_lines` — - so a bare "0 dropped" would read as "no bullet has lost its head", which is a - claim it cannot make. Saying which half was checked is the difference between - a measurement and a reassurance. - """ - if not dropped: - return [ - "", - f"dropped lines: 0 across {n_scanned} entry file(s) scanned " - f"[{DROPPED_LINE}] — every non-blank `{NUANCE_HEADING}` line reaches a bullet some reader " - f"will surface. 🔴 PARTIAL BY CONSTRUCTION, IN THREE WAYS, and this " - f"zero is a claim about none of them: (1) ABSORBED TAIL — a bullet that " - f"lost its opening line while another bullet sat above it is absorbed " - f"into that one and is byte-identical to a legitimate wrap, so no check " - f"can separate them; (2) UNCLOSED FENCE — an odd number of ``` or ~~~ " - f"makes every line after it fenced, and fenced lines are skipped as " - f"sample text, so a whole bullet can be swallowed with its `OPEN:` and " - f"reported nowhere; (3) DUPLICATED `{NUANCE_HEADING}` HEADING — the " - f"sections are concatenated into one body, so text under the second is " - f"absorbed by a bullet from the first and any offset printed here would " - f"index the concatenation rather than the file." - ] - n = len(dropped) - marked = sum(1 for d in dropped if d.carries_marker) - out = [ - "", - f"🔴 {n} DROPPED LINE(S) across {n_scanned} entry file(s) scanned " - f"[{DROPPED_LINE}] — present in the file, inside NO bullet, so EVERY " - f"reader skips them: " - f"`--ref`, `--search`, the digest and every openness count. " - f"`parse_journal_bullets` drops text that precedes the first bullet. The " - f"cause is almost always a lost or indented bullet OPENING line; the fix " - f"is to restore it, NOT to delete the text." - ] - if marked: - out.append( - f" 🔴 {marked} of them look{'s' if marked == 1 else ''} like a " - f"`OPEN:`/`RESOLVED:` DECLARATION. " - f"That is an open action the store is actively failing to report — it " - f"raises no badge and is counted in no openness total, because the " - f"bullet that would carry it no longer exists." - ) - for d in dropped: - flag = " ← looks like a DECLARATION" if d.carries_marker else "" - out.append(f" {d.filename}: nuance line {d.offset}{flag}") - out.append(f" {d.line.strip()[:ADVISORY_QUOTE_MAX]}") - out.append( - " 🔴 RESTORE FROM HISTORY, NOT FROM MEMORY. The entry's previous version " - "is one `git log -p -- ` away in the store's own history. " - "Reconstructing the opening line by hand invents a date and an author the " - "store never had." - ) - out.append( - " (Advisory. It changes no verdict: the loader accepts the file, and the " - "write protocol branches on this command's exit code to mean 'write " - "NOTHING'.)" - ) - return out - - -def _reachability_block( - n_scanned: int, unreachable: Sequence[UnreachableMarkerFinding] -) -> list[str]: - """The MARKER-REACHABILITY advisory. - - 🔴 ITS OWN BLOCK, BECAUSE IT IS ITS OWN SHAPE. Every remedy a near-miss - advisory names — "fix the LINE", "rewrite as `RESOLVED :`" — is wrong - here. A marker on a continuation line is spelled correctly; the edit it needs - is to be PROMOTED to a bullet of its own. - """ - if not unreachable: - return [ - "", - f"marker reachability: 0 out-of-reach marker(s) across {n_scanned} entry " - f"file(s) scanned [{UNREACHABLE_MARKER}] — every `OPEN:`/`RESOLVED:` " - f"found is " - f"on a bullet's OPENING line, where the parser reads.", - ] - n = len(unreachable) - out = [ - "", - f"🔴 {n} MARKER(S) OUT OF REACH across {n_scanned} entry file(s) scanned " - f"[{UNREACHABLE_MARKER}] — spelled CORRECTLY, on a bullet's CONTINUATION " - f"line, where NO reader looks. The marker pattern is anchored at position " - f"0 of a bullet's OPENING line, so this declares NOTHING: it raises " - f"neither the `OPEN` badge nor `NEAR-MISS`. 🔴 It is NOT a near-miss and " - f"is NOT counted as one — a near-miss is mis-spelled where the parser " - f"looks and is fixed by editing the line; this is fixed by PROMOTING the " - f"line to a top-level bullet of its own.", - ] - for u in unreachable: - out.append(f" {u.filename}: line {u.offset} of the bullet opening") - out.append(f" bullet: {u.bullet_first_line[:ADVISORY_QUOTE_MAX]}") - out.append( - f" marker: {u.line.strip()[:ADVISORY_QUOTE_MAX]} " - f"(would declare `{u.openness}`)" - ) - out.append( - " 🔴 BEFORE FIXING ANY MARKER ABOVE IT IN THE SAME SECTION, re-check this " - "one against the store's history. Such a bullet can have raised its badge " - "only BY ACCIDENT, through a broken `RESOLVED —` sitting above it — so " - "repairing that line would SILENCE a still-open action." - ) - out.append( - " (Advisory. It changes no verdict: the loader accepts the file, and the " - "write protocol branches on this command's exit code to mean 'write " - "NOTHING'.)" - ) - return out diff --git a/lib/env_aliases.py b/lib/env_aliases.py deleted file mode 100644 index a2d7496e..00000000 --- a/lib/env_aliases.py +++ /dev/null @@ -1,316 +0,0 @@ -"""THE one definition of every environment-variable RENAME — Python side. - -There are two: `SUBSYSTEM_STORE_*` → `CAIRN_*`, and `CAIRN_SUPABASE_*` → `CAIRN_OIDC_*` -over the seven settings of the JWT verifier in `internal/identity` (see below). - -🔴 THERE ARE TWO SPELLINGS OF THIS LEDGER AND THAT IS PACKAGING, NOT DUPLICATION. -`packages.cairn` installs the client script and `lib/` under `libexec` and nothing -else, so this side CANNOT import `internal/envalias`. That Go package is the other -spelling, and `tests/test_env_aliases.py` pins the two against each other — failing -when the pair set GROWS *or* SHRINKS, and comparing the rendered warnings as WHOLE -NORMALISED STRINGS rather than by keyword, because a guard on words is walkable by -rewording. Two spellings plus a gate is the shape `AGENTS.md` already blesses for -`server/Dockerfile` against `flake.nix`'s `serverEnv`. - -Read `internal/envalias/envalias.go`'s package doc for the reasoning in full — the -`CAIRN_HOST` collision, the removal anchor, and the one behaviour change. -The short form, because a reader editing THIS file should not have to open that one: - -* **The new name wins WITHIN ONE SOURCE** — one environment, or one config file. - The old name is read only when the new one is absent or blank *there*. Which - SOURCE supplies the value composes the other way round (environment before file, - and for the default instance only); `README.md` owns that, and it is why the two - warning texts below each speak about one source. -* 🔴 **A PRESENT BUT EMPTY VALUE COUNTS AS ABSENT, AND THAT IS AN AUTHORISED CHANGE - TO THE ORACLE** — decision: the operator, on PR #69. `server.py`'s `main()` used to - hand argparse `""` for `--store` and to raise `ValueError` on a blank `--port`; - every Go call site and this client's `load_config` already treated blank as absent, - so the rule removes a divergence rather than creating one. 🔴 The conformance corpus - is structurally blind to it — no row sends an empty value and none can, the corpus - describing REQUESTS while this decides STARTUP — so a green corpus says nothing - about this rule. The declaration, the accepted cost and the two guards that stand in - the corpus's place are in `tests/conformance/README.md`. -* **An old name that is present and non-blank warns once per process**, including - when the new name shadows it. A blank value is how a caller UNSETS an alias — it - changes no resolution, so it is not a deprecation and does not warn. 🔴 **"Blank" is - ONE predicate** — `_blank`, below — **read by both halves.** Spelled inline on each - side, the two disagreed: a whitespace-only old value resolved *and* did not warn, - which is the one combination that sentence rules out. -* **Warnings are sorted by NEW name.** `tests/parity/harness.py` compares the two - clients' stderr BYTE-FOR-BYTE, so the order has to be a property of the ledger - rather than of whatever order the lookups happened in. - -🔴 TWO PAIRS ARE NOT THE MECHANICAL PREFIX SWAP. `SUBSYSTEM_STORE_HOST` is the pod's -LISTEN ADDRESS, while `CAIRN_HOST` already exists and is the machine LABEL -(`host_identity.HOST_LABEL_ENV[0]`, rendered into client output) — so the mechanical -swap would make a pod bind to an operator's machine label AND let a listen address -hijack the label in rendered output. Hence `CAIRN_LISTEN_HOST`. And `CAIRN_ROOT` -would read as a sibling of the client-side `*_ROOT` names when it is the POD's store -root and belongs to none of them. Hence `CAIRN_STORE_ROOT`. ⚠ The live one is -`CAIRN_MIRROR_ROOT` alone: nothing in either language reads `CAIRN_CACHE_ROOT`, which -an earlier draft of this paragraph named as live. - -⚠ `SUBSYSTEM_STORE_ROUTES_ISH`, in `tests/test_env_pin.py`, is a negative-control -FIXTURE and not a variable anything reads. It is deliberately not in this ledger. - -🔴 THE SECOND RENAME IS NOT A PREFIX SWAP AT ALL, which is why `LEDGER` is pairs and not -a rule: `CAIRN_SUPABASE_*` → `CAIRN_OIDC_*`, over the seven settings of the JWT verifier -in `internal/identity`. That verifier is a generic RFC 7519 one (non-empty issuer and -audience required, a CLOSED asymmetric algorithm set, keys from a JWKS URL) and nothing -in it is specific to one vendor, so the old name asserted a dependency the code never -had. ⚠ `CAIRN_SUPABASE_REDIRECT_URL` is deliberately NOT renamed — it configures the -GoTrue PKCE sign-in flow and is honestly named for what it talks to — and -`CAIRN_SUPABASE_JWT_SECRET`/`_JWT_SECRET_FILE` are RETIRED rather than renamed: a pair -here would turn a startup refusal into a working alias. - -⚠ NOTHING ON THIS SIDE READS THE OIDC NAMES; the verifier is pod-side and Go-only. They -are here because `tests/test_env_aliases.py` pins the two spellings of the ledger as ONE -set — a pair present in one language and absent in the other is the half-migration that -gate exists to catch — and because `deprecations` sweeps the whole environment, so a -client run in a shell that still exports an old spelling warns about it in BOTH clients -and the parity harness's byte-for-byte stderr diff stays meaningful. The single -`REMOVAL_ANCHOR` therefore covers these pairs too, which is a wider promise than they -need and NOT a claim that this client reads them; per-pair anchors were declined as a -mechanism change (see `internal/envalias/envalias.go`'s package doc). -""" - -from __future__ import annotations - -from typing import Iterable, Mapping - -__all__ = [ - "LEDGER", - "REMOVAL_ANCHOR", - "deprecations", - "env_warning", - "file_deprecations", - "file_warning", - "old_name", - "reset_warned_for_test", - "value", - "value_or", - "warn_once", -] - -#: Every renamed variable as `(new, old)`, SORTED BY NEW NAME. -#: -#: 🔴 THE ORDER IS LOAD-BEARING, NOT COSMETIC — see the third bullet above. -#: `tests/test_env_aliases.py` pins it, so a pair appended in the wrong place is a -#: red test rather than a stderr diff the parity harness discovers later. -LEDGER: tuple[tuple[str, str], ...] = ( - ("CAIRN_CONFIG", "SUBSYSTEM_STORE_CONFIG"), - ("CAIRN_FAILURE_WINDOW_S", "SUBSYSTEM_STORE_FAILURE_WINDOW_S"), - ("CAIRN_LISTEN_HOST", "SUBSYSTEM_STORE_HOST"), - ("CAIRN_LOCKOUT_S", "SUBSYSTEM_STORE_LOCKOUT_S"), - ("CAIRN_MAX_FAILURES", "SUBSYSTEM_STORE_MAX_FAILURES"), - # The JWT verifier's settings. 🔴 THEY SORT INTO THE MIDDLE, so this is not an - # append; the order is load-bearing (third bullet above). - ("CAIRN_OIDC_AUDIENCE", "CAIRN_SUPABASE_AUDIENCE"), - ("CAIRN_OIDC_ISSUER", "CAIRN_SUPABASE_ISSUER"), - ("CAIRN_OIDC_JWKS_URL", "CAIRN_SUPABASE_JWKS_URL"), - ("CAIRN_OIDC_LEEWAY", "CAIRN_SUPABASE_LEEWAY"), - ("CAIRN_OIDC_MAX_AGE", "CAIRN_SUPABASE_MAX_AGE"), - ("CAIRN_OIDC_PROVIDER", "CAIRN_SUPABASE_PROVIDER"), - ("CAIRN_OIDC_REQUIRE_ROLE", "CAIRN_SUPABASE_REQUIRE_ROLE"), - ("CAIRN_PORT", "SUBSYSTEM_STORE_PORT"), - ("CAIRN_STORE_ROOT", "SUBSYSTEM_STORE_ROOT"), - ("CAIRN_TOKEN", "SUBSYSTEM_STORE_TOKEN"), - ("CAIRN_TOKEN_FILE", "SUBSYSTEM_STORE_TOKEN_FILE"), - ("CAIRN_TRUSTED_PROXIES", "SUBSYSTEM_STORE_TRUSTED_PROXIES"), - ("CAIRN_URL", "SUBSYSTEM_STORE_URL"), -) - -#: WHEN the old names stop being read, in the only terms this repo can state it: a -#: milestone a reader can CHECK — `packages.cairn` either exists in `flake.nix` or it -#: does not. A date could not be checked, there is no semver here to hang one on -#: (`flake.nix`: `version = self.shortRev`), and `tests/leakscan.py` refuses a dated -#: stamp in this tree anyway. -REMOVAL_ANCHOR = "the Python client (packages.cairn) is retired" - -#: The two pinned warning texts. -#: -#: 🔴 EACH LINE SPEAKS ONLY ABOUT ITS OWN SOURCE, AND THE EARLIER WORDING DID NOT — -#: measured false on both real clients. They used to end "…is read only when ${new} is -#: unset" / "…absent from that file", which reads as a claim about the whole -#: configuration; it is not one, because precedence COMPOSES. A config file holding -#: `CAIRN_URL=…:19001` — what README.md's quickstart tells you to write — plus an -#: exported `SUBSYSTEM_STORE_URL=…:19002` sends both clients to 19002, while the line -#: said the old name is read "only when $CAIRN_URL is unset" and it was set. The mirror -#: case misleads identically. An operator who had just migrated would read either line -#: as "my migration is live" and be wrong. -#: -#: 🔴 SO THE LINES STATE THE WITHIN-SOURCE RULE, the only rule a warning can know: no -#: cross-source sentence is truthful here, because the environment beats the file for the -#: DEFAULT instance and is not consulted at all for a non-default one (see -#: `load_config`'s own `where` text). The composition, with that caveat, is in -#: `README.md`. -#: -#: 🔴 STILL ONE TEXT PER DESTINATION, USED WHETHER OR NOT THE NEW NAME SHADOWS THE OLD -#: ONE, and now for a reason that holds: the sentence states the RULE rather than this -#: run's outcome, so it is true in both cases. A second "…and it is being ignored -#: because you also set X" wording would double the strings the cross-language gate has -#: to pin and double the ways the two spellings can drift. -#: -#: 🔴 `tests/test_env_aliases.py` READS THESE TWO CONSTANTS AND THEIR GO TWINS and -#: compares the rendered results. Editing one alone is a red test, which is why they -#: are named constants rather than inline literals at the call sites. -ENV_WARNING_FORMAT = ( - "${old} is a deprecated alias for ${new}. Where both are set in the environment, " - "${new} is the one that is read. Both are accepted until {anchor}." -) -FILE_WARNING_FORMAT = ( - "{old} in {path} is a deprecated alias for {new}. Where both appear in that file, " - "{new} is the one that is read. Both are accepted until {anchor}." -) - -#: The ONE lookup direction this side builds: new name → old name, read by `old_name` -#: and by `value`'s fallback. -#: -#: ⚠ THE OTHER DIRECTION (old → new) WAS BUILT BESIDE THIS ONE AND HAD ZERO READERS -#: TREE-WIDE — the declared-but-unread shape this repository refuses, the same ruling as -#: `Claims.Email` in `internal/identity/jws.go`. `deprecations`/`file_deprecations` walk -#: `LEDGER` through `_present` instead, which is where the sort order comes from, so the -#: map was dead from the commit that added it. -#: -#: 🔴 ITS GO TWIN IS NOT DEAD, AND THAT ASYMMETRY IS THE POINT RATHER THAN AN OVERSIGHT: -#: `envalias.olds` IS read, by `Deprecations` and `FileDeprecations`, because those two -#: range over a map where these two comprehend a list. So "the two spellings are one -#: ledger" is a claim about the PAIRS, never about the helpers — -#: `tests/test_env_aliases.py` compares ledger CONTENTS and is structurally blind to -#: helper SURFACE, which is why an unread helper here could sit beside a read one there -#: with every gate green. Reintroduce this direction only with a caller. -_NEW_TO_OLD = {new: old for new, old in LEDGER} - -#: The once-per-process-per-LINE set behind `warn_once`. -#: -#: Keyed on the WHOLE LINE rather than on the old name, so the same variable -#: deprecated in the environment AND named as a key in a config file produces both -#: warnings — they say different things and send the operator to different places — -#: while two lookups of the same variable produce one. -_WARNED: set[str] = set() - - -def old_name(new: str) -> str: - """The deprecated spelling of `new`, or `""` if there is not one. - - `""` rather than a `KeyError` so a caller naming something that was never renamed - — `CAIRN_ROUTES`, `CAIRN_UI_PORT` — gets plain single-name behaviour out of - `value` instead of a crash. - """ - return _NEW_TO_OLD.get(new, "") - - -def _blank(v: str) -> bool: - """The ONE definition of "this variable is not set", applied to BOTH spellings. - - 🔴 A NAMED FUNCTION BECAUSE THE TWO HALVES OF THE RULE DISAGREED WHILE BOTH WERE - SPELLED INLINE, AND `tests/parity/` WAS BLIND TO IT BECAUSE `internal/envalias` HAD - THE SAME DISAGREEMENT. `_present` tested `.strip()`; `value` returned the old name's - value RAW. So `SUBSYSTEM_STORE_ROOT=" "` resolved to `" "` — a pod would have taken - a whitespace store root — and warned about nothing, while the module docstring said a - blank value "changes no resolution, so it is not a deprecation". Two clients failing - identically compare equal; only reading the two halves against each other found it. - - ⚠ WHICH HALF WAS WRONG IS A DECISION, AND THIS IS IT: the RESOLUTION half. The - alternative — warn whenever an old name holds any non-empty string — keeps a resolved - value no operator can have meant. Treating it as absent makes the old name behave - exactly like the new one, which has been `.strip()`-tested since this module was - written, and lets `value_or`'s fallback (the code default) run. - - ⚠ IT TESTS BLANKNESS AND DOES NOT TRIM: a non-blank value comes back RAW, because - trimming a real value is the caller's business and would silently rewrite a store root - that legitimately ends in a space. - """ - return not v.strip() - - -def value(env: Mapping[str, str], new: str) -> str: - """`new` if present and non-blank, else its old spelling, else `""`. - - The ONLY place the precedence rule is written. Every call site goes through this; - none open-codes a fallback, because a predicate duplicated across call sites - regenerates the same bug at every site. - """ - direct = env.get(new, "") - if not _blank(direct): - return direct - old = _NEW_TO_OLD.get(new, "") - if old: - fallback = env.get(old, "") - if not _blank(fallback): - return fallback - return "" - - -def value_or(env: Mapping[str, str], new: str, fallback: str) -> str: - """`value`, with a default for "neither name is set".""" - return value(env, new) or fallback - - -def env_warning(new: str, old: str) -> str: - """The pinned text for an environment variable.""" - return ENV_WARNING_FORMAT.format(old=old, new=new, anchor=REMOVAL_ANCHOR) - - -def file_warning(new: str, old: str, path: str) -> str: - """The pinned text for a config-FILE key. - - 🔴 IT NAMES THE FILE, NOT `$VAR`. `SUBSYSTEM_STORE_URL=` inside - `~/.config/subsystem-store/env` is not an exported variable, and telling an - operator to "unset $SUBSYSTEM_STORE_URL" when the string lives in a file they have - to EDIT sends them looking in the wrong place. - """ - return FILE_WARNING_FORMAT.format(old=old, new=new, path=path, anchor=REMOVAL_ANCHOR) - - -def _present(mapping: Mapping[str, str]) -> list[tuple[str, str]]: - """Every `(new, old)` whose OLD name is present and non-blank, sorted by new. - - Blankness through `_blank`, the SAME predicate `value` resolves with. Spelled inline - on both sides once, the two disagreed; see `_blank`. - """ - return sorted( - ((new, old) for new, old in LEDGER if not _blank(mapping.get(old, ""))), - key=lambda pair: pair[0], - ) - - -def deprecations(env: Mapping[str, str]) -> list[str]: - """One warning line per old name present in `env`, sorted by NEW name. - - A pure function of `env`: no process state, no emission. `warn_once` adds the - once-per-process rule, and keeping them apart is what lets a test assert the ORDER - without reaching into module state. - """ - return [env_warning(new, old) for new, old in _present(env)] - - -def file_deprecations(from_file: Mapping[str, str], path: str) -> list[str]: - """`deprecations` for the keys of one config file.""" - return [file_warning(new, old, path) for new, old in _present(from_file)] - - -def warn_once(lines: Iterable[str], emit) -> None: - """Emit each line through `emit`, at most once per process. - - The caller supplies `emit` because the destination differs and the format differs - with it: the CLI writes bare lines to stderr, the pod writes - `subsystem-store-api: ` through `reload_safe`. A module that wrote to - `sys.stderr` itself would need a knob for the prefix, and the prefix would then be - a second thing to keep in step across two languages. - """ - for line in lines: - if line in _WARNED: - continue - _WARNED.add(line) - emit(line) - - -def reset_warned_for_test() -> None: - """Clear the once-per-process set. - - Public because `warn_once`'s whole contract is module-global state, and a test that - could not clear it would be order-dependent: the second test to assert an emission - would see nothing and pass for the wrong reason. - """ - _WARNED.clear() diff --git a/lib/host_identity.py b/lib/host_identity.py deleted file mode 100644 index ea3dfb52..00000000 --- a/lib/host_identity.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python3 -"""WHICH MACHINE am I — one implementation, every consumer. - -🔴 A HOSTNAME IS NOT AN IDENTITY. Machines provisioned from one image commonly -report the SAME hostname, and cairn's local cache is PER-HOST and independently -STALE: two machines holding the same scope can hold different entries in it at -any given instant. - -⚠ NOT "UNREPLICATED", WHICH IS WHAT THIS SAID AND IS NO LONGER TRUE. Since the -Cairn cutover the hosted pod is the canonical datastore and each machine's -`~/.cache/subsystem-store` is a SYNCED READ-THROUGH CACHE of it, so the two -caches CONVERGE — eventually, via the pod, whenever `cairn sync` runs on each. -What survives is the divergence at an instant, and that is enough: nothing makes -the two caches agree at the moment a tool reads one of them. - -So the module's thesis is UNCHANGED, only its reason is. A tool that reads such -a cache and reports a GLOBAL fact ("the store has no `billing/` scope") is -stating one machine's disk as though it were the fleet's — it is now wrong by -STALENESS rather than by isolation, which is the same wrong answer to the reader. -That is the defect this module exists to make un-writable: every consumer prints -the identity of the machine it actually read. - -WHY THE LABEL ALONE IS NOT ENOUGH ---------------------------------- -`host_label()` reads an operator-set environment variable and falls back to the -hostname. Under a systemd unit that variable is typically set to something -machine-specific; in an INTERACTIVE shell it is usually unset and the label -degrades to the hostname — which is exactly the value that may be shared. - -So a header printing `host_label()` alone would read as coverage while providing -none: identical on the very machines it is supposed to distinguish. `this_host()` -joins the readable label to the machine id, which is distinct per host by -construction and needs no systemd. -""" -from __future__ import annotations - -import os -import re -import socket -from pathlib import Path - -#: Where the machine id is read from. A module-level tuple so a test can point a -#: reader at synthetic files and exercise the REAL function, rather than -#: re-implementing its shape check in the test — which would only ever prove the -#: test agrees with itself. -MACHINE_ID_FILES: tuple[str, ...] = ("/etc/machine-id", "/var/lib/dbus/machine-id") - -#: What `/etc/machine-id` is defined to hold: 32 lowercase hex digits. -_MACHINE_ID_SHAPE = re.compile(r"[0-9a-f]{32}") - -#: Printed instead of an id when no file could be read or none had the right -#: shape. A SENTENCE, not an empty string: the whole point of this module is that -#: a host claim is never silently unqualified. -MACHINE_ID_UNREADABLE = "machine-id-unreadable" - -#: Environment variables consulted for a readable label, in precedence order. -#: A tuple rather than a hardcoded pair so a deployment can add its own without -#: editing the function. -HOST_LABEL_ENV: tuple[str, ...] = ("CAIRN_HOST", "ASIB_HOST", "ACTIVITY_HOST") - - -def machine_id(files: "tuple[str, ...] | None" = None) -> str | None: - """The only reliable "which machine am I" signal available without config. - - 🔴 SHAPE-CHECKED, NOT JUST NON-EMPTY. Returning whatever junk a file happened - to hold would make a caller's "does this prefix belong to this host" answer - True for any prefix containing it — an error in the FALSE DATA-LOSS - direction, which is the one that gets someone to act destructively. - - Returns `None` when no candidate file is readable or none parses. The caller - decides what an unknown machine means; this never guesses. - """ - for p in (MACHINE_ID_FILES if files is None else files): - try: - v = Path(p).read_text(encoding="utf-8").strip() - except OSError: - continue - if _MACHINE_ID_SHAPE.fullmatch(v): - return v - return None - - -def host_label() -> str: - """The READABLE name of this machine, for a human reading a key or a header. - - 🔴 The fallback is the hostname, which may be SHARED across machines — that - is precisely why `this_host()` exists and why nothing should print this value - on its own as a per-host claim. - """ - for var in HOST_LABEL_ENV: - v = os.environ.get(var) - if v and v.strip(): - return re.sub(r"[^A-Za-z0-9._-]", "-", v.strip()) - return re.sub(r"[^A-Za-z0-9._-]", "-", socket.gethostname() or "unknown") - - -#: How much of the machine id `this_host()` prints. -#: 🔴 A PREFIX, NEVER THE WHOLE ID. `/etc/machine-id` is a stable, unique -#: installation identifier, and `this_host()` is a DISPLAY value: it lands in -#: rendered headers and JSON payloads, and tool output gets pasted into issues -#: and pull requests routinely. A dozen hex characters separate machines with -#: room to spare; the job is to tell a fleet apart, not to identify hardware. -#: 🔴 THIS DOES NOT TOUCH `machine_id()` OR `host_label()`. A caller that builds -#: a storage key from the full id must keep doing so — truncating a key prefix -#: would repoint every future object, which is a data-loss shape, not a privacy -#: fix. -MACHINE_ID_DISPLAY_CHARS = 12 - - -def this_host() -> str: - """An identity that DIFFERS between machines even on a hand-run. - - `