rungate 0.8.7 → 0.8.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/gates/.gate-salt +1 -1
  2. package/hooks/StaleTTLCleanup.hook.ts +13 -5
  3. package/hooks/VerifyPhaseLock.hook.ts +8 -0
  4. package/hooks/lib/findWorkflow.ts +19 -3
  5. package/lib/active-workflow.ts +57 -0
  6. package/lib/ai-review-rounds.ts +223 -10
  7. package/lib/ai-review-suppression.ts +80 -127
  8. package/lib/ai-review-threads.ts +182 -6
  9. package/lib/board-mirror.ts +438 -0
  10. package/lib/cli-commands.ts +133 -0
  11. package/lib/config-readers.ts +34 -0
  12. package/lib/crc-reading.ts +655 -0
  13. package/lib/criterion-issue-census.ts +325 -0
  14. package/lib/filing-plan.ts +381 -0
  15. package/lib/generators/agents-md.ts +15 -11
  16. package/lib/git-isolation.ts +32 -0
  17. package/lib/github.ts +66 -0
  18. package/lib/issue-decomposition.ts +523 -0
  19. package/lib/issue-filing-gate.ts +304 -19
  20. package/lib/issue-repair.ts +225 -0
  21. package/lib/live-issues.ts +442 -0
  22. package/lib/project-state-shape.ts +30 -0
  23. package/lib/prose-self-distance.ts +414 -0
  24. package/lib/review-tool-agreement.ts +364 -15
  25. package/lib/sc-ids.ts +31 -1
  26. package/lib/scaffold/ai-review-findings.ts +64 -3
  27. package/lib/scaffold/ai-review-step.ts +501 -82
  28. package/lib/scaffold/owned-files.ts +60 -2
  29. package/lib/scaffold/steps.ts +130 -4
  30. package/lib/spec-deps.ts +257 -0
  31. package/lib/spec-evidence.ts +479 -0
  32. package/lib/spec-placement.ts +430 -0
  33. package/lib/spec-template.ts +206 -0
  34. package/lib/stage-ladder.ts +628 -0
  35. package/lib/worktree-cleanup.ts +438 -3
  36. package/package.json +12 -4
  37. package/scripts/ai-review-findings.ts +12 -17
  38. package/scripts/ai-review-threads.ts +51 -3
  39. package/scripts/audit-spec-evidence.ts +246 -0
  40. package/scripts/audit-specs.ts +27 -0
  41. package/scripts/board-conformance.ts +765 -0
  42. package/scripts/board-mirror.ts +344 -0
  43. package/scripts/board-snapshot.ts +459 -0
  44. package/scripts/create-spec.ts +8 -34
  45. package/scripts/criterion-inventory.ts +649 -0
  46. package/scripts/extract-constraints.ts +108 -9
  47. package/scripts/plan-deps.ts +378 -0
  48. package/scripts/plan-issues.ts +701 -0
  49. package/scripts/plan-spec.ts +371 -0
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- aa2a5af1b31b712c5702035b4740c14f591f59fdcbed342e791976869850bfd2
1
+ b3f611f4544c955941ff527106a0f7260cb49e435e814901388c5d79e5dbf9ad
@@ -75,15 +75,15 @@ if (PROJECT_ROOT) try {
75
75
 
76
76
  // Branch cleanup (#516, #1079). Thin trigger: lib/branch-cleanup.ts holds
77
77
  // every decision. This arm issues `git push origin --delete`, the one
78
- // irreversible thing this hook does and the only thing in it that reaches a
79
- // remote, at EVERY SessionStart from the shared checkout — so it is DISARMED
80
- // by default and signals nothing. Set RUNGATE_BRANCH_CLEANUP=1 to arm it.
78
+ // IRREVERSIBLE thing this hook does, at EVERY SessionStart from the shared
79
+ // checkout — DISARMED by default; set RUNGATE_BRANCH_CLEANUP=1 to arm. The
80
+ // rescue below reaches the remote too and IS armed: a delete destroys a
81
+ // commit's last copy, a push only creates a ref and never --forces.
81
82
  //
82
83
  // A disarmed arm and a run that could not resolve the repository both say so
83
84
  // by name: zero deletions has three causes here and only one is a clean
84
85
  // sweep. `.claude/rungate/hooks.json` names this arming and the #1079 slug
85
- // refusal as the two things that must BOTH hold before this hook may be
86
- // reconsidered for consumer deployment.
86
+ // refusal as the two that must BOTH hold before consumer deployment.
87
87
  if (PROJECT_ROOT) try {
88
88
  const { runBranchCleanupArm } = await import('../lib/branch-cleanup.ts');
89
89
  const br = await runBranchCleanupArm({ projectRoot: PROJECT_ROOT, maxAgeDays: 7 });
@@ -129,11 +129,19 @@ if (PROJECT_ROOT) try {
129
129
  }
130
130
  }
131
131
  } catch (e) { log(`GAP scan error: ${e}`); }
