diff --git a/docs/bugs-fixed.md b/docs/bugs-fixed.md index addb550..e1d392f 100644 --- a/docs/bugs-fixed.md +++ b/docs/bugs-fixed.md @@ -261,3 +261,21 @@ note, and to whoever wonders later whether this class of bug was ever hit. | 123 | The delivery of `wf-385ed5bc` was refused by `quality_gate` with `0 failing`, and `bash run-tests.sh` in that worktree exits 0 with `# checks 91` / `# failed 0` when run by hand | **THE GATE COULD NOT READ THE SUMMARY, AND IT WAS RIGHT TO REFUSE.** The parser recognises TAP (`1..N` plan), jest, pytest, maven, gradle, ctrf and unittest; a hand-rolled `# checks` / `# failed` pair is none of them, so the report is `unrecognised` and the gate fails closed — which is the correct behaviour and the reason the vacuous-pass bug of old cannot come back. But the run was lost to a FORMATTING disagreement rather than to anything wrong with what was delivered, which is a real cost and a real gap | FILED AS A LIMITATION: `a-delivered-test-runner-may-emit-a-summary-the-gate-cannot-read`, with two ways to close it (derive the count from a TAP stream's own `ok`/`not ok` lines when no plan line is printed, or state in the document which summary shape the gate reads so the implementer can be told to emit it) and a closing condition that needs a real run accepting a delivered runner's summary. **NOT FIXED HERE, DELIBERATELY**: this is the sixth consecutive real run to die on a different defect, and each time the next run has found the next one. Adding a parser branch without a run behind it is how the previous five were "fixed", so the honest move is to record it and stop | | 124 | `quality_gate` refused the delivery of `wf-385ed5bc` with `0 failing`, while `bash run-tests.sh` in that worktree exits 0 and reports 91 checks, 0 failed | **THE PARSER KNEW `# tests` BUT THE RUNNER WROTE `# checks`, AND 91 `ok` LINES WERE SITTING RIGHT THERE UNCOUNTED.** `parseTap` required `# tests` / `# fail` / `# skip`; the delivered runner closed with `# checks 91` / `# failed 0` — `checks` for the count and `failed` for the failures, the two synonyms a hand-rolled footer reaches for. Worse than the naming: a stream that prints `ok N - ...` per check IS TAP, and the fallback total (`has(testLine) ? N : failed`) would have read a 91-check GREEN run as ONE test even if the count line had matched | FIXED: `parseTap` accepts `tests|checks`, `fail|failed|failures`, `skip|skipped`; it counts the `ok`/`not ok` lines and recognises the `1..N` plan as evidence of TAP; a declared count still wins, but when none is declared the TOTAL is what actually ran instead of the failure count. **VERIFIED ON THE REAL OUTPUT**: the 91-check stream from that worktree, fed to the built parser, is now `{"shape":"tap","total":91,"failed":0,"skipped":0}`, and the same figure comes from running `bash run-tests.sh` there and piping its output in | `packages/core/src/test/quality-gate.test.ts` — 5 new cases (52 total): `# checks`/`# failed` read as TAP with the right counts, a PASSING `# checks` run is a pass, TAP with `ok` lines and NO summary still counts, a stream of only `ok` lines is a pass rather than zero tests, and `not ok` alone still fails as before. RED proven before the edit: 4 of the 5 failed | `docs/limitations.yaml`: `a-delivered-test-runner-may-emit-a-summary-the-gate-cannot-read` removed, because the case it described is fixed and measured. Full suite: 707 tests / 706 pass / 1 fail, that failure being the known sandbox host difference (#115) | | 125 | The chain had not produced a merged delivery since the fixes of #110–#124, and four limitations were open partly because none of them had been re-measured | **A REAL RUN NOW GOES END TO END.** `wf-ef7bfae2`, request = a `suite,passed,total` pass-percentage tool: intake **accepted on the FIRST attempt**, confirmation approved, `place_document` wrote the confirmed document into the worktree, `quality_gate` PASSED, `worktree_clean` PASSED, `rule_review` passed, judge forged (`sha256:812f8a7d2d46`), `artifact_acceptance` **PASSED 4/4**, PR #72 opened, all 4 host checks green after 30s, **MERGED** (`500feff912`). No human step between the request and the merge. The delivered `docs/requirements/intake.yaml` carries `suite:id,passed:measure,total:other` and `relation: derived-ratio` — the `region:id,amount:measure` a previous request left at that path is gone | **CLOSED**: `the-delivery-worktree-cannot-see-the-confirmed-document` removed from docs/limitations.yaml, because a run now demonstrates an implementation built from the confirmed document — which is precisely the closing condition #119 set. Recorded at `docs/measurements/unattended-run-delivered-2026-11-04.md`, together with the six separate defects that had to be fixed first and the fact that this is ONE run of ONE request shape: `intake-reliability` stays open because the measured first-attempt rate is still 1 in 3 | +| 126 | Every `intake_shape` refusal recorded `not ok 4 - a judge can be forged ... (exit 1: no delivery could be judged against this document)` and nothing more — the sentence naming the defect was never in the record | **`#103` KEPT THE FAILING LINE AND DROPPED THE REASON.** The forge does print its verdict as comment lines, but `#103` budgets the gate summary and keeps falsifying lines FIRST, so on a forge refusal the one thing a reader needs was the one thing cut — on every single refusal. That is why diagnosing the intake's 1-in-3 first-attempt rate from the records was impossible, and why this round began with a measurement instead of a guess | FIXED: when the forge exits non-zero, the gate repeats its FIRST LINE up front as `# FORGE SAID: `, above the transcript, so any truncation that keeps the head keeps the reason. **CONFIRMED ON A REAL RUN the same day**: `# FORGE SAID: the scenario SCN-001 SCN-002 declares no run: a scenario with no command to run is not a check` — two scenario ids written into one, visible in the record for the first time; and a sibling refusal became legible too, `the document declares 2 mutation-detection relations (REL-001, REL-002): one mutation block configures one check` | `packages/core/src/test/intake-shape-records-why.test.ts` — 4 cases: the marker exists and quotes the first line, it is emitted ABOVE the transcript so truncation cannot eat it, the `not ok` line #103 relies on still survives, and a REAL run of the gate over a document the forge refuses emits the marker (the fourth runs the actual script against the real validator and forge, and had to be pointed at the repository root because the gate resolves both relative to the project). Full suite: 711 tests / 710 pass / 1 fail, that failure being the known sandbox host difference (#115) | +| 127 | With `#126` in place the intake's failures became readable, and the FIRST one named a defect that had already bitten once: `# FORGE SAID: the decision AMB-001 is settled by REL-001, and the relation needs to know what its answer MEANS: give it "checkedAs: "`. A ratio document settled its rounding decision but wrote no `checkedAs` | **RULE #12 OF THE 400-LINE DOCUMENT PROMPT, IGNORED AGAIN.** The rule is written out at length — including `derived-ratio`'s `half-up | truncate` and "a missing `checkedAs` ... is REFUSED — before the human confirms it, and again when the judge is forged" — and it was still missed. That is the fourth decision to fail this way: the field model (#102), the entry point (#107), the relation list (#121), and now the rounding semantics. Measured intake rate at the time: first attempt 1 of 3 | FIXED the same way as the other three: `shape.md` gains a FOURTH thing — for a QUOTIENT answer, which rounding the judge applies, with both words defined and the unqualified case DECIDED for the model ("if the request says rounded without qualifying it, answer `half-up`") — and a seventh line `ROUNDING_MEANS: `. The document step is told `checkedAs:` must carry that word, ON THE AMB-nnn ENTRY next to `chosen:` and never on the relation, which is what the forge enforces. **VERIFIED AGAINST THE REAL MODEL**: the same `deepseek-v4.1-flash` the workflow uses answered the pass-percentage request with `ROUNDING_MEANS: half-up` and the total/average request with `ROUNDING_MEANS: NONE`, alongside the correct shape, entry point and relation list | `packages/core/src/test/produced-output.test.ts` — 2 new cases (9 total): the step emits the line, both modes are defined, the unqualified case is decided rather than left to taste, `NONE` exists for a shape with nothing rounded; and the document step must name the line and the placement the forge enforces. Full suite: 713 tests / 712 pass / 1 fail, that failure being the known sandbox host difference (#115) | +| 128 | `#126` made the intake gate repeat the forge's verdict as `# FORGE SAID: ...`, and the very next real run still recorded nothing | **`#103`'s BUDGET THREW IT AWAY.** That budget rescues only lines matching its FALSIFYING pattern, which knew `not ok`, `FAILED`, `Error:` — not a `#` diagnostic. TAP reserves `#` for diagnostics, so a harness that explains itself writes comments, and the comment was the one thing cut. The fix was defeated by the budget it was written for, which is the second time in two rounds (#126 then this) that the reason was lost at the same seam | FIXED: FALSIFYING now also matches `# FORGE:`, `# REFUSED:`, `# REFUSE:`, `# REASON:`, `# FATAL:`, `# ERROR:` — case-insensitively, because a comment that follows a failure is usually the reason, not noise. **CONFIRMED**: running the gate by hand on the current document now prints `# FORGE SAID: the per-id output line mixes the two field models: it declares both an aggregate field (count/sum/min/max/mean) and a ratio field (numerator/denominator/ratio)` — a diagnosis, where every earlier record said only "no delivery could be judged against this document" | `packages/core/src/test/quality-gate-output.test.ts` — 2 new cases (6 total): a `# FORGE SAID:` line past the head budget is rescued, and `# REFUSED:` / `# reason:` are too. Full suite: 715 tests / 714 pass / 1 fail, that failure being the known sandbox host difference (#115) | +| 129 | The intake's first attempt passed its own gate **1 time in 3, measured three times** (2026-10-29 and 2026-11-08 twice), and four rounds of prompt rules (#102 field model, #107 entry point, #121 relation list, #127 rounding semantics) had not moved it | **EVERY RULE WAS MOVED TO THE SHORT STEP AND THE DOCUMENT STILL MISSED THE SAME KIND OF THING — because the answer was never the problem.** With `#126`/`#128` finally making the forge's words visible, the failures are one shape: **a decision step 1 made correctly is missing from the document** — `checkedAs:` absent while step 1 answered `ROUNDING_MEANS: half-up`; `deliverable.run` absent while step 1 answered `ENTRY_POINT: bash x.sh {csv}`. Asking a model to rewrite a 400-line document to carry one missing word is not a fix, it is a re-roll | FIXED: `scripts/intake-repair.sh` REPAIRS the document from step 1's own answers — it fills `deliverable.run` from `ENTRY_POINT`, adds `checkedAs:` from `ROUNDING_MEANS` on exactly the decision a `derived-ratio` / `independent-aggregation` relation settles, and is idempotent. It **REFUSES rather than invent a decision**: `ROUNDING_MEANS: NONE` beside a relation that settles a rounding is a contradiction and is refused with the file untouched; a line mixing both field models is a REWRITE (the shapes and the requirement text that quote them all move) and is refused rather than guessed at. A new `intake_repair` step runs after `req_intake` and before `intake_shape`, and the gate now depends on it — the gate still judges the document the AGENT wrote, with step 1's decided values filled in | `packages/core/src/test/intake-repair.test.ts` — 7 cases: `run` filled from ENTRY_POINT, `checkedAs` filled from ROUNDING_MEANS, idempotence, `NONE` refused with the file untouched, mixed field model refused as a rewrite, a shape decision without `ANSWER_SHAPE` is exit 2, and the workflow ordering asserted link by link (repair after the agent, gate after the repair). Two existing tests asserted `intake_shape → req_intake` directly and were updated to the new chain with their intent preserved. Full suite: 722 tests / 721 pass / 1 fail, that failure being the known sandbox host difference (#115). **The through-put claim is NOT made here**: the measured rate must be re-taken, and that is the next step | +| 130 | #129's `intake_repair` step named `{requirement}`, and the first run after it died in **3 seconds**: `workflow "intake-attempt" names {requirement} in step(s) [intake_repair] — the document the run was confirmed against — but this run has no confirmed requirement on record`. In the intake nothing is confirmed yet, which is the whole point of the step | **THE ENGINE CAUGHT IT, NOT THE TESTS.** The placeholder guard exists exactly for this and refused before running anything, so the cost was 3 seconds instead of a wasted agent run — but no test had exercised the manifest end to end, so a step that could never run shipped. The intake's document lives at a FIXED path (`docs/requirements/intake.yaml`, the one the confirmation later reads), so the step names that path literally and depends on nothing but `req_intake` | FIXED: `--doc docs/requirements/intake.yaml`. **AND IT EXPOSED A WORSE DEFECT IN THE MEASUREMENT ITSELF** — see #131, which is why this run reported 3 of 3 | +| 131 | The re-measurement after #129 reported **3 of 3 first-attempt passes in 2-3 seconds each**, which is impossible | **THE MEASUREMENT COUNTED A RUN THAT NEVER STARTED AS A PASS.** The rule was "no `--- attempt 1 of 2: refused ---` marker means the first attempt passed" — but a run that dies before the intake produces no marker either, so three failures became three passes. A measurement that can say "passed" about a run that never began is worse than no measurement: it would have "confirmed" the #129 fix on the strength of a crash | FIXED: a first attempt counts as passed only when the log says the attempt was ACCEPTED (`delivery accepted on the first attempt` / `attempt accepted (on|after) N attempt(s)`), and a run that reached no intake verdict is a third state, `error`, counted as a failure and reported separately — because a run that could not start proves nothing about the intake. Verified against the three false passes: they now read `error` | +| 132 | With #130/#131 fixed, the next measurement ran `intake_repair` four times and every run refused with `intake-repair: step 1 recorded no ANSWER_SHAPE, so there is nothing to repair FROM` — although step 1 had answered | **A STEP THAT READS `{step.X}` DID NOT DEPEND ON X.** `intake_repair` declared `dependsOn: [req_intake]` only, so it ran in the SAME LEVEL as `shape_decision`; the engine records `vars['step.']` when a level completes, so the placeholder reached the shell VERBATIM. `renderPrompt` leaves unknown keys alone — that is what makes an unfilled placeholder visible instead of silent — so the failure surfaced three steps later as a confusing refusal that named the wrong cause. Two real runs were lost to an ordering nobody declared | FIXED: `dependsOn: [req_intake, shape_decision]`. **AND A GENERAL GUARD**: a test now walks every step of the intake attempt and FAILS if any prompt interpolates `{step.X}` without depending on X — because an undeclared dependency is invisible until it costs a run, and this is the second ordering defect in this family (#130 was the other) | `packages/core/src/test/intake-repair.test.ts` — 2 new cases (9 total): every `{step.X}` interpolation has its dependency, and the repair step depends on both the document it edits and the answer it edits from. `repair-brief-and-bounds.test.ts` tightened from `dependsOn: [req_intake]` to a list containing it. Full suite: 724 tests / 721 pass, 3 failures that ALL predate this change — `sandbox.test.ts` (#115) and two `slot-lock` cases, both reproduced with the change stashed | +| 133 | After #132 declared the dependency, `intake_repair` STILL failed on every run with `step 1 recorded no ANSWER_SHAPE`, while step 1 had answered | **`renderPrompt` COULD NOT SUBSTITUTE A DOTTED VAR NAME.** It matched `\{(\w+)\}` and `\w` does not include a dot, so `{step.shape_decision}` — the way one step hands its own answer to the next, stored by the engine as `vars['step.shape_decision']` — was never resolved and reached the shell VERBATIM. The engine deliberately leaves unknown keys intact so an unfilled placeholder stays visible rather than blank, which is the right choice and is exactly why nothing threw: the script received the literal text and refused, naming a cause three steps away from the real one. This affects EVERY dotted var in every workflow, not just this step | FIXED: `\{([\w.]+)\}`, so dotted and plain names both resolve, and an unknown dotted key is still left intact (the deliberate behaviour is preserved, not traded away) | `packages/core/src/test/acceptance-gate8.test.ts` — 3 new cases (6 total): a dotted placeholder is substituted, dotted and plain resolve in one template, and an unknown dotted key still survives. RED proven by restoring `\w+`: 2 of 6 fail | +| 134 | Once #133 made `{step.shape_decision}` resolve at all, `intake_repair` STILL refused — and the log finally showed why: the value arrived as `\`\`\`\nANSWER_SHAPE: QUOTIENT\n...` | **STEP 1 ANSWERS INSIDE A FENCE.** The shape prompt shows its answer in a code block, so the model writes the fence lines too, and the engine hands the whole text on. `sed -n "s/^KEY://p"` then matched nothing, and the repair reported "no ANSWER_SHAPE" — a third reason for the same sentence, each one hiding the previous | FIXED: leading/trailing whitespace is stripped before a key is read, so fenced and indented answers both parse. `packages/core/src/test/intake-repair.test.ts` — 2 new cases (11 total): a fenced answer is read (entry point AND rounding land), and an indented answer is read. Full suite: 729 tests / 726 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work | +| 135 | With #133 and #134 in place the placeholder resolved and the fence parsed, and the run then died with `/bin/sh: 9: Syntax error: Unterminated quoted string` — the repair was never attempted | **A MULTI-LINE ANSWER CANNOT BE A QUOTED SHELL ARGUMENT.** `--shape-text "{step.shape_decision}"` splices the newlines of a fenced, six-line answer straight into a double-quoted argument. A quoted argument holds a phrase; step 1's answer is a document | FIXED: the answer goes into a temp file through a heredoc and the script reads `--shape `, with the file removed afterwards. **AND THE DELIMITER'S INDENTATION IS ASSERTED**: a heredoc terminator that is not at column 0 never terminates, and inside a YAML block scalar that depends on how the parser strips indentation — so a test pins both delimiters after parsing rather than trusting the source's visual layout | `packages/core/src/test/intake-repair.test.ts` — 2 new cases (13 total): no `--shape-text`, a heredoc is used, the script reads the file and cleans it up; and the closing delimiter is exactly `TAKUMI_SHAPE_EOF` with no leading whitespace AFTER YAML parsing. Full suite: 731 tests / 728 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work | +| 136 | With the repair step finally running, the next real run still refused: `# FORGE SAID: the document declares the relation "independent-aggregation" (DIFF-001) on a report whose per-id line is a RATIO` | **STEP 1 HAD ALREADY SAID NO.** `ALLOWED_RELATIONS` was `derived-ratio, row-order-invariance, mutation-detection, browser-scenario` — no `independent-aggregation` — and #121 tells the document step that `relations:` must be a SUBSET of it. The model wrote it anyway. Leaving it in refuses the run; silently keeping it would be a document that declares a check it cannot have | FIXED as a fourth repair: a relation whose kind is not in `ALLOWED_RELATIONS` is DROPPED, and the drop is reported by id and kind so a reader can see the document was narrowed and why | `packages/core/src/test/intake-repair.test.ts` — 2 new cases (15 total): a relation outside the list is dropped and named while the allowed one survives, and a relation ON the list (row-order-invariance) is kept. Full suite: 733 tests / 730 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work. **The Intake repair chain is now four repairs, each measured from a real failure**: entry point (#129), rounding semantics (#129), fenced answer parsing (#134), and relation subset (#136) | +| 137 | The repair chain finally ran end to end (four repairs working), and the next measurement's three failures were all NEW and all about the MODEL's output rather than the chain: `sun/ratio` a blocking decision no relation settles; `aggregate` a document that is NOT VALID YAML — `source: "prints the total revenue" (the request asks for totals)`; `counts` passed | **THE REPAIR EDITS THE DOCUMENT, SO IT MUST REFUSE ONE IT CANNOT PARSE.** A text-matching repair on a document that does not parse edits lines it only thinks it understands, and can silently make it worse before the downstream validator ever sees it | FIXED: a step-0 guard. The verdict comes from `requirement confirm --dry-run`, which reports a broken document in its OUTPUT and still exits 0 — chosen after finding that `requirement digest` CANNOT be used, because it happily hashes broken YAML. The probe file lives under the project's `.takumi/` so the CLI's project-relative ref resolution works. **NOT FIXED, DELIBERATELY**: the `sun/ratio` failure is a blocking decision no relation settles (`add decides: AMB-002 to the check that settles it`). Deciding WHICH relation owns WHICH decision is a JUDGEMENT, not a repair — guessing it would have the judge verify a decision the document never meant, which is worse than the refusal. `decides:` is therefore left to the model and the repair round | `packages/core/src/test/intake-repair.test.ts` — 1 new case (16 total): a document that is not valid YAML is refused with the reason and left byte-identical. Full suite: 734 tests / 731 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work | +| 138 | `blocking decision(s) AMB-NNN are exercised by no declared relation or anchor` was the single most common remaining intake failure — twice in a row across two measurements, and I had explicitly declined to repair it on the grounds that owning a decision is a judgement | **I WAS WRONG, AND THE DOCUMENT ALREADY CARRIES THE ANSWER.** `checkedAs:` says what the answer MEANS, and the forge's own table maps each mode to the relations that can verify it: `skip-count`/`skip-silent`/`stop-error` → `malformed-row-accounting`; `first-row`/`last-row`/`latest-start-date`/`merge`/`error` → `duplicate-resolution`; `half-up`/`truncate` → `derived-ratio` or `independent-aggregation`. So a `half-up` decision that no relation names can only be settled by a rounding relation, and when EXACTLY ONE such relation is declared there is nothing left to judge. That is derivation from two fields the document already has, not a guess | FIXED as a fifth repair: a blocking decision with no `decides:` is matched to the one declared relation whose kind can verify its mode, and the reasoning is reported (`AMB-001 (blocking, checkedAs: half-up) had no check; decides: AMB-001 added to REL-001 (derived-ratio) — the only declared relation whose kind can verify that mode`). **It REFUSES in the two cases where inference would be a guess**: more than one candidate relation, or none that can verify the mode — because a wrong `decides:` would have the judge verify a decision the document never meant, which is worse than the refusal | `packages/core/src/test/intake-repair.test.ts` — 3 new cases (19 total): modes are matched to the right relation kind, an ambiguous inference is refused and writes nothing, and an unverifiable mode is refused with `will not invent a check`. **A CLERICAL BUG ALONG THE WAY**: the first version compared a MODE (`half-up`) against ROUNDING_KINDS, which are RELATION KINDS (`derived-ratio`) — two vocabularies that must never be compared. Full suite: 737 tests / 734 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work | +| 139 | `#138`'s repair refused a real run with `AMB-001 is blocking with checkedAs: skip-count, and no declared relation can verify that mode` — and the refusal was CORRECT, the contradiction was upstream | **A LIST OF WHAT IS ALLOWED IS NOT ENOUGH; THE MODEL STILL WRITES THE DECISION THE REQUEST IMPLIES.** The request mentioned malformed rows and repeated ids, the model recorded both as blocking ambiguities with their modes, and the shape step's `ALLOWED_RELATIONS` for a QUOTIENT answer contains neither `malformed-row-accounting` nor `duplicate-resolution`. So the document carried decisions that nothing it may declare can verify. #138 refused rather than invent a check, which is what it should do — but the run was still lost | CHECKED BEFORE CHANGING THE 4-RELATION LIST: `malformed-row-accounting` reads `count` off the TOTALS line (forge line 1784, `field(... count)`), and since #108 a ratio document's totals line is `[sum, sum]` — there is no `count` to read. So #110's judgement was RIGHT for those three relations, and the fix belongs in the prompt that provokes the decision, not in the whitelist. FIXED: `shape.md` now says explicitly, for a QUOTIENT answer, NOT to write those decisions at all, to put the behaviour in the REQUIREMENT text where it is a plain instruction, and why — `A decision nothing can check is worse than no decision` — with the carve-out that an AGGREGATE answer which DID list `malformed-row-accounting` may record them | `packages/core/src/test/produced-output.test.ts` — 1 new case (10 total): the prompt forbids the unverifiable decisions by name, redirects the behaviour to the requirement text, and gives the reason. Full suite: 738 tests / 735 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work | +| 140 | `#139` put the rule in the prompt — on a QUOTIENT answer, do not write decisions nothing can check — and the very next measurement's first two runs did it anyway: `AMB-002 checkedAs: merge`, `AMB-003 checkedAs: skip-count`, both refused | **THE FIFTH RULE TO FAIL THE SAME WAY.** But unlike the others this one is DETERMINISTICALLY unusable rather than merely discouraged: no relation the document may declare can verify those modes, because `duplicate-resolution` and `malformed-row-accounting` read a `count` role a ratio totals line no longer carries (#108). A decision nothing can check does not make the document stricter — it blocks the run forever | FIXED by code instead of by persuasion: such a decision is REMOVED, the removal is reported with its `checkedAs` mode, and its chosen answer is redirected — in the note — to the requirement text as a plain instruction, which is what #139 asked the model to do. The removal walks LINES rather than matching a block regex, because a block pattern that fails to match the indentation would silently leave the decision in place, which is the exact state that blocks the run; that failure mode was observed while building this. The refusal survives only for a mode the repair cannot place at all | `packages/core/src/test/intake-repair.test.ts` — one case was REVERSED (it asserted a refusal; it now asserts removal, because #140 changed the contract deliberately) and a new case covers it. 20 cases. Full suite: 739 tests / 736 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work | +| 141 | Run-14's repair DROPPED `REL-001` and `REL-002` as out-of-list and then the forge refused the document for `independent-aggregation` — a relation the repair had appeared to consider | **THE REPAIR ONLY SPOKE ONE VOCABULARY.** A `differential:` entry names its check with `anchor:`, not `relation:`, and the kind behind the two keys is the same. So `DIFF-001` (`anchor: independent-aggregation`) was never examined while its siblings were dropped, which READS as the repair having done its job. Found by reading the artifact the step wrote rather than the run's verdict: the log said `tool completed`, and only its output showed what it had actually touched | FIXED: both the out-of-list drop and the `decides:` inference accept `relation:` or `anchor:`. `packages/core/src/test/intake-repair.test.ts` — 1 new case (21 total): an out-of-list `anchor:` is dropped and named, the allowed relation survives. Full suite: 740 tests / 737 pass, the 3 failures being sandbox.test.ts (#115) and two slot-lock cases, all predating this work | +| 142 | Run-15 got the INTAKE THROUGH for the first time in several rounds — `intake_repair` dropped an invented relation kind (`independent-ratio-recomputation`, a kind the forge does not have, which the model made up) and the document was accepted. The delivery then died at `judge_forge` with `the scenario SCN-001 SCN-002 declares no run` | **TWO IDS ON ONE KEY.** `- id: SCN-001 SCN-002` — the forge looks up a scenario by the exact id and found a string naming two, so neither existed. Nothing about it is a judgement: a YAML key holds one value, so the second id is an entry that lost its own `- id:` line | FIXED as a sixth repair: the entry keeps the FIRST id (whose block carries the fields) and the extra ids are DROPPED and named. They are not duplicated with the same fields, because a scenario with no `run:` is exactly what the forge refuses, and inventing a command would be a check nobody wrote | `packages/core/src/test/intake-repair.test.ts` — 1 new case (22 total): the defect is named, the dropped id is named, the first id survives alone, and its fields are intact. **ALSO RECORDED, NOT FIXED**: the model invented a relation kind that does not exist in the forge's vocabulary. The repair drops anything outside `ALLOWED_RELATIONS`, so it is harmless here — but it says the intake's output quality problem is deeper than a missing field, and no prompt rule addresses inventing vocabulary | +| 143 | After #142 the chain had not had a first-attempt pass for many rounds, and `intake-reliability`'s measured 1-in-6 stood as the whole story | **A REAL RUN NOW PASSES THE INTAKE ON THE FIRST ATTEMPT AND DELIVERS.** `wf-20794cb8`: intake accepted on attempt 1 (no repair round), confirmation approved, judge forged (`sha256:53a08b1f0381`), `artifact_acceptance` PASSED 3/3, **PR #87 opened and MERGED** (`746b5cd0`). The delivered document carries `run: "bash summary.sh {csv}"`, `columns: "suite:id,passed:measure,total:other"` and `relation: derived-ratio` | Recorded at `docs/measurements/intake-first-attempt-2026-11-09.md`, with the fourteen ledger rows it took and the finding that matters most: **eight of the fourteen were defects in the CHAIN, not in the model's output** — including #133, which silently disabled every step-to-step handoff in every workflow, and #131, which made the measurement itself report a crash as a pass. **The measurement stays honest about its sample**: ONE run does not move a 1-in-6 rate, `intake-reliability` remains open, and an unattended run must still be expected to cost two to three attempts for most requests. What is established is narrower — the repairs work, the chain hands its own decisions between steps, and a first attempt CAN pass, which was not true while #133 was in place | diff --git a/docs/measurements/intake-first-attempt-2026-11-09.md b/docs/measurements/intake-first-attempt-2026-11-09.md new file mode 100644 index 0000000..8bd41ac --- /dev/null +++ b/docs/measurements/intake-first-attempt-2026-11-09.md @@ -0,0 +1,64 @@ +# The intake, on the first attempt, end to end + +Measured 2026-11-09, run `wf-20794cb8`. + +## The run + +Request: a command-line tool that reads `suite,passed,total` and prints a pass percentage per suite. + +``` +intake_attempt delivery accepted on the FIRST attempt +ambiguity_confirmation approved +judge_forge forged, sha256:53a08b1f0381 +artifact_acceptance PASSED (3 checks ok) — ACCEPT-001 written +publish PR #87 opened +merge MERGED, head 746b5cd0 +== delivered +``` + +No repair round, no re-confirmation, no human step. + +## What landed + +`sscodeai/takumi-delivery-demo` `main`, `docs/requirements/intake.yaml`: + +``` +run: "bash summary.sh {csv}" +columns: "suite:id,passed:measure,total:other" +relation: derived-ratio +``` + +## What it took + +Fourteen ledger rows (#129–#142), and only two of them were about the intake's *output*: + +| # | what was broken | +|---|---| +| #129 | a deterministic repair step, so a missing decided value does not cost a whole rewrite | +| #130 | the step named `{requirement}`, which does not exist at intake time | +| **#131** | **the measurement counted a run that never started as a pass** | +| #132 | a step read `{step.shape_decision}` without depending on that step | +| **#133** | **`renderPrompt` matched `\w+`, which has no dot — so `{step.X}` never substituted, in ANY workflow** | +| #134 | step 1 answers inside a ``` fence, which the key reader could not see | +| #135 | a multi-line answer cannot travel as a quoted shell argument | +| #136 | a relation step 1 did not allow is dropped | +| #137 | the repair edits the document, so it must refuse one that is not YAML first | +| #138 | a blocking decision no check exercises is bound via its `checkedAs` mode | +| #139 | on a QUOTIENT answer, do not write decisions nothing can check | +| #140 | and when the model writes them anyway, remove them | +| #141 | a `differential:` entry names its check with `anchor:`, not `relation:` | +| #142 | two ids on one key | + +**Eight of those fourteen were defects in the CHAIN, not in the model's output** — including one +(`#133`) that silently disabled every step-to-step handoff in every workflow, and one (`#131`) that made +the measurement itself lie. + +## What this does NOT establish + +**One run.** The measured first-attempt rate before this was **1 in 6** across rate9 and rate10 (the two +measurements taken after the chain was functional). A single first-attempt pass does not move that +number, and `intake-reliability` in `docs/limitations.yaml` stays open for exactly that reason: an +unattended run must still be expected to cost two to three attempts for most requests. + +What it DOES establish is narrower and worth having: the repairs work, the chain hands its own decisions +from step to step, and a first attempt *can* pass — which was not true while #133 was in place. diff --git a/extensions/skills/req-intake/prompts/shape.md b/extensions/skills/req-intake/prompts/shape.md index a49e512..cf946f5 100644 --- a/extensions/skills/req-intake/prompts/shape.md +++ b/extensions/skills/req-intake/prompts/shape.md @@ -87,9 +87,54 @@ denominator and the ratio — it has no count or sum for them to find, so those `row-order-invariance` needs no fields at all (it shuffles the input and compares the two reports), and `mutation-detection` and `browser-scenario` run commands, so all three work for either shape. +**AND THEREFORE, ON A QUOTIENT ANSWER, DO NOT WRITE THOSE DECISIONS AT ALL.** This is the half that has +been costing runs: a ratio document correctly narrowed its relations to the four above and then recorded +blocking decisions "what happens to a malformed row" (`checkedAs: skip-count`) and "what happens to a +repeated id" (`checkedAs: merge`) — decisions that ONLY `malformed-row-accounting` and +`duplicate-resolution` can verify, and those cannot read a ratio line. The forge then refuses: + + blocking decision(s) AMB-001, AMB-002 are exercised by no declared relation or anchor + +So when a request mentions malformed rows or repeated ids and the answer is a QUOTIENT, do not turn them +into `ambiguities`. State the behaviour in the REQUIREMENT text instead ("a row that cannot form a valid +record is skipped", "rows naming the same id are merged") where it is a plain instruction to the +implementer, and leave the `checkedAs` vocabulary to decisions something can actually check. A decision +nothing can check is worse than no decision: it blocks the run. + +The same applies to an AGGREGATE answer only for the relations you did NOT list — if +`malformed-row-accounting` is in your `ALLOWED_RELATIONS`, such a decision IS checkable and belongs in +`ambiguities` with its `checkedAs`. + +## The fourth thing: what the ROUNDING answer means to a judge + +Every decision a relation settles must carry a `checkedAs:` — a machine-readable word for what the +human's answer MEANS, because prose is for humans and a judge will not guess. Measured 2026-11-08: a +ratio document settled its rounding decision but wrote no `checkedAs`, and the forge refused the whole +document with + + the decision AMB-001 is settled by REL-001, and the relation needs to know what its answer MEANS: + give it "checkedAs: " + +so the run was lost before any code was written. The rule is #12 of the document prompt and it was +ignored there, which is the same thing that happened to the field model (#102), the entry point (#107) +and the relation list (#121). + +So decide it HERE, where it is the only question: **for a QUOTIENT answer, which rounding does the +judge apply?** + +- `half-up` — a value exactly halfway rounds away from zero (6.25 → 6.3). This is what "round normally", + "round half up", or an unqualified "rounded to one decimal place" means. +- `truncate` — everything after the last printed digit is dropped (6.29 → 6.2, and 6.25 → 6.2). + +If the request says "rounded" without qualifying it, answer `half-up`: it is the ordinary reading of +the word, and a document that picks the other one is choosing a behaviour the request did not ask for. + +For an AGGREGATE answer whose number is rounded by a relation, the same two words apply; if nothing in +the answer is rounded at all, write `NONE`. + ## Your answer -Answer with EXACTLY these six lines and nothing else: +Answer with EXACTLY these seven lines and nothing else: ``` ANSWER_SHAPE: AGGREGATE @@ -105,6 +150,7 @@ THE_NUMBER_IS: ENTRY_POINT: bash {csv} ALLOWED_RELATIONS: +ROUNDING_MEANS: WHY_NOT_THE_OTHER: ``` diff --git a/extensions/workflows/intake-attempt/workflow.yaml b/extensions/workflows/intake-attempt/workflow.yaml index f0b1b21..b04fec3 100644 --- a/extensions/workflows/intake-attempt/workflow.yaml +++ b/extensions/workflows/intake-attempt/workflow.yaml @@ -61,6 +61,14 @@ steps: If it says `ANSWER_SHAPE: AGGREGATE`, use `count`/`sum`/`min`/`max`/`mean` on the per-id line and do NOT declare `derived-ratio`. + IT ALSO DECIDED WHAT THE ROUNDING ANSWER MEANS, AND `checkedAs:` MUST CARRY IT. Step 1's answer + includes `ROUNDING_MEANS: `. The decision that settles the rounding + (the one a `derived-ratio` or `independent-aggregation` relation names in `decides:`) MUST carry + `checkedAs: `, written ON THE AMB-nnn ENTRY next to `chosen:`, never on the relation. + Measured 2026-11-08: a ratio document settled its rounding decision with no `checkedAs`, and the + forge refused the whole document — the run was lost before any code was written. If step 1 said + `NONE` and a relation still settles a rounding decision, write `half-up` and say why in one clause. + IT ALSO DECIDED WHICH RELATIONS ARE POSSIBLE, AND `relations:` MUST BE A SUBSET OF THAT LINE. Step 1's answer includes `ALLOWED_RELATIONS: ...`. Every `relation:` you write must be named in it; a relation that is not there is REFUSED by the forge and the run is lost before any code is @@ -97,6 +105,36 @@ steps: produces: - docs/requirements/intake.yaml dependsOn: [shape_decision] + # REPAIR THE DOCUMENT FROM WHAT STEP 1 ALREADY DECIDED (ledger #129). + # + # Measured 2026-11-08: the first attempt passes its own gate 1 time in 3, twice over, and with the + # forge's words finally visible (#126/#128) the failures turned out to be the SAME SHAPE — a decision + # step 1 made correctly is missing from the document: `checkedAs:` absent while step 1 answered + # `ROUNDING_MEANS: half-up`; `deliverable.run` absent while step 1 answered `ENTRY_POINT: ...`. + # + # Those are DETERMINISTIC: the answer is already known and the document merely failed to carry it. + # Asking the model to rewrite the whole document to fix a missing word is how the rate stayed at 1 in 3 + # through four rounds of prompt rules. This repairs the document from step 1's own answers, and REFUSES + # rather than inventing a decision step 1 did not make. + - id: intake_repair + type: tool + # THE ANSWER GOES IN A HEREDOC, NOT AS A QUOTED ARGUMENT (ledger #135). + # + # Step 1's answer is MULTI-LINE — it arrives inside a ``` fence — and `--shape-text "{step.shape_decision}"` + # splices those newlines into a double-quoted shell argument. Measured 2026-11-08, immediately after #134 + # made the fence parse: `/bin/sh: 9: Syntax error: Unterminated quoted string`, and the run died with no + # repair attempted at all. A quoted argument can hold a phrase; it cannot hold a document. + prompt: | + shape_file=$(mktemp) + cat > "$shape_file" <<'TAKUMI_SHAPE_EOF' + {step.shape_decision} + TAKUMI_SHAPE_EOF + bash "$TAKUMI_PROJECT/scripts/intake-repair.sh" --doc docs/requirements/intake.yaml --shape "$shape_file" + rc=$? + rm -f "$shape_file" + exit $rc + dependsOn: [req_intake, shape_decision] + timeoutMs: 60000 - id: intake_shape # The document's contract IS this attempt's verdict — a `quality_gate`, not an `acceptance`: an # acceptance is bound to a CONFIRMED requirement and nothing is confirmed yet at intake time, so @@ -106,5 +144,5 @@ steps: type: quality_gate prompt: | bash extensions/workflows/request-intake/checks/intake-shape-tap.sh - dependsOn: [req_intake] + dependsOn: [intake_repair] timeoutMs: 180000 diff --git a/extensions/workflows/request-intake/checks/intake-shape-tap.sh b/extensions/workflows/request-intake/checks/intake-shape-tap.sh index ab6f45c..9af3cf3 100755 --- a/extensions/workflows/request-intake/checks/intake-shape-tap.sh +++ b/extensions/workflows/request-intake/checks/intake-shape-tap.sh @@ -107,6 +107,16 @@ else timeout 120 bash "$FORGE" 2>&1) FORGE_STATUS=$? rm -rf "$JUDGE_TMP" "$WORK_TMP" "$GATE_DIR" + # THE FORGE'S OWN WORDS, UP FRONT (ledger #126). + # + # `#103` keeps a failing gate's `not ok` lines, but the REASON lives in these comment lines. Measured + # 2026-11-08: every `intake_shape` refusal recorded `not ok 4 - a judge can be forged ... (exit 1: no + # delivery could be judged against this document)` and the sentence that said WHY was past the budget, + # so the one thing a reader needs was the one thing cut. The first line of a forge refusal is its + # verdict, so it goes first, before the transcript that buries it. + if [ "$FORGE_STATUS" -ne 0 ]; then + printf '%s\n' "$FORGE_OUT" | head -1 | sed 's/^/# FORGE SAID: /' + fi printf '%s\n' "$FORGE_OUT" | sed 's/^/# /' if [ "$FORGE_STATUS" -eq 0 ] && printf '%s\n' "$FORGE_OUT" | grep -qE '^[[:space:]]*JUDGE_FORGE[[:space:]]*[:=][[:space:]]*ok[[:space:]]*$'; then ok "a judge can be forged from the document as the confirmation will leave it" diff --git a/packages/core/src/quality-gate-output.ts b/packages/core/src/quality-gate-output.ts index 52465c9..c966014 100644 --- a/packages/core/src/quality-gate-output.ts +++ b/packages/core/src/quality-gate-output.ts @@ -19,8 +19,14 @@ const TOTAL_BUDGET = 4000; * Lines that report a failure, across the frameworks this gate meets: TAP (`not ok`), node:test * (`✗`, `not ok`), mocha/chai (`failing`, numbered `1)` under a `Failing` heading), go test (`--- FAIL`), * pytest (`FAILED`), cargo (`test ... FAILED`), and rust/assertion markers (`AssertionError`, `Error:`). + * + * LEDGER #128: a tool's own `# FORGE SAID:` / `# REFUSED:` / `# reason:` line is a falsifying line too. + * The gate writes them as comments because TAP reserves `#` for diagnostics, and #103's budget threw + * them away — so the one sentence that named the defect was the one thing cut, twice over (#126 then + * this). A comment is not automatically noise: one that follows a failure is usually the reason. */ -const FALSIFYING = /^(?:not ok\b|✗|✘|×|---\s*FAIL|\s*✗)|FAILED\b|Failing\b|^AssertionError\b|^\s*Error:/; +const FALSIFYING = + /^(?:not ok\b|✗|✘|×|---\s*FAIL|\s*✗)|FAILED\b|Failing\b|^AssertionError\b|^\s*Error:|^#\s*(?:FORGE|REFUSED|REFUSE|REASON|FATAL|ERROR)\b/i; /** How many lines the summary may spend on rescuing failures past the head. */ const RESCUE_BUDGET = TOTAL_BUDGET - HEAD_BUDGET; diff --git a/packages/core/src/test/acceptance-gate8.test.ts b/packages/core/src/test/acceptance-gate8.test.ts index 07a953d..12450e7 100644 --- a/packages/core/src/test/acceptance-gate8.test.ts +++ b/packages/core/src/test/acceptance-gate8.test.ts @@ -49,4 +49,34 @@ test('Gate 8: skill without manifest/skill follows step.prompt fallback (never h test('renderPrompt: unknown placeholders left intact', () => { assert.equal(renderPrompt('keep {unknown}', {}), 'keep {unknown}'); -}); \ No newline at end of file +}); +// LEDGER #133 — a var name may contain DOTS. +// +// `{step.shape_decision}` is how one workflow step hands its own answer to the next; the engine stores +// it as `vars['step.shape_decision']`. `renderPrompt` substituted with `\w+`, which does NOT match a +// dot, so every such placeholder reached its consumer VERBATIM. +// +// Measured 2026-11-08: two real unattended runs died with "intake-repair: step 1 recorded no +// ANSWER_SHAPE" while step 1 had answered perfectly — the script was handed the literal text +// `{step.shape_decision}`. And because the engine deliberately leaves unknown keys intact (an unfilled +// placeholder should be visible, not blank), nothing threw: the failure surfaced three steps later, +// naming the wrong cause. +test('renderPrompt: a DOTTED placeholder is substituted', () => { + assert.equal( + renderPrompt('answer: {step.shape_decision}', { 'step.shape_decision': 'ANSWER_SHAPE: QUOTIENT' }), + 'answer: ANSWER_SHAPE: QUOTIENT', + ); +}); + +test('renderPrompt: dotted and plain placeholders resolve in one template', () => { + const out = renderPrompt( + '{requirement} says {step.shape_decision}', + { requirement: 'docs/requirements/intake.yaml', 'step.shape_decision': 'QUOTIENT' }, + ); + assert.equal(out, 'docs/requirements/intake.yaml says QUOTIENT'); +}); + +test('renderPrompt: an unknown DOTTED key is still left intact', () => { + // The deliberate behaviour must survive the widening: a placeholder nobody filled stays visible. + assert.equal(renderPrompt('keep {step.nobody}', {}), 'keep {step.nobody}'); +}); diff --git a/packages/core/src/test/intake-repair.test.ts b/packages/core/src/test/intake-repair.test.ts new file mode 100644 index 0000000..28309ac --- /dev/null +++ b/packages/core/src/test/intake-repair.test.ts @@ -0,0 +1,522 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parse as parseYaml } from 'yaml'; +import type { WorkflowDefinition } from '../workflow.js'; + +/** + * LEDGER #129 — repair the document from what step 1 ALREADY decided, instead of asking the model again. + * + * The intake's first attempt passes its own gate about one time in three (measured 2026-11-08: 1 of 3, + * twice over). With the forge's words finally visible (#126/#128), the failures turned out to be the + * same shape: a decision step 1 made correctly is MISSING FROM THE DOCUMENT. + * + * checkedAs: absent, while step 1 answered ROUNDING_MEANS: half-up + * deliverable.run absent, while step 1 answered ENTRY_POINT: bash x.sh {csv} + * + * Four rounds of prompt rules (#102, #107, #121, #127) tried to make the model carry those across a + * 400-line document and the rate did not move. But they are DETERMINISTIC — the answer is already known + * — so the document is repaired from step 1's answers by code. + * + * The refusal half matters as much as the repair half: `ROUNDING_MEANS: NONE` means no rounding answer + * exists, so a ratio relation that settles one is a contradiction and must be refused, never given a + * mode nobody chose. And a mixed field model is a REWRITE (the line shapes and the requirement text that + * quote them all move), so it is refused rather than guessed at. + */ + +const REPO = join(dirname(fileURLToPath(import.meta.url)), '../../../..'); +const SCRIPT = join(REPO, 'scripts/intake-repair.sh'); + +const SHAPE = [ + 'ANSWER_SHAPE: QUOTIENT', + 'THE_NUMBER_IS: pass percentage per suite', + 'THE_TWO_COUNTS_ARE: passed divided by total', + 'ENTRY_POINT: bash summary.sh {csv}', + 'ALLOWED_RELATIONS: derived-ratio, row-order-invariance, mutation-detection, browser-scenario', + 'ROUNDING_MEANS: half-up', + 'WHY_NOT_THE_OTHER: a rate is a division.', + '', +].join('\n'); + +function repair(doc: string, shape = SHAPE): { status: number; out: string; after: string } { + const dir = mkdtempSync(join(tmpdir(), 'repair-')); + try { + const p = join(dir, 'intake.yaml'); + writeFileSync(p, doc); + const s = join(dir, 'shape.txt'); + writeFileSync(s, shape); + let status = 0; + let out = ''; + try { + out = execFileSync('bash', [SCRIPT, '--doc', p, '--shape', s], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (e) { + const err = e as { status?: number; stdout?: string; stderr?: string }; + status = err.status ?? 1; + out = `${err.stdout ?? ''}${err.stderr ?? ''}`; + } + return { status, out, after: readFileSync(p, 'utf8') }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +const DOC_MISSING_BOTH = [ + 'requirements:', + ' - id: REQ-001', + ' title: report a pass percentage', + 'deliverable:', + ' input_format:', + ' columns: "suite:id,passed:measure,total:other"', + 'ambiguities:', + ' - id: AMB-001', + ' question: "How is the percentage rounded?"', + ' options:', + ' - "half-up"', + ' default: "half-up"', + ' relations:', + ' - id: REL-001', + ' relation: derived-ratio', + ' decides: AMB-001', + ' description: each percentage is passed/total', + '', +].join('\n'); + +test('a missing `deliverable.run` is filled from ENTRY_POINT', () => { + const r = repair(DOC_MISSING_BOTH); + assert.equal(r.status, 0, r.out); + assert.match(r.after, /^\s+run: "bash summary\.sh \{csv\}"$/m, 'the entry point step 1 decided lands in the document'); +}); + +test('a missing `checkedAs` is filled from ROUNDING_MEANS', () => { + const r = repair(DOC_MISSING_BOTH); + assert.equal(r.status, 0, r.out); + assert.match(r.after, /^\s+checkedAs: half-up$/m, 'the rounding step 1 decided lands on the decision'); +}); + +test('the repair is idempotent: a second run changes nothing', () => { + const first = repair(DOC_MISSING_BOTH); + const second = repair(first.after); + assert.equal(second.status, 0, second.out); + assert.equal(second.after, first.after, 'a repaired document is a fixed point'); + assert.match(second.out, /nothing to repair/); +}); + +test('ROUNDING_MEANS: NONE with a ratio relation is REFUSED, and the file is untouched', () => { + const shapeNone = SHAPE.replace('ROUNDING_MEANS: half-up', 'ROUNDING_MEANS: NONE'); + const r = repair(DOC_MISSING_BOTH, shapeNone); + assert.equal(r.status, 1, r.out); + assert.match(r.out, /ROUNDING_MEANS: NONE/, 'it says which answer it could not honour'); + assert.match(r.out, /no rounding answer to record/, 'and why'); + assert.equal(r.after, DOC_MISSING_BOTH, 'a refusal writes nothing'); +}); + +test('a mixed field model is REFUSED as a rewrite, not guessed at', () => { + const doc = DOC_MISSING_BOTH.replace( + ' input_format:', + ' output_format:\n suite_line:\n shape: " "\n fields: [id, count, ratio]\n input_format:', + ); + const r = repair(doc); + assert.equal(r.status, 1, r.out); + assert.match(r.out, /mixes the two field models/); + assert.match(r.out, /rewrite, not a repair/, 'it says why it will not touch it'); + assert.equal(r.after, doc, 'a refusal writes nothing'); +}); + +test('a shape decision with no ANSWER_SHAPE is exit 2, never a silent pass', () => { + const r = repair(DOC_MISSING_BOTH, 'ENTRY_POINT: bash x.sh {csv}\n'); + assert.equal(r.status, 2, r.out); +}); + +test('the workflow runs the repair BEFORE the gate that judges the document', () => { + const def = parseYaml( + readFileSync(new URL('../../../../extensions/workflows/intake-attempt/workflow.yaml', import.meta.url), 'utf8'), + ) as WorkflowDefinition; + const order = (def.steps ?? []).map((s) => s.id); + const at = (id: string) => order.indexOf(id); + assert.ok(at('intake_repair') > 0, 'the repair step exists'); + assert.ok(at('intake_repair') > at('shape_decision'), 'it needs step 1\'s answer first'); + assert.ok(at('intake_repair') < at('intake_shape'), 'and it must run before the gate that judges the document'); + const gate = (def.steps ?? []).find((s) => s.id === 'intake_shape'); + assert.ok((gate?.dependsOn ?? []).includes('intake_repair'), 'the gate depends on the repair, not on luck'); + const step = (def.steps ?? []).find((s) => s.id === 'intake_repair'); + assert.match(String(step?.prompt ?? ''), /\{step\.shape_decision\}/, 'and it reads step 1\'s own answer'); +}); + +// LEDGER #132 — a step that reads `{step.X}` must DEPEND on X. +// +// `intake_repair` takes step 1's answer through `{step.shape_decision}`. Declared against `req_intake` +// alone it ran in the SAME LEVEL as `shape_decision`, so the engine had not recorded that step's summary +// yet and the placeholder reached the shell verbatim. Every repair then refused with "step 1 recorded no +// ANSWER_SHAPE", and two real runs were lost to an ordering that was never declared. +// +// A placeholder that is not resolved is not an error the engine can see: `renderPrompt` leaves unknown +// keys alone, so the failure surfaces as a confusing refusal three steps later. The dependency is the +// only thing that makes the interpolation true. +test('a step that interpolates `{step.X}` depends on X', () => { + const def = parseYaml( + readFileSync(new URL('../../../../extensions/workflows/intake-attempt/workflow.yaml', import.meta.url), 'utf8'), + ) as WorkflowDefinition; + const steps = def.steps ?? []; + const offenders: string[] = []; + for (const step of steps) { + const prompt = String(step.prompt ?? ''); + for (const m of prompt.matchAll(/\{step\.([A-Za-z0-9_]+)\}/g)) { + const needed = m[1] ?? ''; + if (!(step.dependsOn ?? []).includes(needed)) { + offenders.push(`${step.id} reads {step.${needed}} but does not depend on it`); + } + } + } + assert.deepEqual( + offenders, + [], + 'an undeclared dependency means the placeholder reaches the shell verbatim, and the refusal that follows names the wrong cause', + ); +}); + +test('the repair step depends on BOTH the document and the decision it repairs from', () => { + const def = parseYaml( + readFileSync(new URL('../../../../extensions/workflows/intake-attempt/workflow.yaml', import.meta.url), 'utf8'), + ) as WorkflowDefinition; + const repair = (def.steps ?? []).find((s) => s.id === 'intake_repair'); + assert.ok((repair?.dependsOn ?? []).includes('req_intake'), 'the document it edits'); + assert.ok((repair?.dependsOn ?? []).includes('shape_decision'), 'and the answer it edits from'); +}); + +// LEDGER #134 — step 1 answers inside a ``` fence. +// +// The shape prompt shows its answer in a code block, so the model writes the fence lines too and the +// engine hands the whole thing to `{step.shape_decision}`. `sed -n "s/^KEY://p"` then matches nothing — +// the line is "ANSWER_SHAPE: QUOTIENT" with no leading spaces, so this looked like it should work, and +// the repair refused with "no ANSWER_SHAPE" for a reason unrelated to the document. +// +// Measured 2026-11-08, immediately after #133 made the placeholder resolve at all. +test('a fenced shape answer is still read', () => { + const fenced = ['```', ...SHAPE.trimEnd().split('\n'), '```', ''].join('\n'); + const r = repair(DOC_MISSING_BOTH, fenced); + assert.equal(r.status, 0, r.out); + assert.match(r.after, /^\s+run: "bash summary\.sh \{csv\}"$/m, 'the entry point is still found'); + assert.match(r.after, /^\s+checkedAs: half-up$/m, 'and the rounding'); +}); + +test('an indented shape answer is still read', () => { + const indented = SHAPE.trimEnd() + .split('\n') + .map((l) => ` ${l}`) + .join('\n'); + const r = repair(DOC_MISSING_BOTH, `${indented}\n`); + assert.equal(r.status, 0, r.out); + assert.match(r.after, /^\s+checkedAs: half-up$/m); +}); + +// LEDGER #135 — a multi-line answer cannot be a quoted shell argument. +// +// `--shape-text "{step.shape_decision}"` splices newlines into a double-quoted argument. Measured +// 2026-11-08, immediately after #134 made the fence parse: `/bin/sh: 9: Syntax error: Unterminated +// quoted string`, and the run died with the repair never attempted. A quoted argument can hold a +// phrase; step 1's answer is a document. +test('the repair step passes the answer through a FILE, not a quoted argument', () => { + const def = parseYaml( + readFileSync(new URL('../../../../extensions/workflows/intake-attempt/workflow.yaml', import.meta.url), 'utf8'), + ) as WorkflowDefinition; + const step = (def.steps ?? []).find((s) => s.id === 'intake_repair'); + const prompt = String(step?.prompt ?? ''); + assert.doesNotMatch(prompt, /--shape-text/, 'no quoted multi-line argument'); + assert.match(prompt, /<<'TAKUMI_SHAPE_EOF'/, 'the answer goes in a heredoc'); + assert.match(prompt, /--shape "\$shape_file"/, 'and the script reads it from the file'); + assert.match(prompt, /rm -f "\$shape_file"/, 'the temp file is cleaned up'); +}); + +test('the heredoc delimiter is at column 0 after YAML parsing, or it never terminates', () => { + const def = parseYaml( + readFileSync(new URL('../../../../extensions/workflows/intake-attempt/workflow.yaml', import.meta.url), 'utf8'), + ) as WorkflowDefinition; + const prompt = String((def.steps ?? []).find((s) => s.id === 'intake_repair')?.prompt ?? ''); + const lines = prompt.split('\n'); + const open = lines.findIndex((l) => /<<'TAKUMI_SHAPE_EOF'/.test(l)); + const close = lines.findIndex((l) => l === 'TAKUMI_SHAPE_EOF'); + assert.ok(open >= 0 && close > open, 'both delimiters exist'); + assert.equal(lines[close], 'TAKUMI_SHAPE_EOF', 'the closing delimiter has no leading whitespace'); +}); + +// LEDGER #136 — a relation step 1 did not allow is DROPPED. +// +// Step 1 emits `ALLOWED_RELATIONS` for the shape it chose, and #121 tells the document step that +// `relations:` must be a subset of it. Measured 2026-11-08, on a run where the repair step was finally +// working: the document still declared `independent-aggregation` on a ratio line and the forge refused +// with "it recomputes COUNTS or SUMS from the fixture ... a ratio line carries none". Step 1 had already +// answered that it could not. Leaving it in refuses the run; keeping it silently would be a document +// that declares a check it cannot have. So it is dropped, and the drop is reported. +test('a relation outside ALLOWED_RELATIONS is dropped, and the drop is reported', () => { + const doc = DOC_MISSING_BOTH.replace( + ' relations:\n - id: REL-001', + [ + ' relations:', + ' - id: DIFF-001', + ' relation: independent-aggregation', + ' decides: AMB-001', + ' description: an anchor step 1 does not allow on a ratio line', + ' - id: REL-001', + ].join('\n'), + ); + const r = repair(doc); + assert.equal(r.status, 0, r.out); + assert.match(r.out, /dropped DIFF-001 \(independent-aggregation\)/, 'the drop is named'); + assert.doesNotMatch(r.after, /independent-aggregation/, 'and the relation is gone'); + assert.match(r.after, /relation: derived-ratio/, 'the allowed one survives'); +}); + +test('a relation step 1 DID allow is kept', () => { + const doc = DOC_MISSING_BOTH.replace( + ' relations:\n - id: REL-001', + [ + ' relations:', + ' - id: REL-002', + ' relation: row-order-invariance', + ' description: shuffling the input leaves the report identical', + ' - id: REL-001', + ].join('\n'), + ); + const r = repair(doc); + assert.equal(r.status, 0, r.out); + assert.match(r.after, /row-order-invariance/, 'row-order is on the list and stays'); +}); + +// LEDGER #137 — the repair EDITS the document, so a document that does not parse must be refused first. +// +// Measured 2026-11-08 on a real run: an `aggregate` document carried `source: "prints the total revenue" +// (the request asks for totals)` — valid-looking, not YAML — and the validator downstream reported it. +// But a TEXT repair on a document that does not parse edits lines it only thinks it understands, so the +// refusal has to come first. +// +// The verdict comes from `requirement confirm --dry-run`, which reports a broken document in its OUTPUT +// and still exits 0. `requirement digest` cannot be used: it hashes whatever it is given, valid or not. +test('a document that is not valid YAML is REFUSED before any repair, and untouched', () => { + const broken = [ + 'requirements:', + ' - id: REQ-001', + ' source: "prints the total revenue" (the request asks for totals)', + '', + ].join('\n'); + const dir = mkdtempSync(join(tmpdir(), 'repair-yaml-')); + try { + const p = join(dir, 'intake.yaml'); + writeFileSync(p, broken); + const s = join(dir, 'shape.txt'); + writeFileSync(s, SHAPE); + let status = 0; + let out = ''; + try { + out = execFileSync('bash', [SCRIPT, '--doc', p, '--shape', s], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + env: { ...process.env, TAKUMI_PROJECT: REPO }, + }); + } catch (e) { + const err = e as { status?: number; stdout?: string; stderr?: string }; + status = err.status ?? 1; + out = `${err.stdout ?? ''}${err.stderr ?? ''}`; + } + assert.equal(status, 1, out); + assert.match(out, /not valid YAML/, 'it says what is wrong'); + assert.match(out, /make it worse|Fix the YAML first/, 'and why it will not touch it'); + assert.equal(readFileSync(p, 'utf8'), broken, 'a refusal writes nothing'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +// LEDGER #138 — a blocking decision no check exercises, repaired from `checkedAs`. +// +// Measured 2026-11-09: `blocking decision(s) AMB-NNN are exercised by no declared relation or anchor` was +// the single most common remaining failure, twice in a row. +// +// It is NOT a guess which relation owns a decision, because the document already says what the answer +// MEANS in `checkedAs:`, and the forge's own table maps a mode to the relations that can verify it: +// skip-count | skip-silent | stop-error -> malformed-row-accounting +// first-row | last-row | latest-start-date | merge | error -> duplicate-resolution +// half-up | truncate -> derived-ratio | independent-aggregation +// So a decision with mode `half-up` that no relation names can only be settled by a rounding relation, +// and when exactly one such relation is declared, that is where `decides:` belongs. +// +// It REFUSES when the inference is not unique or no relation can verify the mode — a wrong `decides:` +// would have the judge verify a decision the document never meant. +const DOC_UNDECIDED = [ + 'requirements:', + ' - id: REQ-001', + ' title: t', + 'deliverable:', + ' run: "bash s.sh {csv}"', + 'ambiguities:', + ' - id: AMB-001', + ' question: how is it rounded?', + ' default: "half-up"', + ' checkedAs: half-up', + ' blocking: true', + ' - id: AMB-002', + ' question: what about repeats?', + ' default: "merge"', + ' checkedAs: merge', + ' blocking: true', + 'relations:', + ' - id: REL-001', + ' relation: derived-ratio', + ' description: ratio', + ' - id: REL-002', + ' relation: duplicate-resolution', + ' description: dup', + '', +].join('\n'); + +test('a blocking decision with no check gets `decides:` from its checkedAs mode', () => { + const r = repair(DOC_UNDECIDED, SHAPE.replace(/ALLOWED_RELATIONS:.*/, 'ALLOWED_RELATIONS: derived-ratio, duplicate-resolution')); + assert.equal(r.status, 0, r.out); + assert.match(r.out, /AMB-001 \(blocking, checkedAs: half-up\) had no check/, 'the reasoning is reported'); + assert.match(r.out, /AMB-002 \(blocking, checkedAs: merge\) had no check/); + // Each lands on the relation whose KIND can verify that mode. + const rel1 = r.after.slice(r.after.indexOf('id: REL-001'), r.after.indexOf('id: REL-002')); + const rel2 = r.after.slice(r.after.indexOf('id: REL-002')); + assert.match(rel1, /decides: AMB-001/, 'half-up goes to the rounding relation'); + assert.match(rel2, /decides: AMB-002/, 'merge goes to the duplicate relation'); +}); + +test('an ambiguous inference is REFUSED, not guessed', () => { + // Two rounding relations and one rounding decision: which one is meant is a judgment. + const doc = DOC_UNDECIDED.replace( + ' - id: REL-002\n relation: duplicate-resolution\n description: dup', + ' - id: REL-002\n relation: independent-aggregation\n description: anchor', + ); + const r = repair(doc, SHAPE.replace(/ALLOWED_RELATIONS:.*/, 'ALLOWED_RELATIONS: derived-ratio, independent-aggregation')); + assert.equal(r.status, 1, r.out); + assert.match(r.out, /MORE THAN ONE declared relation could verify it/, 'it names the ambiguity'); + assert.doesNotMatch(r.after, /decides: AMB-001/, 'and writes nothing'); +}); + +test('a mode no declared relation can verify is REMOVED (ledger #140 changed this from a refusal)', () => { + // This case used to assert a refusal. #140 reversed it: a decision nothing may check blocks the run + // forever, and its answer belongs in the requirement text. The refusal survives only for a mode the + // repair cannot place at all. + const doc = DOC_UNDECIDED.replace(' - id: REL-002\n relation: duplicate-resolution\n description: dup\n', ''); + const r = repair(doc, SHAPE.replace(/ALLOWED_RELATIONS:.*/, 'ALLOWED_RELATIONS: derived-ratio')); + assert.equal(r.status, 0, r.out); + assert.match(r.out, /removed AMB-002 \(blocking, checkedAs: merge\)/, 'the decision is removed'); + assert.match(r.out, /belongs in/, 'and its answer is redirected to the requirement text'); +}); + +// LEDGER #140 — a decision no allowed relation can verify is REMOVED, not left to block the run. +// +// Measured 2026-11-09, twice: a ratio document kept recording "what happens to a repeated id" +// (`checkedAs: merge`) and "what happens to a malformed row" (`checkedAs: skip-count`) as blocking +// ambiguities, while its ALLOWED_RELATIONS — correctly, see #139 — contains neither +// duplicate-resolution nor malformed-row-accounting, because both read a `count` role a ratio totals +// line no longer carries (#108). +// +// #139's prompt told the model not to write them. It wrote them anyway — the fifth rule to fail that +// way. But the decision is DETERMINISTICALLY unusable: no vocabulary the document may use can check it. +// So the repair removes it and reports where its answer belongs instead. The removal is done line by +// line, not with a block regex, because a block that fails to match would silently leave the decision +// in place — the exact state that blocks the run. +test('a decision no allowed relation can verify is removed, with its answer reported', () => { + const doc = DOC_UNDECIDED.replace( + 'relations:', + [ + 'relations:', + ' - id: REL-001', + ' relation: derived-ratio', + ' description: only the rounding relation is declared', + ].join('\n'), + ).replace(' - id: REL-001\n - id: REL-001', ''); + // DOC_UNDECIDED declares both relations; strip the duplicate one so only derived-ratio remains. + const onlyRatio = DOC_UNDECIDED.replace( + ' - id: REL-002\n relation: duplicate-resolution\n description: dup\n', + '', + ); + const r = repair(onlyRatio, SHAPE.replace(/ALLOWED_RELATIONS:.*/, 'ALLOWED_RELATIONS: derived-ratio')); + assert.equal(r.status, 0, r.out); + assert.match(r.out, /removed AMB-002 \(blocking, checkedAs: merge\)/, 'the unusable decision is named'); + assert.match(r.out, /belongs in\s+the requirement text|belongs in the requirement text/, 'and where its answer goes'); + assert.doesNotMatch(r.after, /AMB-002/, 'the decision is gone'); + assert.match(r.after, /decides: AMB-001/, 'the usable one is bound to its relation'); +}); + +// LEDGER #141 — a `differential:` entry names its check with `anchor:`, not `relation:`. +// +// Measured 2026-11-09: run-14's repair dropped REL-001 and REL-002 as out-of-list, left DIFF-001 +// (`anchor: independent-aggregation`) alone, and the forge refused the document for the relation that +// survived. The two keys carry the same relation kinds, and a repair that speaks only one vocabulary +// leaves half the document unexamined — which looks like the repair did nothing. +test('an out-of-list `anchor:` is dropped just like a `relation:`', () => { + const doc = [ + 'requirements:', + ' - id: REQ-001', + ' title: t', + 'deliverable:', + ' run: "bash s.sh {csv}"', + 'ambiguities:', + ' - id: AMB-001', + ' question: q', + ' default: "half-up"', + ' checkedAs: half-up', + ' blocking: true', + 'relations:', + ' - id: REL-001', + ' relation: derived-ratio', + ' description: ratio', + 'differential:', + ' - id: DIFF-001', + ' anchor: independent-aggregation', + ' decides: AMB-001', + ' description: anchor', + '', + ].join('\n'); + const r = repair(doc, SHAPE.replace(/ALLOWED_RELATIONS:.*/, 'ALLOWED_RELATIONS: derived-ratio')); + assert.equal(r.status, 0, r.out); + assert.match(r.out, /dropped DIFF-001 \(independent-aggregation\)/, 'the anchor is named as dropped'); + assert.doesNotMatch(r.after, /anchor: independent-aggregation/, 'and it is gone'); + assert.match(r.after, /relation: derived-ratio/, 'the allowed relation survives'); +}); + +// LEDGER #142 — two ids on one key. +// +// Measured 2026-11-09: `- id: SCN-001 SCN-002` — one key, two identifiers — and the forge refused the +// whole document with "the scenario SCN-001 SCN-002 declares no run", because it looks up a scenario by +// the exact id and found a string naming two. +// +// Nothing about it is a judgement: a key holds one value, so the second id is an entry that lost its own +// `- id:` line. The repair keeps the first id (its block carries the fields) and drops the extra, saying +// so — a second id needs its own entry with its own run, and inventing one would be a check nobody wrote. +test('two ids on one key are split down to one, and the drop is reported', () => { + const doc = [ + 'requirements:', + ' - id: REQ-001', + ' title: t', + 'deliverable:', + ' run: "bash s.sh {csv}"', + ' scenarios:', + ' - id: SCN-001 SCN-002', + ' expect: "the report lists a line per suite"', + ' run: "bash check.sh"', + 'ambiguities:', + ' - id: AMB-001', + ' question: q', + ' default: "half-up"', + ' checkedAs: half-up', + ' blocking: true', + 'relations:', + ' - id: REL-001', + ' relation: derived-ratio', + ' description: r', + '', + ].join('\n'); + const r = repair(doc, SHAPE.replace(/ALLOWED_RELATIONS:.*/, 'ALLOWED_RELATIONS: derived-ratio')); + assert.equal(r.status, 0, r.out); + assert.match(r.out, /- id: SCN-001 SCN-002.*named two entries on one key/s, 'the defect is named'); + assert.match(r.out, /DROPPED `SCN-002`/, 'and which id was dropped'); + assert.match(r.after, /- id: SCN-001\s*$/m, 'the first id survives alone'); + assert.doesNotMatch(r.after, /SCN-001 SCN-002/, 'no key names two ids'); + assert.match(r.after, /expect:/, 'its fields are intact'); +}); diff --git a/packages/core/src/test/intake-shape-records-why.test.ts b/packages/core/src/test/intake-shape-records-why.test.ts new file mode 100644 index 0000000..e656fd4 --- /dev/null +++ b/packages/core/src/test/intake-shape-records-why.test.ts @@ -0,0 +1,114 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * LEDGER #126 — the shape gate must record WHY the forge refused, not just that it did. + * + * Measured 2026-11-08: every `intake_shape` refusal read + * + * not ok 4 - a judge can be forged from the document as the confirmation will leave it + * (exit 1: no delivery could be judged against this document) + * + * and nothing else. The forge DOES print its reason as comment lines, but `#103` budgets the gate's + * summary and keeps the failing lines first — so the sentence naming the defect was the one thing cut, + * on every single refusal. Diagnosing the intake's 1-in-3 first-attempt rate was impossible from the + * records for that reason alone. + * + * The first line of a forge refusal is its verdict, so it is repeated up front, prefixed so it is + * greppable in a log and survives any truncation that keeps the head. + */ + +const SCRIPT = join( + dirname(fileURLToPath(import.meta.url)), + '../../../../extensions/workflows/request-intake/checks/intake-shape-tap.sh', +); + +test('a forge refusal is repeated as `# FORGE SAID:` before the transcript', () => { + const body = readFileSync(SCRIPT, 'utf8'); + assert.match(body, /FORGE SAID/, 'the marker exists'); + assert.match( + body, + /head -1 \| sed 's\/\^\/# FORGE SAID: \/'/, + 'it repeats the forge\'s first line, which is its verdict', + ); + // It must be conditional on failure: a successful forge has no refusal to quote. + assert.match(body, /if \[ "\$FORGE_STATUS" -ne 0 \]/, 'only when the forge failed'); +}); + +test('the marker is emitted ABOVE the comment transcript, so truncation cannot eat it', () => { + // A budget that keeps the head must keep the marker. Asserting the order in the source is the only + // way to check this without running the whole gate. + const body = readFileSync(SCRIPT, 'utf8'); + const marker = body.indexOf('FORGE SAID'); + const transcript = body.indexOf('printf \'%s\\n\' "$FORGE_OUT" | sed \'s/^/# /\''); + assert.ok(marker > 0 && transcript > 0, 'both lines exist'); + assert.ok(marker < transcript, 'the verdict comes first'); +}); + +test('the gate still records the failing check itself', () => { + const body = readFileSync(SCRIPT, 'utf8'); + assert.match( + body, + /not_ok "a judge can be forged from the document as the confirmation will leave it \(exit \$FORGE_STATUS/, + 'the `not ok` line survives, so #103 keeps working', + ); +}); + +test('a running gate prints the marker before the reason it already printed', () => { + // Drive the real script over a document whose forge will refuse, and read the TAP it emits. + // The gate resolves the validator and the forge RELATIVE TO THE PROJECT, so it must run from the real + // repository while the DOCUMENT under test lives in a temp dir (TAKUMI_INTAKE_DOC is absolute). + const REPO = join(dirname(fileURLToPath(import.meta.url)), '../../../..'); + const dir = mkdtempSync(join(tmpdir(), 'shape-said-')); + try { + const docs = join(dir, 'docs/requirements'); + mkdirSync(docs, { recursive: true }); + // Two scenarios collapsed into one id: the forge refuses by name, which is the case that was + // invisible in the records. + writeFileSync( + join(docs, 'intake.yaml'), + [ + 'requirements:', + ' - id: REQ-001', + ' title: one requirement', + ' acceptance_criteria:', + ' - something checkable', + 'deliverable:', + ' run: "bash summary.sh {csv}"', + ' input_format:', + ' columns: "suite:id,passed:measure,total:other"', + ' sample: |', + ' a,1,2', + ' b,0,1', + ' output_format:', + ' suite_line:', + ' shape: " "', + ' fields: [id, numerator, denominator, ratio]', + ' scenarios:', + ' - id: SCN-001 SCN-002', + ' expect: "the report lists a line per suite"', + ' relations:', + ' - id: REL-001', + ' relation: derived-ratio', + ' description: each percentage is passed/total', + '', + ].join('\n'), + ); + const r = spawnSync('bash', [SCRIPT], { + cwd: REPO, + encoding: 'utf8', + env: { ...process.env, TAKUMI_INTAKE_DOC: join(docs, 'intake.yaml') }, + }); + const out = `${r.stdout}${r.stderr}`; + // If the forge accepted this document the marker would be absent, which would prove nothing about + // the marker — but the fixture is built to be refused, so require the marker. + assert.match(out, /# FORGE SAID: /, `the gate must quote the forge's verdict. Output:\n${out.slice(0, 2000)}`); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/core/src/test/produced-output.test.ts b/packages/core/src/test/produced-output.test.ts index 79aab62..a54bcc1 100644 --- a/packages/core/src/test/produced-output.test.ts +++ b/packages/core/src/test/produced-output.test.ts @@ -251,7 +251,18 @@ test('the REAL intake manifests declare the document its agent step must produce // The gate that reads the document must depend on the step that produces it, or the declaration // is checked after something has already read the stale file. const gate = (def.steps ?? []).find((s) => s.type === 'quality_gate'); - assert.ok((gate?.dependsOn ?? []).includes(agent?.id ?? ''), 'the shape gate depends on the agent step'); + // LEDGER #129: the gate depends on `intake_repair`, which depends on the agent. The gate still judges + // the DOCUMENT THE AGENT WROTE — the repair only fills in what step 1 had already decided — so the + // chain is asserted link by link rather than collapsed into one edge. + assert.ok( + (gate?.dependsOn ?? []).includes('intake_repair'), + 'the shape gate depends on the repair step', + ); + const repair = (def.steps ?? []).find((s) => s.id === 'intake_repair'); + assert.ok( + (repair?.dependsOn ?? []).includes(agent?.id ?? ''), + 'and the repair acts on the document the agent wrote', + ); }); // --------------------------------------------------------------------------------------------- @@ -326,3 +337,73 @@ test('the document step is told the list is a CONSTRAINT, not a suggestion', () assert.match(prompt, /SUBSET/, 'and calls it a subset constraint'); assert.match(prompt, /may not use any other|REFUSED/, 'with the consequence stated'); }); + +// LEDGER #127: the shape step also decides what the ROUNDING answer MEANS. +// +// Measured 2026-11-08 on a real run: a ratio document settled its rounding decision but wrote no +// `checkedAs`, so the forge refused the whole document — +// the decision AMB-001 is settled by REL-001, and the relation needs to know what its answer MEANS: +// give it "checkedAs: " +// — and the run was lost before a line of code was written. The rule is #12 of the 400-line document +// prompt and was ignored there, which is the same thing that happened to the field model (#102), the +// entry point (#107) and the relation list (#121). So it is decided in the 60-line step instead. +test('the shape step decides the rounding mode, with the default spelled out', () => { + const prompt = readFileSync( + new URL('../../../../extensions/skills/req-intake/prompts/shape.md', import.meta.url), + 'utf8', + ); + assert.match(prompt, /^ROUNDING_MEANS: /m, 'the step emits the line'); + assert.match(prompt, /`half-up` — a value exactly halfway rounds away from zero/, 'half-up is defined'); + assert.match(prompt, /`truncate` — everything after the last printed digit is dropped/, 'truncate is defined'); + assert.match( + prompt, + /without qualifying it, answer `half-up`/, + 'the unqualified case is decided for the model rather than left to taste', + ); + assert.match(prompt, /NONE/, 'a shape with nothing rounded says so'); +}); + +test('the document step is told `checkedAs` must carry that word, on the DECISION', () => { + const def = parseYaml( + readFileSync(new URL('../../../../extensions/workflows/intake-attempt/workflow.yaml', import.meta.url), 'utf8'), + ) as WorkflowDefinition; + const doc = (def.steps ?? []).find((s) => (s.produces ?? []).includes('docs/requirements/intake.yaml')); + const prompt = String(doc?.prompt ?? ''); + assert.match(prompt, /ROUNDING_MEANS/, 'it names the line'); + assert.match(prompt, /checkedAs/, 'and the field it fills'); + assert.match( + prompt, + /ON THE AMB-nnn ENTRY next to `chosen:`, never on the relation/i, + 'with the placement the forge actually enforces', + ); +}); + +// LEDGER #139 — the shape step must also say which decisions NOT to write. +// +// Measured 2026-11-09: a ratio document narrowed its relations correctly to the four that can read a +// ratio line, and THEN recorded blocking decisions "what happens to a malformed row" (checkedAs: +// skip-count) and "what happens to a repeated id" (checkedAs: merge) — decisions only +// `malformed-row-accounting` and `duplicate-resolution` can verify, and those cannot read a ratio line. +// The forge refused with "blocking decision(s) AMB-001, AMB-002 are exercised by no declared relation". +// +// A list of what IS allowed is not enough: the model still writes the decision the request implies. The +// prompt has to say what to do with that impulse instead. +test('the shape step forbids on a QUOTIENT answer the decisions its relations cannot check', () => { + const prompt = readFileSync( + new URL('../../../../extensions/skills/req-intake/prompts/shape.md', import.meta.url), + 'utf8', + ); + assert.match(prompt, /DO NOT WRITE THOSE DECISIONS AT ALL/, 'the half that was missing'); + assert.match(prompt, /skip-count/, 'it names the malformed-row decision'); + assert.match(prompt, /merge/, 'and the duplicate one'); + assert.match( + prompt, + /State the behaviour in the REQUIREMENT text instead/, + 'and says where the behaviour goes instead of into an unverifiable decision', + ); + assert.match( + prompt, + /A decision\s+nothing can check is worse than no decision/, + 'with the reason a reader can act on', + ); +}); diff --git a/packages/core/src/test/quality-gate-output.test.ts b/packages/core/src/test/quality-gate-output.test.ts index 3f29270..4531cb7 100644 --- a/packages/core/src/test/quality-gate-output.test.ts +++ b/packages/core/src/test/quality-gate-output.test.ts @@ -65,3 +65,32 @@ test('the kept text names how much was dropped, so a truncated summary is visibl assert.match(kept, /not ok 1 - the real reason/); assert.match(kept, /\d+ earlier line\(s\) omitted|\d+ line\(s\) omitted/, 'the cut is stated, not silent'); }); + +// LEDGER #128 — a tool's own refusal line survives the budget. +// +// #126 made the intake shape gate repeat the forge's verdict as `# FORGE SAID: ...`, and the next real +// run still recorded nothing: `#103`'s budget only rescues lines matching its FALSIFYING pattern, and +// that pattern knew `not ok`, `FAILED`, `Error:` — not a `#` diagnostic. TAP reserves `#` for +// diagnostics, so a harness that explains itself writes comments, and those comments were the one thing +// cut. Twice in a row the fix was defeated by the budget it was written for. +test('a `# FORGE SAID:` comment past the head budget is rescued', () => { + const out = [ + 'ok 1 - wrote the document', + ...Array.from({ length: 40 }, (_, i) => `# decision ${i}: a line of explanatory prose`), + '# FORGE SAID: the decision AMB-001 is settled by REL-001, and the relation needs checkedAs', + 'not ok 4 - a judge can be forged from the document', + ].join('\n'); + const kept = summariseGateOutput(out); + assert.match(kept, /# FORGE SAID: the decision AMB-001/, `the verdict must survive:\n${kept}`); +}); + +test('other self-explaining harness lines are rescued too', () => { + const out = [ + ...Array.from({ length: 60 }, (_, i) => `ok ${i + 1} - check ${i}`), + '# REFUSED: the document declares two scenarios under one id', + '# reason: one mutation block configures one check', + ].join('\n'); + const kept = summariseGateOutput(out); + assert.match(kept, /# REFUSED: the document declares two scenarios under one id/); + assert.match(kept, /# reason: one mutation block configures one check/); +}); diff --git a/packages/core/src/test/repair-brief-and-bounds.test.ts b/packages/core/src/test/repair-brief-and-bounds.test.ts index 02d7655..1fb4085 100644 --- a/packages/core/src/test/repair-brief-and-bounds.test.ts +++ b/packages/core/src/test/repair-brief-and-bounds.test.ts @@ -275,7 +275,16 @@ test('the manifests carry the wiring: the intake is a repair round, and the deli /- id: intake_shape[\s\S]*?type: quality_gate/, 'the gate is the attempt’s verdict: a repair sub-workflow needs a verdict step, and here that is a shape gate — an `acceptance` would be bound to a confirmed requirement that cannot exist yet', ); - assert.match(sub, /- id: intake_shape[\s\S]*?dependsOn: \[req_intake\]/, 'the gate runs on the document the agent wrote'); + // LEDGER #129: `intake_repair` sits between the agent and the gate, because the document it judges is + // the agent's own with step 1's decided values filled in — NOT a different document. The gate must + // therefore depend on the repair, and the repair on the agent, or the chain could judge a document + // nobody wrote. + assert.match( + sub, + /- id: intake_repair[\s\S]*?dependsOn: \[[^\]]*req_intake[^\]]*\]/, + 'the repair acts on the agent\'s document', + ); + assert.match(sub, /- id: intake_shape[\s\S]*?dependsOn: \[intake_repair\]/, 'the gate runs on the repaired document'); const delivery = read('extensions/workflows/request-to-delivery-attempt/workflow.yaml'); for (const id of ['implementation', 'unit_and_integration_tests']) { diff --git a/packages/core/src/workflow-engine.ts b/packages/core/src/workflow-engine.ts index e9300f9..95eb603 100644 --- a/packages/core/src/workflow-engine.ts +++ b/packages/core/src/workflow-engine.ts @@ -522,7 +522,13 @@ export function stepArtifactKind(step: WorkflowStep, fallback: string): string { /** Render a step prompt by resolving {placeholders} from the run context. */ export function renderPrompt(template: string, vars: Record): string { - return template.replace(/\{(\w+)\}/g, (m, key: string) => vars[key] ?? m); + // LEDGER #133: a var name may contain DOTS. `{step.shape_decision}` is how one step hands its own + // answer to the next, and `\w+` — the pattern this used — does not match a dot, so every such + // placeholder reached the shell verbatim. Measured 2026-11-08: two real runs died with + // "intake-repair: step 1 recorded no ANSWER_SHAPE" while step 1 had answered, because the script + // received the literal text `{step.shape_decision}`. The engine leaves unknown keys alone on purpose + // (an unfilled placeholder should be visible), which is why this failed quietly instead of throwing. + return template.replace(/\{([\w.]+)\}/g, (m, key: string) => vars[key] ?? m); } /** Resolve trace ids carried in the run vars (REQ-001, DESIGN-001, ...). */ diff --git a/scripts/intake-repair.sh b/scripts/intake-repair.sh new file mode 100644 index 0000000..13f7a31 --- /dev/null +++ b/scripts/intake-repair.sh @@ -0,0 +1,490 @@ +#!/usr/bin/env bash +# REPAIR THE DOCUMENT FROM WHAT STEP 1 ALREADY DECIDED (ledger #129). +# +# WHY THIS EXISTS. The intake's first attempt passes its own gate about one time in three (measured +# 2026-11-08: 1 of 3, twice). The failures are not mysterious any more — #126/#128 made the forge's own +# words visible — and they are almost all the SAME SHAPE: a decision step 1 already made correctly is +# missing from the document. +# +# * `checkedAs:` absent on the decision a derived-ratio / independent-aggregation relation settles, +# while step 1 answered `ROUNDING_MEANS: half-up`. +# * `deliverable.run` absent or different, while step 1 answered `ENTRY_POINT: bash x.sh {csv}`. +# * a per-id line carrying BOTH an aggregate field and a ratio field, while step 1 answered +# `ANSWER_SHAPE: QUOTIENT` and `ALLOWED_RELATIONS:` lists what is checkable. +# +# Every one of those is DETERMINISTIC: the answer is already known, and the document merely failed to +# carry it. Asking the model to write the whole document again to fix a missing word is how the rate +# stayed at 1 in 3 through four rounds of prompt rules (#102, #107, #121, #127). This repairs the +# document from step 1's own answers instead, and refuses when step 1 did not decide the thing. +# +# It NEVER invents a decision: `ROUNDING_MEANS: NONE` means there is no rounding answer to record, so a +# relation that settles one is refused rather than given a mode nobody chose. +# +# Usage: +# intake-repair.sh --doc (--shape | --shape-text "") [--dry-run] +# +# The shape file is the text step 1 wrote (ANSWER_SHAPE / ENTRY_POINT / ALLOWED_RELATIONS / +# ROUNDING_MEANS lines). Exit: 0 repaired or already correct, 1 refusal (names why), 2 bad inputs. +set -u + +DOC=""; SHAPE=""; DRY=0; SHAPE_IS_TEXT=0 +while [ $# -gt 0 ]; do + case "$1" in + --doc) DOC="${2:-}"; shift 2 ;; + --shape) SHAPE="${2:-}"; shift 2 ;; + --shape-text) SHAPE="${2:-}"; SHAPE_IS_TEXT=1; shift 2 ;; + --dry-run) DRY=1; shift ;; + *) echo "intake-repair: unknown option '$1'" >&2; exit 2 ;; + esac +done +[ -n "$DOC" ] || { echo "intake-repair: --doc is required" >&2; exit 2; } +[ -n "$SHAPE" ] || { echo "intake-repair: --shape is required" >&2; exit 2; } +[ -f "$DOC" ] || { echo "intake-repair: '$DOC' does not exist" >&2; exit 2; } +if [ "${SHAPE_IS_TEXT:-0}" != 1 ]; then + [ -f "$SHAPE" ] || { echo "intake-repair: the shape decision '$SHAPE' does not exist" >&2; exit 2; } + SHAPE_FILE="$SHAPE" +else + # Step 1's answer arrives as TEXT through the engine's per-step vars, so it is written to a temp file + # here rather than requiring the manifest to name a path that does not exist. + SHAPE_FILE=$(mktemp) + printf '%s\n' "$SHAPE" > "$SHAPE_FILE" + trap 'rm -f "$SHAPE_FILE"' EXIT +fi +SHAPE="$SHAPE_FILE" + +# Step 1 answers inside a ``` fence (the prompt shows a code block), so the fence lines and any +# indentation are stripped before a key is read. Measured 2026-11-08: `{step.shape_decision}` began with +# a fence, `sed -n "s/^KEY://p"` matched nothing, and every repair refused with "no ANSWER_SHAPE" for a +# second, unrelated reason. +field() { # $1 key, prints the value or nothing + sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' "$SHAPE" \ + | sed -n "s/^$1:[[:space:]]*//p" \ + | head -1 +} + +ANSWER=$(field ANSWER_SHAPE) +ENTRY=$(field ENTRY_POINT) +ROUNDING=$(field ROUNDING_MEANS) +ALLOWED=$(field ALLOWED_RELATIONS) + +[ -n "$ANSWER" ] || { echo "intake-repair: step 1 recorded no ANSWER_SHAPE, so there is nothing to repair FROM" >&2; exit 2; } + +python3 - "$DOC" "$ANSWER" "$ENTRY" "$ROUNDING" "$ALLOWED" "$DRY" <<'PYEOF' +import re, sys + +doc_path, answer, entry, rounding, allowed, dry = sys.argv[1:7] +dry = dry == '1' +allowed = [x.strip() for x in re.split(r'[,\s]+', allowed) if x.strip()] +text = open(doc_path, encoding='utf-8').read() +original = text +notes = [] +refusals = [] + +# ---------------------------------------------------------------- 0. the document must be YAML at all +# LEDGER #137: this script EDITS the document. Measured 2026-11-08: a real run handed it a document whose +# `source:` value contained an unescaped quote, so the YAML did not parse — and a text-matching repair on a +# broken document can silently make it worse (it edits lines it thinks it understands). The validator runs +# right after this step and reports "not valid YAML", but by then the repair has already touched the file. +# Refusing early is both safer and clearer, and it needs no YAML parser of its own: the project's own CLI +# already answers this question. +def parses(text): + import subprocess, tempfile, os + # The CLI resolves the ref RELATIVE TO ITS CWD, so the temp file goes beside the document and the + # ref is its basename — an absolute path would be reported as "does not exist in ", which is a + # different failure and would have masked a genuinely broken document. + # The CLI is at a path relative to the PROJECT and resolves its ref from that same root, so the + # probe file goes under the project's own `.takumi/` and the ref is relative to the root. + root = os.environ.get('TAKUMI_PROJECT') or os.getcwd() + probe_dir = os.path.join(root, '.takumi') + os.makedirs(probe_dir, exist_ok=True) + fd, tmp = tempfile.mkstemp(suffix='.yaml', prefix='yaml-probe-', dir=probe_dir) + with os.fdopen(fd, 'w', encoding='utf-8') as fh: + fh.write(text) + ref = os.path.relpath(tmp, root) + try: + r = subprocess.run( + ['node', 'apps/cli/dist/index.js', 'requirement', 'confirm', ref, '--dry-run'], + capture_output=True, text=True, timeout=60, cwd=root, + ) + # `confirm --dry-run` reports a broken document in its OUTPUT and still exits 0, so the verdict is + # in the text. `digest` cannot be used: it hashes whatever it is given, valid or not. + out = (r.stderr or '') + (r.stdout or '') + if 'not valid YAML' in out: + return (False, out.strip()) + return (True, '') + except Exception as exc: # noqa: BLE001 - any failure to ask is a refusal to repair + return (False, str(exc)) + finally: + os.unlink(tmp) + + +ok_yaml, why = parses(text) +if not ok_yaml: + print('intake-repair: refused — the document is not valid YAML, so there is nothing safe to repair:', file=sys.stderr) + print(' ' + why.splitlines()[0] if why else ' (no detail)', file=sys.stderr) + print(' A text repair on a document that does not parse can silently make it worse. Fix the YAML first.', file=sys.stderr) + sys.exit(1) + +# ---------------------------------------------------------------- split into top-level blocks +lines = text.split('\n') + + +def block_bounds(name): + """(start, end) line indices of a top-level `name:` block, end exclusive.""" + start = None + for i, line in enumerate(lines): + if re.match(rf'^{re.escape(name)}:\s*$', line): + start = i + break + if start is None: + return None + end = len(lines) + for j in range(start + 1, len(lines)): + if re.match(r'^[A-Za-z_][A-Za-z0-9_]*:', lines[j]): + end = j + break + return (start, end) + + +# ---------------------------------------------------------------- 1. deliverable.run +if entry: + bounds = block_bounds('deliverable') + if bounds is None: + refusals.append('the document has no `deliverable` block, so there is nowhere to put the entry point step 1 decided') + else: + start, end = bounds + run_at = None + for i in range(start + 1, end): + if re.match(r'^ run:', lines[i]): + run_at = i + break + want = f' run: "{entry}"' + if run_at is None: + lines.insert(start + 1, want) + notes.append(f'added `deliverable.run: {entry}` (step 1 decided the entry point and the document had none)') + else: + have = lines[run_at] + if have.strip() != want.strip(): + lines[run_at] = want + notes.append(f'replaced `{have.strip()}` with `{want.strip()}` (step 1 decided the entry point)') + +# ---------------------------------------------------------------- 2. checkedAs on a decision a ratio relation settles +# Which decisions are settled by a relation that needs `checkedAs`? A relation whose kind is +# derived-ratio or independent-aggregation names its decision with `decides:`. +text = '\n'.join(lines) +needs = set() +for m in re.finditer(r'-\s+id:\s*(REL-\d+)\s*\n(?:.*\n)*?\s+relation:\s*([a-z-]+)\s*\n(?:.*\n)*?\s+decides:\s*(AMB-\d+)', text): + _rel, kind, amb = m.group(1), m.group(2), m.group(3) + if kind in ('derived-ratio', 'independent-aggregation'): + needs.add((amb, kind)) + +if needs: + if not rounding or rounding.upper() == 'NONE': + for amb, kind in sorted(needs): + refusals.append( + f'{amb} is settled by a {kind} relation, which needs `checkedAs:`, and step 1 answered ' + f'ROUNDING_MEANS: {rounding or "(nothing)"} — there is no rounding answer to record, so the ' + f'document either settled the wrong decision or declared the wrong relation' + ) + else: + for amb, kind in sorted(needs): + # Find the AMB block and add checkedAs next to its default (or after its options, when there + # is no default) — the placement the forge documents. + pat = re.compile(rf'(^([ ]*)- id: {re.escape(amb)}\s*\n(?:.*\n)*?)(?=^\2?- id: |\Z)', re.M) + m = pat.search('\n'.join(lines)) + if not m: + refusals.append(f'{amb} is named by a relation but has no entry in `ambiguities`') + continue + body = m.group(1) + if re.search(r'^\s+checkedAs:', body, re.M): + continue + body_lines = body.rstrip('\n').split('\n') + indent = re.match(r'^([ ]*)', body_lines[1]).group(1) if len(body_lines) > 1 else ' ' + insert_at = None + for i, line in enumerate(body_lines): + if re.match(r'\s+(default|chosen):', line): + insert_at = i + 1 + if insert_at is None: + insert_at = len(body_lines) + body_lines.insert(insert_at, f'{indent}checkedAs: {rounding}') + repaired = '\n'.join(body_lines) + '\n' + joined = '\n'.join(lines) + joined = joined.replace(body, repaired, 1) + lines = joined.split('\n') + notes.append(f'added `checkedAs: {rounding}` to {amb} (step 1 decided ROUNDING_MEANS: {rounding})') + +# ---------------------------------------------------------------- 3. a per-id line mixing the two field models +AGG = {'count', 'sum', 'min', 'max', 'mean'} +RATIO = {'numerator', 'denominator', 'ratio'} +text = '\n'.join(lines) +for m in re.finditer(r'( +)fields:\s*\[([^\]]*)\]', text): + roles = [r.strip() for r in m.group(2).split(',')] + roleset = set(roles) + has_agg, has_ratio = bool(roleset & AGG), bool(roleset & RATIO) + if not (has_agg and has_ratio): + continue + if answer == 'QUOTIENT': + keep = roleset & (RATIO | {'id', 'skipped-count'}) + notes.append( + 'a line declared both field models; step 1 answered QUOTIENT, so the aggregate roles cannot be ' + 'dropped automatically — the line shapes and the requirement text must be rewritten to match' + ) + else: + notes.append( + 'a line declared both field models; step 1 answered AGGREGATE, so the ratio roles cannot be dropped ' + 'automatically — the line shapes and the requirement text must be rewritten to match' + ) + refusals.append( + 'the per-id output line mixes the two field models (it declares both an aggregate field and a ratio ' + 'field). Step 1 answered ' + + answer + + ', but a field list cannot be repaired without rewriting the line shapes and the requirement text that ' + 'quote them — that is a rewrite, not a repair, so it is refused here instead of guessed at' + ) + +# ---------------------------------------------------------------- 4. a relation step 1 did not allow +# LEDGER #136: step 1 emits `ALLOWED_RELATIONS` for the shape it chose, and #121 tells the document step +# that `relations:` must be a SUBSET of it — the model still wrote `independent-aggregation` on a ratio +# document, and the forge refused the run with "it recomputes COUNTS or SUMS from the fixture and a ratio +# line carries none". Step 1 had already said so. A relation outside the list is DROPPED here, because +# leaving it in refuses the run and keeping it silently would be a document that declares a check it +# cannot have. +if allowed: + text = '\n'.join(lines) + out_lines = [] + dropped = [] + i = 0 + src = text.split('\n') + while i < len(src): + line = src[i] + m = re.match(r'^( *)- id:\s*([A-Z]+-\d+)\s*$', line) + if not m: + out_lines.append(line) + i += 1 + continue + indent, rel_id = m.group(1), m.group(2) + # Collect the whole entry: it runs until a line at or above its own indent that starts a new item. + j = i + 1 + while j < len(src): + follow = src[j] + if re.match(rf'^{indent}- ', follow) or (follow.strip() and not follow.startswith(indent + ' ')): + break + j += 1 + entry = src[i:j] + # LEDGER #141: a `differential:` entry names its check with `anchor:`, not `relation:` — the two + # vocabularies are the same relation kinds under different keys. Measured 2026-11-09: the repair + # dropped `REL-001` and `REL-002` and left `DIFF-001` (anchor: independent-aggregation) in place, + # and the forge refused the document for the relation that survived. + kind = None + for ln in entry: + km = re.match(r'^\s*(?:relation|anchor):\s*([a-z-]+)\s*$', ln) + if km: + kind = km.group(1) + break + if kind and kind not in allowed: + dropped.append((rel_id, kind)) + else: + out_lines.extend(entry) + i = j + if dropped: + for rel_id, kind in dropped: + notes.append( + f'dropped {rel_id} ({kind}): step 1 answered ALLOWED_RELATIONS without it, and a relation that ' + f'cannot read this report refuses the whole document' + ) + lines = '\n'.join(out_lines).split('\n') + +# ---------------------------------------------------------------- 5. a blocking decision no check exercises +# LEDGER #138: the forge refuses `blocking decision(s) AMB-NNN are exercised by no declared relation or +# anchor`. Measured 2026-11-09 — this was the single most common remaining failure, twice in a row. +# +# It is NOT a guess which relation owns a decision, because the document ALREADY SAYS what the answer +# means: `checkedAs:`. The forge's own table maps a mode to the relations that can verify it — +# skip-count | skip-silent | stop-error -> malformed-row-accounting +# first-row | last-row | latest-start-date | merge | error -> duplicate-resolution +# half-up | truncate -> derived-ratio | independent-aggregation +# So a decision whose mode is `half-up` and which no relation names can only be settled by a rounding +# relation — and if exactly one such relation is declared, that is where `decides:` belongs. This is +# derived from two fields the document already carries, not invented. +# +# It refuses when the inference is not unique: two rounding relations and no way to tell them apart, or +# no relation of the needed kind at all. A wrong `decides:` would have the judge verify a decision the +# document never meant, which is worse than the refusal. +MODE_TO_RELATION = { + 'skip-count': 'malformed-row-accounting', + 'skip-silent': 'malformed-row-accounting', + 'stop-error': 'malformed-row-accounting', + 'first-row': 'duplicate-resolution', + 'last-row': 'duplicate-resolution', + 'latest-start-date': 'duplicate-resolution', + 'merge': 'duplicate-resolution', + 'error': 'duplicate-resolution', + 'half-up': None, + 'truncate': None, +} +ROUNDING_KINDS = ('derived-ratio', 'independent-aggregation') +ROUNDING_MODES = ('half-up', 'truncate') + +if True: + text = '\n'.join(lines) + # decisions that exist, with their mode and whether they are blocking + ambs = {} + for m in re.finditer(r'^( *)- id: (AMB-\d+)\s*\n((?:\1 +.*\n|\s*\n)*)', text, re.M): + body = m.group(3) + mode = re.search(r'^\s*checkedAs:\s*([a-z-]+)\s*$', body, re.M) + blocking = re.search(r'^\s*blocking:\s*true\s*$', body, re.M) + ambs[m.group(2)] = (mode.group(1) if mode else None, bool(blocking)) + # relations that exist, with their kind and what they already decide + rels = [] + for m in re.finditer(r'^( *)- id: ([A-Z]+-\d+)\s*\n((?:\1 +.*\n|\s*\n)*)', text, re.M): + body = m.group(3) + kind = re.search(r'^\s*(?:relation|anchor):\s*([a-z-]+)\s*$', body, re.M) + decides = re.search(r'^\s*decides:\s*(AMB-\d+)\s*$', body, re.M) + if kind: + rels.append((m.group(2), kind.group(1), decides.group(1) if decides else None)) + + covered = {d for (_rid, _k, d) in rels if d} + for amb_id, (mode, blocking) in sorted(ambs.items()): + if not blocking or amb_id in covered: + continue + if mode is None: + continue # no mode: nothing in the document says what would check it + # `mode` is a MODE (`half-up`), `ROUNDING_KINDS` are RELATION KINDS (`derived-ratio`) — the two + # vocabularies must not be compared to each other. + need = MODE_TO_RELATION.get(mode) + if mode in ROUNDING_MODES: + candidates = [(rid, kind) for (rid, kind, decided) in rels if kind in ROUNDING_KINDS and not decided] + elif need is not None: + candidates = [(rid, kind) for (rid, kind, decided) in rels if kind == need and not decided] + else: + candidates = [] + if len(candidates) == 1: + rid, kind = candidates[0] + # Named groups: the back-reference must point at the INDENT group, and inside an f-string + # `\1` would be renumbered by the braces around `rid`. + pat = re.compile( + rf'^(?P *)- id: {re.escape(rid)}\s*\n(?:(?P=ind) +.*\n|\s*\n)*?(?=^ *- id: |\Z)', + re.M, + ) + m = pat.search('\n'.join(lines)) + if m: + entry = m.group(0) + indent = ' ' * 6 + entry_new = entry.rstrip('\n') + f'\n{indent}decides: {amb_id}\n' + joined = '\n'.join(lines).replace(entry, entry_new, 1) + lines = joined.split('\n') + covered.add(amb_id) + notes.append( + f'{amb_id} (blocking, checkedAs: {mode}) had no check; `decides: {amb_id}` added to {rid} ' + f'({kind}) — the only declared relation whose kind can verify that mode' + ) + elif len(candidates) == 0: + # LEDGER #140: nothing the document may declare can verify this decision, so it must GO. + # + # Measured 2026-11-09, twice: a ratio document kept recording "what happens to a repeated id" + # (`merge`) and "what happens to a malformed row" (`skip-count`) as blocking ambiguities, while + # its ALLOWED_RELATIONS — correctly, see #139 — contains neither `duplicate-resolution` nor + # `malformed-row-accounting` because both read a `count` role a ratio totals line no longer + # carries (#108). #139's prompt said not to write them; the model wrote them anyway, which is + # the fifth rule to fail that way. + # + # The decision is DETERMINISTICALLY unusable: no vocabulary the document may use can check it. + # So it is removed and its chosen behaviour is moved into the requirement text, where it is a + # plain instruction to the implementer — what the prompt asked for, done by code instead. + verb = MODE_TO_RELATION.get(mode) + if verb is None: + refusals.append( + f'{amb_id} is blocking with `checkedAs: {mode}`, and no relation can verify a rounding mode ' + f'here — this is not a decision the repair can place' + ) + continue + # Line-level removal: the block regexes above have to tolerate two-space and four-space + # nesting, and a block that failed to match would silently leave the decision in place — + # which is exactly the state that blocks the run. Walking the lines cannot miss. + src = '\n'.join(lines).split('\n') + out_lines = [] + i = 0 + removed = False + while i < len(src): + mm = re.match(rf'^( *)- id: {re.escape(amb_id)}\s*$', src[i]) + if not mm: + out_lines.append(src[i]) + i += 1 + continue + indent = mm.group(1) + entry = [src[i]] + j = i + 1 + while j < len(src): + follow = src[j] + if re.match(rf'^{indent}- ', follow) or (follow.strip() and not follow.startswith(indent + ' ')): + break + entry.append(follow) + j += 1 + chosen = None + for ln in entry: + cm = re.search(r'^\s*(?:chosen|default):\s*"?(.*?)"?\s*$', ln) + if cm: + chosen = cm.group(1) + break + behaviour = chosen if chosen else mode + removed = True + i = j + if removed: + lines = '\n'.join(out_lines).split('\n') + notes.append( + f'removed {amb_id} (blocking, checkedAs: {mode}): no relation this document may declare can verify ' + f'that mode, so the decision would block the run forever. Its answer — "{behaviour}" — belongs in ' + f'the requirement text as an instruction, not as a decision nothing can check' + ) + else: + refusals.append( + f'{amb_id} is blocking with `checkedAs: {mode}`, and MORE THAN ONE declared relation could verify ' + f'it ({", ".join(r for r, _ in candidates)}). Which one is meant is a judgment, not a repair' + ) + +# ---------------------------------------------------------------- 6. two ids on one entry +# LEDGER #142: `- id: SCN-001 SCN-002` — one key, two identifiers. Measured 2026-11-09: the forge refused +# the whole document with "the scenario SCN-001 SCN-002 declares no run", because it looks up a scenario by +# the exact id and found a string that names two. Nothing about it is a judgement: a key holds one value, +# so the extra id is a SECOND entry that lost its own `- id:` line. +# +# The repair SPLITS the entry: the first id keeps the fields, and the rest become their own entries with +# the same fields but no `run:` — because a scenario without a command is exactly what the forge refuses, +# and inventing a command would be a check nobody wrote. They are therefore dropped, not duplicated, and +# the drop is reported. +if True: + text = '\n'.join(lines) + renamed = [] + for m in re.finditer(r'^( *)- id:\s*([A-Z]+-\d+)\s+([A-Z]+-\d+(?:\s+[A-Z]+-\d+)*)\s*$', text, re.M): + indent, first, extra = m.group(1), m.group(2), m.group(3) + # Keep the FIRST id on this entry — it is the one whose block actually carries fields — and drop + # the extra ids, reporting them so a reader knows a scenario was lost rather than merged. + old_line = m.group(0) + new_line = f'{indent}- id: {first}' + text = text.replace(old_line, new_line, 1) + renamed.append((first, extra)) + if renamed: + lines = text.split('\n') + for first, extra in renamed: + notes.append( + f'`- id: {first} {extra}` named two entries on one key; kept `{first}` and DROPPED `{extra}` — ' + f'a second id needs its own entry with its own run, and inventing one would be a check nobody wrote' + ) + +# ---------------------------------------------------------------- refusals win over notes +if refusals: + print('intake-repair: refused —', file=sys.stderr) + for r in refusals: + print(f' * {r}', file=sys.stderr) + sys.exit(1) + +if not notes: + print('intake-repair: nothing to repair — the document already carries what step 1 decided') + sys.exit(0) + +if not dry: + open(doc_path, 'w', encoding='utf-8').write('\n'.join(lines)) +for n in notes: + print(f'intake-repair: {n}') +print('intake-repair: ' + ('would write (dry run)' if dry else 'wrote') + f' {doc_path}') +PYEOF diff --git a/scripts/measure-intake-rate.sh b/scripts/measure-intake-rate.sh index c625e84..f3aecc1 100644 --- a/scripts/measure-intake-rate.sh +++ b/scripts/measure-intake-rate.sh @@ -50,6 +50,7 @@ set -a; . /srv/hermes/.env; set +a FIRST_OK=0 TOTAL=0 +ERRORS=0 printf 'shape\trun\tfirst_attempt_ok\tdelivered\tseconds\n' > "$LOGDIR/report.tsv" for i in $(seq 1 "$N"); do @@ -62,10 +63,22 @@ for i in $(seq 1 "$N"); do elapsed=$(( $(date +%s) - started )) run_id=$(grep -oE 'run *: wf-[a-f0-9]+' "$log" | tail -1 | grep -oE 'wf-[a-f0-9]+') - # The repair wrapper writes `--- attempt 1 of 2: refused ---` when the FIRST attempt was refused. - if grep -q -- '--- attempt 1 of 2: refused ---' "$log"; then first=no; else first=yes; fi + # A FIRST ATTEMPT COUNTS AS PASSED ONLY IF THE INTAKE ACTUALLY COMPLETED (ledger #130). + # + # This used to be "no `--- attempt 1 of 2: refused ---` marker means passed", which reported a run that + # DIED BEFORE THE INTAKE EVER RAN as a first-attempt pass — measured 2026-11-08: three runs finished in + # 2-3 seconds with `step intake_attempt: failed — ... could not be run` and the report said 3 of 3. + # A measurement that can say "passed" about a run that never started is worse than no measurement. + if grep -q -- '--- attempt 1 of 2: refused ---' "$log"; then + first=no + elif grep -qE 'attempt accepted (on|after) .*attempt\(s\)|delivery accepted on the first attempt' "$log"; then + first=yes + else + first=error + fi if grep -qE '^== delivered' "$log"; then delivered=yes; else delivered=no; fi [ "$first" = yes ] && FIRST_OK=$((FIRST_OK + 1)) + [ "$first" = error ] && ERRORS=$((ERRORS + 1)) TOTAL=$((TOTAL + 1)) printf '%s\t%s\t%s\t%s\t%s\n' "$shape" "${run_id:-?}" "$first" "$delivered" "$elapsed" >> "$LOGDIR/report.tsv" echo " [$i/$N] $shape ${run_id:-?} first=$first delivered=$delivered ${elapsed}s" >&2 @@ -73,6 +86,10 @@ done echo echo "MEASURED: the intake's first attempt passed its own gate in $FIRST_OK of $TOTAL run(s)." +if [ "$ERRORS" -gt 0 ]; then + echo " $ERRORS run(s) never reached an intake verdict at all — they are counted as failures above," + echo " not as passes, because a run that could not start proves nothing about the intake." +fi echo "A first attempt that failed still delivered through the repair round — that is the REPAIR" echo "working, and it is not the same claim as the intake being reliable on the first try." echo "report: $LOGDIR/report.tsv"