132
+ // Stranded work (#1038): a push CREATES a ref where the branch arm destroys one.
133
+ let rescued = 0;
134
+ if (PROJECT_ROOT) try {
135
+ const { rescueStrandedBranches, rescueReportLines } = await import('../lib/worktree-cleanup.ts');
136
+ const rs = rescueStrandedBranches(PROJECT_ROOT); rescued = rs.pushed.length;
137
+ for (const line of rescueReportLines(rs)) log(line);
138
+ } catch (e) { log(`STRANDED rescue error: ${e}`); }
132
139
 
133
140
  const parts: string[] = [];
134
141
  if (deletedCount > 0) parts.push(`${deletedCount} removed`);
135
142
  if (orphansSignalled > 0) parts.push(`${orphansSignalled} orphaned processes signalled`);
136
143
  if (gapWarns > 0) parts.push(`${gapWarns} gap warnings`);
144
+ if (rescued > 0) parts.push(`${rescued} stranded branch(es) pushed`);
137
145
  if (parts.length > 0) {
138
146
  console.log(`Stale TTL cleanup: ${parts.join(', ')}`);
139
147
  } else {
@@ -31,6 +31,7 @@ import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
31
31
  import { join } from 'path';
32
32
  import { parseHookInput } from './lib/parseStdin';
33
33
  import { verifyPhaseRefusal } from '../lib/issue-create-override';
34
+ import { isRunDirectory } from '../lib/active-workflow';
34
35
  import { filingGate, ledgerPath, recordAdjudication } from '../lib/issue-filing-gate';
35
36
 
36
37
  const WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
@@ -42,6 +43,10 @@ function findActiveWorkflow(): { path: string; data: any } | null {
42
43
  try {
43
44
  for (const entry of readdirSync(WORK_DIR, { withFileTypes: true })) {
44
45
  if (!entry.isDirectory()) continue;
46
+ // `.archive/<slug>/workflow-state.json` matches the nested shape below,
47
+ // so without this an ARCHIVED run decides the lock. One did, for eight
48
+ // days — see lib/active-workflow.ts for the reading.
49
+ if (!isRunDirectory(entry.name)) continue;
45
50
  const wfPath = join(WORK_DIR, entry.name, 'workflow-state.json');
46
51
  if (existsSync(wfPath)) {
47
52
  try {
@@ -56,6 +61,9 @@ function findActiveWorkflow(): { path: string; data: any } | null {
56
61
  try {
57
62
  for (const sub of readdirSync(nested, { withFileTypes: true })) {
58
63
  if (!sub.isDirectory()) continue;
64
+ // Both readings, or the defect survives one level deeper — see
65
+ // lib/active-workflow.ts, which holds the reading and the why.
66
+ if (!isRunDirectory(sub.name)) continue;
59
67
  const nestedWf = join(nested, sub.name, 'workflow-state.json');
60
68
  if (!existsSync(nestedWf)) continue;
61
69
  try {
@@ -9,8 +9,13 @@
9
9
 
10
10
  import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
11
11
  import { join } from 'path';
12
+ import { isRunDirectory } from '../../lib/active-workflow';
12
13
 
13
- const RUNGATE_WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.RUNGATE_WORK_DIR || join(process.env.HOME!, '.rungate');
14
+ // `PAI_WORK_DIR` second, as every sibling resolves it — VerifyPhaseLock,
15
+ // StaleTTLCleanup, AgentVerdictCapture and lib/issue-filing-gate.ts all read
16
+ // the same three in the same order. This file read RUNGATE_WORK_DIR twice,
17
+ // so a consumer still on the legacy variable silently got `~/.rungate`.
18
+ const RUNGATE_WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
14
19
 
15
20
  interface WorkflowState {
16
21
  path: string;
@@ -36,8 +41,18 @@ export function findWorkflowForIssue(issueNum?: string, phases?: string[], repo?
36
41
  };
37
42
 
38
43
  try {
44
+ // Hidden entries are the work dir's own bookkeeping, not runs — and
45
+ // `Priority 3` below is an mtime fallback, so `.archive`'s newest state
46
+ // file outranks every live run. That is #1648. Both levels, for the
47
+ // reason in lib/active-workflow.ts.
48
+ //
49
+ // Blast radius, since an earlier version of this comment got it wrong:
50
+ // `CommitEnforcement.hook.ts` is the ONLY hook importing this module.
51
+ // `IssueCloseGuard` and `AutoVerifyGate` use `findWorkflowState` from
52
+ // `./utils`, a third implementation of this scan that is still
53
+ // unfiltered — #1668. Fixing this file does not reach them.
39
54
  const dirs = readdirSync(RUNGATE_WORK_DIR, { withFileTypes: true })
40
- .filter(d => d.isDirectory());
55
+ .filter(d => d.isDirectory() && isRunDirectory(d.name));
41
56
 
42
57
  for (const d of dirs) {
43
58
  // Level 1: direct children
@@ -46,7 +61,8 @@ export function findWorkflowForIssue(issueNum?: string, phases?: string[], repo?
46
61
  // Level 2: nested subdirectories (e.g., pai/361)
47
62
  const subDir = join(RUNGATE_WORK_DIR, d.name);
48
63
  try {
49
- const subDirs = readdirSync(subDir, { withFileTypes: true }).filter(sd => sd.isDirectory());
64
+ const subDirs = readdirSync(subDir, { withFileTypes: true })
65
+ .filter(sd => sd.isDirectory() && isRunDirectory(sd.name));
50
66
  for (const sd of subDirs) {
51
67
  collectWorkflow(join(subDir, sd.name, 'workflow-state.json'), `${d.name}/${sd.name}`);
52
68
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Which directories under the work dir hold a LIVE run (#1648).
3
+ *
4
+ * `hooks/VerifyPhaseLock.hook.ts` picks the most recently modified
5
+ * `workflow-state.json` under `$RUNGATE_WORK_DIR` and refuses
6
+ * `gh issue create` when its phase is `VERIFY`. It scans each entry and then
7
+ * each entry's subdirectories, which is how a run nested one level deep is
8
+ * found — and it is also how `.archive/<slug>/workflow-state.json` is found,
9
+ * because `.archive` is just another directory to `readdirSync`.
10
+ *
11
+ * **Measured 2026-10-29 on this machine.** The newest state file anywhere
12
+ * under `~/.rungate` was
13
+ * `.archive/pai-harness-892/workflow-state.json`, modified 21 October, phase
14
+ * `VERIFY`. Three live run directories existed and none of them was in
15
+ * VERIFY: `pai-harness-169` DONE, `pai-harness-630` DONE, `pai-harness-65`
16
+ * GOAL. So every `gh issue create` reaching Bash on this machine had been
17
+ * refused for eight days on behalf of a run that finished, and the refusal
18
+ * named a `verifyBlockers[]` array in a file nobody was writing to.
19
+ *
20
+ * That is the worst failure mode a workflow gate has. It does not look like a
21
+ * bug — it looks like the gate working — and the documented way out is to
22
+ * apply an override label, so the pressure it creates is to mislabel issues.
23
+ * `lib/issue-create-override.ts` already records that happening once: #362,
24
+ * #363 and #364 all wear `follow-up` and none of them is follow-up work.
25
+ *
26
+ * ## The rule, and why it is about the dot and not about `.archive`
27
+ *
28
+ * A run directory is named for the slug of the run — `pai-harness-892`,
29
+ * `agentgrit-311`. Nothing names a run with a leading dot, and the work dir's
30
+ * own bookkeeping is what uses them. So the predicate is "not hidden" rather
31
+ * than "not `.archive`": a list of one name has to be extended by whoever adds
32
+ * the second kind of bookkeeping directory, and they will not know to.
33
+ *
34
+ * ## It has to guard BOTH readings
35
+ *
36
+ * The hook reads twice — `<run>/workflow-state.json` and
37
+ * `<run>/<sub>/workflow-state.json` — and the first version of this fix
38
+ * filtered only the outer one. That leaves the same defect one level deeper:
39
+ * a hidden bookkeeping directory INSIDE a live run is still read, and being
40
+ * written last it still outranks the live run by mtime.
41
+ *
42
+ * One filtered reading beside one unfiltered reading of the same question is
43
+ * the fourth shape in `.claude/rules/checks-must-be-able-to-fail.md`. No
44
+ * behavioural case can tell them apart while the outer one is right, so the
45
+ * end-to-end suite plants `<run>/.archive` directly and the mutation that
46
+ * removes the inner guard reddens exactly that case and no other.
47
+ */
48
+
49
+ /**
50
+ * Does this entry under the work directory hold a run that is still going?
51
+ *
52
+ * Hidden entries are the work dir's own bookkeeping, not runs. `.archive` is
53
+ * the one that exists today and the one that caused #1648.
54
+ */
55
+ export function isRunDirectory(name: string): boolean {
56
+ return !name.startsWith(".");
57
+ }
@@ -514,9 +514,25 @@ export interface ReviewFinding {
514
514
  * Case and whitespace only. Not punctuation, and not stemming: two findings
515
515
  * that differ in a word are two findings, and a key that erases the
516
516
  * difference suppresses a real one.
517
+ *
518
+ * **The case fold is ASCII-only on purpose, and `.toLowerCase()` is wrong
519
+ * here.** This is one half of a pair: the generated jq re-derives the same key
520
+ * from a thread body with its own `norm`, which folds case with
521
+ * `ascii_downcase`. jq exposes no Unicode-aware downcase to match — its
522
+ * `builtins` carry `ascii_downcase` and `ascii_upcase` and nothing else — so
523
+ * the agreement can only be bought on this side. `.toLowerCase()` is
524
+ * Unicode-aware, so it folded `É` to `é` where jq left it alone, the two
525
+ * engines keyed one thread two ways, and a thread a human had resolved could
526
+ * never answer its finding. `test/ai-review-carry-forward.test.ts` (AC-C9)
527
+ * drives both engines and holds them to the same verdict.
528
+ *
529
+ * The whitespace half needs no such care: jq's `[[:space:]]+` and JS's `\s+`
530
+ * were measured to agree on NBSP, U+2028 and U+3000.
517
531
  */
518
532
  function normalise(v: unknown): string {
519
- return typeof v === "string" ? v.trim().toLowerCase().replace(/\s+/g, " ") : "";
533
+ return typeof v === "string"
534
+ ? v.trim().replace(/[A-Z]/g, c => c.toLowerCase()).replace(/\s+/g, " ")
535
+ : "";
520
536
  }
521
537
 
522
538
  /**
@@ -691,6 +707,110 @@ export function carryForward(
691
707
  return out;
692
708
  }
693
709
 
710
+ /* ──────────────── the same question, asked of the review threads ──────────
711
+ *
712
+ * `carryForward` above decides "is this finding still live" by comparing the
713
+ * TEXT at its cited line against the text recorded when it was raised. That
714
+ * is a heuristic over a moving document and #1601 is what it costs when it is
715
+ * wrong: a required check reported CLEAN over a live blocker for two rounds,
716
+ * because unrelated edits shifted the file and every finding read as
717
+ * resolved.
718
+ *
719
+ * A review thread answers the same question authoritatively. `isResolved` is
720
+ * a thing a PERSON did, on the finding itself, and no edit elsewhere in the
721
+ * file can forge it. #1618 is what makes the match possible at all: a posted
722
+ * thread now carries, base64 in an HTML comment, the key the finding was
723
+ * raised under.
724
+ *
725
+ * ## The two readings disagree, and the disagreement is the point
726
+ *
727
+ * Text-resolution says "the code moved". Thread-resolution says "a human
728
+ * accepted the answer". Only the second is a decision. The first is the one
729
+ * that re-raised one observation on #1614 twelve times across fifteen rounds,
730
+ * because the line numbers moved under it each round while the finding did
731
+ * not.
732
+ */
733
+
734
+ /** One review thread, reduced to the two facts the decision needs. */
735
+ export interface CarryThread {
736
+ /** The finding key the thread was posted under, per `threadKeyFrom`. */
737
+ key: string;
738
+ isResolved: boolean;
739
+ }
740
+
741
+ /**
742
+ * What was learned about the pull request's review threads.
743
+ *
744
+ * **Evidence is a PARAMETER, never fetched in here.** The decision has to be
745
+ * runnable against a reading that is empty, a reading that is wrong, and a
746
+ * reading that could not be taken — and a function that fetches its own
747
+ * evidence can only ever be tested against whatever the network returned.
748
+ */
749
+ export type ThreadReading =
750
+ | { status: "MEASURED"; threads: readonly CarryThread[] }
751
+ | { status: "UNMEASURED"; reason: string };
752
+
753
+ /**
754
+ * Carry forward every prior finding no review thread shows was ANSWERED.
755
+ *
756
+ * @returns `carried` — the findings still live — and `unmeasured`, the reason
757
+ * the thread list could not be read, or `null` when it was read. The two are
758
+ * reported separately on purpose: an empty `carried` after a failed fetch and
759
+ * an empty `carried` after a clean read are the same list and completely
760
+ * different facts.
761
+ *
762
+ * ## Every undecidable case CARRIES
763
+ *
764
+ * An unreadable thread list, a finding this caller cannot key, and a key no
765
+ * thread holds all carry. Re-raising something already dealt with is loud,
766
+ * cheap and self-correcting. Dropping a live finding is silent and permanent.
767
+ *
768
+ * ## A finding with any OPEN thread is unanswered
769
+ *
770
+ * Not "the first thread found", and not "any resolved thread". One
771
+ * observation produced twelve threads on #1614, so a reader that stops at the
772
+ * first key match answers a live finding by coincidence of the API's
773
+ * ordering. Every thread carrying the key must be resolved before the finding
774
+ * is.
775
+ */
776
+ export function carryForwardFromThreads(
777
+ prior: readonly CarriedFinding[],
778
+ reading: ThreadReading,
779
+ keyFor: (f: ReviewFinding) => string | null,
780
+ ): { carried: ReviewFinding[]; unmeasured: string | null } {
781
+ if (reading.status !== "MEASURED") {
782
+ return { carried: prior.map(e => e.finding), unmeasured: reading.reason };
783
+ }
784
+
785
+ // Fold the threads into one verdict per key BEFORE deciding anything, so
786
+ // the decision cannot depend on where a key's threads sat in the list.
787
+ const allResolved = new Map<string, boolean>();
788
+ for (const t of reading.threads) {
789
+ allResolved.set(t.key, (allResolved.get(t.key) ?? true) && t.isResolved === true);
790
+ }
791
+ // The empty key is refused on the FINDING side only, below, and once. It
792
+ // was refused here too until a battery showed neither guard alone could be
793
+ // made to fail: two deciders answering one question are behaviourally one,
794
+ // and no test can say which of them is live
795
+ // (`.claude/rules/checks-must-be-able-to-fail.md`). The surviving one is
796
+ // the stronger — it also refuses the `null` that `keyFor` returns, which a
797
+ // guard over `t.key` cannot see.
798
+
799
+ // ONE decider, and `!== true` is the whole of it. An unkeyable finding, a
800
+ // key no thread holds, and a key whose threads are not all resolved are
801
+ // three different reasons and one outcome, and they share a line so that a
802
+ // mutation of it moves all three. Spelling them as three branches would be
803
+ // three deciders agreeing — no behavioural test could tell which was live,
804
+ // and two of them would be dead (`.claude/rules/checks-must-be-able-to-fail.md`).
805
+ const carried: ReviewFinding[] = [];
806
+ for (const entry of prior) {
807
+ const key = keyFor(entry.finding);
808
+ const answered = typeof key === "string" && key !== "" && allResolved.get(key) === true;
809
+ if (!answered) carried.push(entry.finding);
810
+ }
811
+ return { carried, unmeasured: null };
812
+ }
813
+
694
814
  /* ───────────────── reading the ledger a previous round wrote ──────────────
695
815
  *
696
816
  * `lib/scaffold/ai-review-step.ts` upserts ONE comment per pull request
@@ -1181,21 +1301,72 @@ export function selectLedgerComment(
1181
1301
  * bare array would discard the history of every pull request mid-flight at
1182
1302
  * the moment the new writer merged.
1183
1303
  */
1184
- export function readLedger(body: unknown): LedgerReading {
1185
- if (typeof body !== "string") return { status: AI_REVIEW_LEDGER_ABSENT };
1186
- const marker = body.indexOf(AI_REVIEW_LEDGER_COMMENT_MARKER);
1187
- if (marker === -1) return { status: AI_REVIEW_LEDGER_ABSENT };
1304
+ export const LEDGER_PAYLOAD_FOUND = "LEDGER_PAYLOAD_FOUND";
1305
+ export const LEDGER_PAYLOAD_NO_MARKER = "LEDGER_PAYLOAD_NO_MARKER";
1306
+ export const LEDGER_PAYLOAD_NO_FENCE = "LEDGER_PAYLOAD_NO_FENCE";
1307
+ export const LEDGER_PAYLOAD_UNCLOSED = "LEDGER_PAYLOAD_UNCLOSED";
1188
1308
 
1309
+ /**
1310
+ * Four arms, not two — one object type per status rather than one carrying a
1311
+ * union of three. TypeScript narrows a discriminated union by eliminating
1312
+ * ARMS, so three `if (status === …) return` checks against a single
1313
+ * three-literal arm eliminate none of it and `payload.text` stays an error.
1314
+ */
1315
+ export type LedgerPayload =
1316
+ | { readonly status: typeof LEDGER_PAYLOAD_FOUND; readonly text: string }
1317
+ | { readonly status: typeof LEDGER_PAYLOAD_NO_MARKER }
1318
+ | { readonly status: typeof LEDGER_PAYLOAD_NO_FENCE }
1319
+ | { readonly status: typeof LEDGER_PAYLOAD_UNCLOSED };
1320
+
1321
+ /**
1322
+ * Where the ledger's JSON payload starts and stops. THE ONLY SITE.
1323
+ *
1324
+ * The fence rule is `indexOf("```json")` from the marker, then
1325
+ * `indexOf("\n```")` from there, and the obvious alternative —
1326
+ * `split("```json")[1].split("```")[0]` — is wrong on live data rather than
1327
+ * in theory: a ledger whose stored finding quotes a fenced code block is cut
1328
+ * at the quote. On 2026-10-27 that cut a 27,252-character ledger at 18,021,
1329
+ * and the text at the cut was a reviewer quoting the recipe that did the
1330
+ * cutting.
1331
+ *
1332
+ * It is one exported function because it was briefly two. #1633 round 6
1333
+ * found `readLedger` and `ledgerRawRounds` each computing these three
1334
+ * offsets, agreeing by convention with nothing enforcing it — the *two
1335
+ * deciders that agree* shape in `.claude/rules/checks-must-be-able-to-fail.md`,
1336
+ * where no behavioural test can tell them apart and a mutation of either
1337
+ * leaves the other holding the case up. They cannot now disagree, because
1338
+ * there is only one of them.
1339
+ *
1340
+ * `scripts/record-ai-review-unmeasured.ts` still cuts its own, because it
1341
+ * needs the whole DOCUMENT rather than the payload — it splices annotated
1342
+ * rounds back in, and the bare-array and `{rounds}` shapes are written back
1343
+ * differently. That one is a declared second decider and it is narrower:
1344
+ * it indexes from the start of the body rather than from the marker.
1345
+ */
1346
+ export function ledgerPayloadText(body: unknown): LedgerPayload {
1347
+ if (typeof body !== "string") return { status: LEDGER_PAYLOAD_NO_MARKER };
1348
+ const marker = body.indexOf(AI_REVIEW_LEDGER_COMMENT_MARKER);
1349
+ if (marker === -1) return { status: LEDGER_PAYLOAD_NO_MARKER };
1189
1350
  const fence = body.indexOf("```json", marker);
1190
- if (fence === -1) {
1351
+ if (fence === -1) return { status: LEDGER_PAYLOAD_NO_FENCE };
1352
+ const start = body.indexOf("\n", fence);
1353
+ const close = start === -1 ? -1 : body.indexOf("\n```", start);
1354
+ if (close === -1) return { status: LEDGER_PAYLOAD_UNCLOSED };
1355
+ return { status: LEDGER_PAYLOAD_FOUND, text: body.slice(start + 1, close) };
1356
+ }
1357
+
1358
+ export function readLedger(body: unknown): LedgerReading {
1359
+ const payload = ledgerPayloadText(body);
1360
+ if (payload.status === LEDGER_PAYLOAD_NO_MARKER) {
1361
+ return { status: AI_REVIEW_LEDGER_ABSENT };
1362
+ }
1363
+ if (payload.status === LEDGER_PAYLOAD_NO_FENCE) {
1191
1364
  return ledgerUnreadable(
1192
1365
  "the ledger comment is present and holds no ```json block, so the rounds it " +
1193
1366
  "recorded cannot be read; it is not being treated as an empty ledger",
1194
1367
  );
1195
1368
  }
1196
- const start = body.indexOf("\n", fence);
1197
- const close = start === -1 ? -1 : body.indexOf("\n```", start);
1198
- if (close === -1) {
1369
+ if (payload.status === LEDGER_PAYLOAD_UNCLOSED) {
1199
1370
  return ledgerUnreadable(
1200
1371
  "the ledger comment's ```json block is not closed, so it was truncated in " +
1201
1372
  "transit or in storage and the rounds it recorded cannot be read",
@@ -1204,7 +1375,7 @@ export function readLedger(body: unknown): LedgerReading {
1204
1375
 
1205
1376
  let parsed: unknown;
1206
1377
  try {
1207
- parsed = JSON.parse(body.slice(start + 1, close));
1378
+ parsed = JSON.parse(payload.text);
1208
1379
  } catch (e) {
1209
1380
  return ledgerUnreadable(
1210
1381
  `the ledger comment's JSON block could not be parsed (${
@@ -1243,6 +1414,48 @@ export function readLedger(body: unknown): LedgerReading {
1243
1414
  };
1244
1415
  }
1245
1416
 
1417
+ /**
1418
+ * The ledger's round entries **as written**, for readers that need a field
1419
+ * `LedgerRound` does not carry.
1420
+ *
1421
+ * `readLedger` is the reading; this is the same bytes with nothing dropped.
1422
+ * The `unmeasured` key is the case that forced it — `lib/ai-review-unmeasured.ts`
1423
+ * adds it in a second pass and `toLedgerRound` has no slot for it, so counting
1424
+ * how many rounds were `declined` rather than `no_payload` means going back to
1425
+ * the entry.
1426
+ *
1427
+ * **It does not compute the fence** — `ledgerPayloadText` does, for this and
1428
+ * for `readLedger` both, so the two cannot disagree about where the payload
1429
+ * is (#1633 round 6).
1430
+ *
1431
+ * `null` means `readLedger` would not have returned READ either — absent,
1432
+ * unfenced, unparseable, or an object with no `rounds` array. A caller wanting
1433
+ * to know WHICH should ask `readLedger`; this answers only "hand me the
1434
+ * entries".
1435
+ *
1436
+ * **IT CANNOT THROW**, and the reason is structural rather than a catch. A
1437
+ * reader of a RANGE calls it once per pull request,
1438
+ * and an exception from one of them would abort the whole reading and lose
1439
+ * the other forty-five — the exact failure the jq recipe this replaces had.
1440
+ * Refusing one entry costs one `UNMEASURED` line.
1441
+ */
1442
+ export function ledgerRawRounds(body: unknown): unknown[] | null {
1443
+ if (readLedger(body).status !== AI_REVIEW_LEDGER_READ) return null;
1444
+ const payload = ledgerPayloadText(body);
1445
+ /* c8 ignore next — narrowing the union; a READ reading implies FOUND. */
1446
+ if (payload.status !== LEDGER_PAYLOAD_FOUND) return null;
1447
+ // No try/catch, deliberately. READ means `readLedger` already parsed THIS
1448
+ // STRING — the same bytes from the same function — so a catch here could
1449
+ // never fire, and a guard against a state nothing can produce is a guard
1450
+ // no test can prove (`.claude/rules/checks-must-be-able-to-fail.md`). What
1451
+ // makes the throw impossible is the single fence site, and that is
1452
+ // asserted rather than defended against.
1453
+ const parsed: unknown = JSON.parse(payload.text);
1454
+ if (Array.isArray(parsed)) return parsed;
1455
+ const rounds = (parsed as Record<string, unknown>)[AI_REVIEW_LEDGER_ROUNDS_KEY];
1456
+ return Array.isArray(rounds) ? rounds : null;
1457
+ }
1458
+
1246
1459
  /**
1247
1460
  * How deep a legacy bare-array ledger is, derived from its length (#1447).
1248
1461
  *