@oscaner-skills/cdd-engine 4.13.0 → 4.14.0

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.
@@ -19,13 +19,15 @@ import path from "node:path";
19
19
  import process from "node:process";
20
20
  import { printParseErrorCode } from "jsonc-parser";
21
21
  import { CompletionCriteria, FixDispositions } from "../contract/completion-criterion.js";
22
+ import { PinAudit } from "../contract/pins.js";
23
+ import { regradeNote } from "../contract/review-criteria.js";
22
24
  import { PlanTaskBlocksReader } from "../contract/task-blocks.js";
23
25
  import { CarrierSeal } from "../infra/carrier-seal.js";
24
26
  import { GitClient } from "../infra/git.js";
25
27
  import { ProcessFacts } from "../infra/proc.js";
26
28
  import { RoundLog } from "../infra/round-log.js";
27
29
  import { BriefRenderer } from "../render/brief.js";
28
- import { TemplateAssembler } from "../render/templates.js";
30
+ import { pinLensOf, TemplateAssembler } from "../render/templates.js";
29
31
  import { ABSENT_READ, ArtifactReads } from "../session/artifact-reads.js";
30
32
  import { CarrierIntegrity, CarrierMismatchError } from "../session/carrier-integrity.js";
31
33
  import { TargetFaceTable } from "../session/faces.js";
@@ -126,6 +128,9 @@ export class CliLifecycle {
126
128
  * when the channel opened — the record face must see a channel that never opened,
127
129
  * not only the stderr notice. */
128
130
  #logUnavailable = null;
131
+ /** The pin gate of this dispatch (P37 §7.2) — built on first use so the resolution
132
+ * index is walked once per process, never once per read. */
133
+ #pinIndex = null;
129
134
  constructor(opts) {
130
135
  this.#env = opts.env ?? process.env;
131
136
  this.#scene = opts.scene;
@@ -835,31 +840,36 @@ export class CliLifecycle {
835
840
  // front-matter link target, the plan→spec conformance anchor); the branch line
836
841
  // carries the plan document (its plan-conformance reference) plus the same
837
842
  // design-spec reference, while the live tree against BASE_BRANCH is the judged
838
- // object; the spec-shaped doc targets (phase-spec · single-spec) carry their
839
- // spec document (INPUT_SPEC, the judged doc); the overall line's ONE charter
840
- // anchor is INPUT_OVERALL, so its INPUT_SPEC stays empty (C2 — the charter is
841
- // never its own spec). Empty off the off-faces (the slots are dropped by the
842
- // assembler).
843
+ // object; the wave line carries the same-slug identity document and its
844
+ // `program:` charter (P37 §4.1) so a code review reads the phase contract it is
845
+ // judged against; the spec-shaped doc targets (phase-spec · single-spec) carry
846
+ // their spec document (INPUT_SPEC, the judged doc); the overall line's ONE
847
+ // charter anchor is INPUT_OVERALL, so its INPUT_SPEC stays empty (C2 — the
848
+ // charter is never its own spec). Empty off the off-faces (the slots are dropped
849
+ // by the assembler).
843
850
  INPUT_PLAN: frame.type === "plan"
844
851
  ? this.#rel(docPath ?? "")
845
852
  : frame.type === "branch"
846
853
  ? this.#rel(scene.planPath ?? "")
847
854
  : "",
848
- INPUT_SPEC: frame.type === "plan" || frame.type === "branch"
855
+ INPUT_SPEC: frame.type === "plan" || frame.type === "branch" || frame.type === "wave"
849
856
  ? this.#rel(scene.specLink ?? "")
850
- : frame.type === "wave" || frame.type === "overall"
857
+ : frame.type === "overall"
851
858
  ? ""
852
859
  : // the spec-shaped doc targets (phase-spec · single-spec) carry the judged
853
860
  // document; the overall line's charter anchor is INPUT_OVERALL below.
854
861
  this.#rel(docPath ?? ""),
855
862
  // The parent charter of the spec the face reads (INPUT_OVERALL) — the overall
856
863
  // line's ONE charter anchor (the judged charter itself); the phase-spec line
857
- // carries its own `program:`; plan/branch carry the same-slug identity doc's
858
- // `program:`; empty off those faces and when the named program is absent (the
859
- // assembler drops the empty slot).
864
+ // carries its own `program:`; plan / branch / wave carry the same-slug identity
865
+ // doc's `program:` (the wave arm landed at P37 §4.1); empty off those faces and
866
+ // when the named program is absent (the assembler drops the empty slot).
860
867
  INPUT_OVERALL: frame.type === "overall"
861
868
  ? this.#rel(docPath ?? "")
862
- : frame.type === "phase-spec" || frame.type === "plan" || frame.type === "branch"
869
+ : frame.type === "phase-spec" ||
870
+ frame.type === "plan" ||
871
+ frame.type === "branch" ||
872
+ frame.type === "wave"
863
873
  ? this.#rel(scene.overallLink ?? "")
864
874
  : "",
865
875
  // The branch/wave tree-review scope anchor (BASE_BRANCH) — engine-injected
@@ -1071,6 +1081,13 @@ export class CliLifecycle {
1071
1081
  if (readBack.problems.length > 0) {
1072
1082
  return this.#reject(frame, path, `the handoff draft at ${path} violates the ${plane} schema: ${readBack.problems.join("; ")}`);
1073
1083
  }
1084
+ // P37 §7.2 — the pin read-back corpora ② and ③ are judged HERE, before the local
1085
+ // findings projection and before `conclusionOf`, so that ONE `rollup` reads them,
1086
+ // `DraftedOutcome.findings` projects them and `#materialize` persists them. The
1087
+ // judgment lives here and the write there: a warn injected at the writer would
1088
+ // reach the carrier while the round still concluded `APPROVED`.
1089
+ if (plane === "judge")
1090
+ this.#injectPinFindings(frame, draft);
1074
1091
  // T2 — the plane-aware read: the judge plane ALONE reads `draft.findings` (its
1075
1092
  // own declared required field — rolled up to the conclusion); the work plane
1076
1093
  // derives its status from the draft's declared status, never the findings slot
@@ -1078,6 +1095,16 @@ export class CliLifecycle {
1078
1095
  // The conclusion rides the ONE source (`HandoffSchema.conclusionOf`) the ledger
1079
1096
  // legs read too — the reconstruct never rules a work status by a second path.
1080
1097
  const findings = plane === "judge" ? (Array.isArray(draft.findings) ? draft.findings : []) : [];
1098
+ // P37 §2.2 — the blocker evidence gate: a blocker that cannot state its scenario is
1099
+ // refused on THIS read-back path (the same one `CDD_BLOCKED` line every schema
1100
+ // refusal rides — no second reporter, no `--dry-run` claim). The round produces no
1101
+ // conclusion instead of a BLOCKED one.
1102
+ // Rule zero (class-size limit): this file is well past the limit and predates it —
1103
+ // splitting it is P39's work (design spec D95 ②), not this round's.
1104
+ const grading = schema.gradingViolations(findings);
1105
+ if (grading.length > 0) {
1106
+ return this.#reject(frame, path, this.#gradingRefusal(grading));
1107
+ }
1081
1108
  // A validated draft's conclusion is total: the judge plane rolls up its own
1082
1109
  // required findings, and the work plane's `status` passed the `required` gate above
1083
1110
  // — so the `?? "BLOCKED"` never fires here (a work draft without a status never
@@ -1091,6 +1118,11 @@ export class CliLifecycle {
1091
1118
  let summary;
1092
1119
  try {
1093
1120
  summary = this.#dispositionsSummary(frame, plane, materialized.carrier);
1121
+ // P37 §5.2 — the downgrade note rides the SAME capsule `summary` slot: the
1122
+ // `emit` signature and key set do not move, and a round with no downgrade leaves
1123
+ // the slot undefined, so the stdout of an ordinary review round is byte-identical
1124
+ // to before this phase.
1125
+ summary ??= this.#downgradeNote(frame, plane, materialized.carrier);
1094
1126
  }
1095
1127
  catch (raw) {
1096
1128
  if (!(raw instanceof CarrierMismatchError))
@@ -1108,6 +1140,98 @@ export class CliLifecycle {
1108
1140
  violations: materialized.violations,
1109
1141
  };
1110
1142
  }
1143
+ /** P37 §7.2 — the two read-back corpora of the pin gate, injected as REAL warn-level
1144
+ * findings into `draft.findings`. The row's LENS is the judged face's own declared
1145
+ * `pinLens` (`render/templates.ts#pinLensOf`), never a literal here: the child's
1146
+ * prompt declares a lens menu per face, and an engine row outside that menu would
1147
+ * be unreadable as "the engine wrote it" to every later reader. They are not a
1148
+ * refusal: no `CDD_BLOCKED` is printed, and the round keeps its conclusions — a warn
1149
+ * reaches `rollup`, so a review round with a dead pin concludes `REVIEW_FIX` instead
1150
+ * of `APPROVED`. Nothing here is a second reporting surface: the rows enter the same
1151
+ * `findings[]`, are projected by the same `findingsOf`, and are keyed by the same
1152
+ * `#findingsList` at materialize. */
1153
+ #injectPinFindings(frame, draft) {
1154
+ const lens = pinLensOf(frame.type);
1155
+ const injected = [
1156
+ ...this.#documentPinRows(frame, lens),
1157
+ ...this.#contractPinRows(draft, lens, _a.#judgedDocOf(frame)),
1158
+ ];
1159
+ if (injected.length === 0)
1160
+ return;
1161
+ const rows = Array.isArray(draft.findings) ? draft.findings : [];
1162
+ draft.findings = [...rows, ...injected];
1163
+ }
1164
+ /** The document this round judges (§7.3 condition ①'s subject) — a repo-relative
1165
+ * path for the two doc-target kinds, `null` for a wave / branch round: those audit
1166
+ * no document body, so a `Create:` declaration has no identity key to match and its
1167
+ * pending path stays a finding (design spec §7.2's `standards` arm). */
1168
+ static #judgedDocOf(frame) {
1169
+ const target = frame.target;
1170
+ return target.kind === "spec" || target.kind === "plan" ? target.doc : null;
1171
+ }
1172
+ /** Corpus ② — the JUDGED document's own body (the three doc targets only; a wave /
1173
+ * branch / plan round judges no document body). The path comes from `frame.target`
1174
+ * (`{ kind: "spec", doc }`, resolved at the CLI seam), and the body is read through
1175
+ * this class's own repo read: `#reconstruct` builds no second `SlugIndex` and adds no
1176
+ * field to `DispatchScene`. */
1177
+ #documentPinRows(frame, lens) {
1178
+ if (frame.target.kind !== "spec")
1179
+ return [];
1180
+ const doc = frame.target.doc;
1181
+ let body;
1182
+ try {
1183
+ body = readFileSync(path.resolve(this.#repoRootValue().absolute, doc), "utf8");
1184
+ }
1185
+ catch {
1186
+ return [];
1187
+ }
1188
+ return this.#pinAudit()
1189
+ .scanText(body, this.#rel(doc))
1190
+ .map((finding) => _a.#pinRow(finding.summary, lens));
1191
+ }
1192
+ /** Corpus ③ — each finding's `contract.path` (design spec §2.3). `PinAudit`'s
1193
+ * markdown scan never carries this cell: the anchor is a declared coordinate, judged
1194
+ * on its own. A missing path appends one warn per offending finding. The judged
1195
+ * document rides in as the time face's subject (§7.3): a `Create:` declaration of
1196
+ * the judged document's own plan is pending, not dead. */
1197
+ #contractPinRows(draft, lens, judged) {
1198
+ const rows = Array.isArray(draft.findings) ? draft.findings : [];
1199
+ const audit = this.#pinAudit();
1200
+ const rel = judged === null ? null : this.#rel(judged);
1201
+ const out = [];
1202
+ for (const row of rows) {
1203
+ const pin = row?.contract?.path;
1204
+ if (typeof pin !== "string" || pin.trim().length === 0)
1205
+ continue;
1206
+ if (audit.pathResolves(pin.trim(), rel))
1207
+ continue;
1208
+ out.push(_a.#pinRow(`the pin \`${pin.trim()}\` resolves nowhere — the finding's \`contract.path\` anchor names no path in the tree`, lens));
1209
+ }
1210
+ return out;
1211
+ }
1212
+ /** One injected pin finding — a warn under the judged face's own declared pin lens,
1213
+ * the tier §7.2 pins and the lens its menu can carry. */
1214
+ static #pinRow(summary, lens) {
1215
+ return { severity: "warn", lens, summary };
1216
+ }
1217
+ /** The one audit instance of this dispatch — the resolution index is built once and
1218
+ * shared by both corpora (and by every round this instance drives). */
1219
+ #pinAudit() {
1220
+ this.#pinIndex ??= new PinAudit(this.#repoRootValue().absolute);
1221
+ return this.#pinIndex;
1222
+ }
1223
+ /** The blocker-evidence refusal (design spec §2.2): the first word after
1224
+ * `CDD_BLOCKED:` is the criteria row's `id` — written as a LITERAL here, because the
1225
+ * gate's pin is the printed byte, not an import of the registry — followed by every
1226
+ * offending finding's `id` and `summary` (all of them, never one of two). */
1227
+ #gradingRefusal(violations) {
1228
+ const labels = violations.map((violation) => {
1229
+ const summary = violation.summary?.trim() ?? "";
1230
+ const quoted = summary.length === 0 ? "" : ` "${summary}"`;
1231
+ return `${violation.id ?? "unkeyed"}${quoted}`;
1232
+ });
1233
+ return `grading-impact-missing: finding(s) graded blocker carry no \`impact.scenario\` — ${labels.join("; ")}`;
1234
+ }
1111
1235
  /** The fix round's ONE summary line (design spec §3.4) — computed from the PERSISTED
1112
1236
  * carrier's dispositions and the REQUESTING carrier's input set (the same pair the
1113
1237
  * fix criterion judges), never stored: no record field, no carrier key, no capsule
@@ -1124,6 +1248,54 @@ export class CliLifecycle {
1124
1248
  const counts = new FixDispositions().summaryOf(carrier, requester.findings);
1125
1249
  return FIX_DISPOSITIONS_SUMMARY.replace("{fixed}", String(counts.fixed)).replace("{rejected}", String(counts.rejected));
1126
1250
  }
1251
+ /** P37 §5.1 · §5.2 — the capsule's downgrade note. The current round's findings are
1252
+ * judged against the NEAREST EARLIER review record on this line whose findings
1253
+ * projection is non-empty (a clean implement / fix record between the two never
1254
+ * resets the reference); a lowered grade against a non-empty earlier scenario prints
1255
+ * the stated `regrade` reason, and one that states none prints the mark. Display
1256
+ * only: the note is the capsule's `summary` line, never a finding row, never a carrier
1257
+ * entry, and it never moves the round's conclusion. */
1258
+ #downgradeNote(frame, plane, carrier) {
1259
+ if (plane !== "judge")
1260
+ return undefined;
1261
+ const current = this.#handoffSchema.findingsOf(carrier.findings);
1262
+ if (current.length === 0)
1263
+ return undefined;
1264
+ const prior = this.#priorFindings(frame);
1265
+ return regradeNote(HandoffSchema.downgrades(prior, current).length, HandoffSchema.regradeReasons(prior, current));
1266
+ }
1267
+ /** The "previous round" of §5.1 — the nearest earlier REVIEW record on this line
1268
+ * whose findings projection is non-empty. `id` is never the match key (it is the
1269
+ * engine-written row number), so the reference is a whole findings set, not a row
1270
+ * picked by position. The read is the ledger's ONE checked carrier read. */
1271
+ #priorFindings(frame) {
1272
+ const current = { cycle: frame.round, attempt: frame.attempt ?? 1 };
1273
+ const earlier = this.#scene.ledger
1274
+ .recordsOf(frame.key)
1275
+ .filter((record) => record.op === "review")
1276
+ .filter((record) => _a.#before(record, current))
1277
+ .sort((left, right) => left.cycle === right.cycle ? right.attempt - left.attempt : right.cycle - left.cycle);
1278
+ for (const record of earlier) {
1279
+ const previous = this.#scene.ledger.readHandoff("review", frame.type, {
1280
+ tasks: frame.params.tasks,
1281
+ round: record.cycle,
1282
+ attempt: record.attempt,
1283
+ });
1284
+ if (previous === null)
1285
+ continue;
1286
+ const findings = this.#handoffSchema.findingsOf(previous.findings);
1287
+ if (findings.length > 0)
1288
+ return findings;
1289
+ }
1290
+ return [];
1291
+ }
1292
+ /** Whether `record` precedes the current round — the `(cycle, attempt)` order the
1293
+ * round identity itself uses. */
1294
+ static #before(record, current) {
1295
+ return record.cycle === current.cycle
1296
+ ? record.attempt < current.attempt
1297
+ : record.cycle < current.cycle;
1298
+ }
1127
1299
  /** The requesting review carrier's path — the fix round's `--reviews` input, or the
1128
1300
  * same-cycle review record's carrier identity through the ledger's ONE accessor
1129
1301
  * (the recorded path, then the read ladder a pre-P31 row needs), or the ledger's
@@ -48,6 +48,7 @@
48
48
  //
49
49
  // Module-level exports are types / the declared constant data / the class — zero
50
50
  // behavior-carrying bare functions (the plan's zero-bare-function discipline).
51
+ import { CRITERIA, LENS_QUESTIONS } from "../contract/review-criteria.js";
51
52
  import { DISPATCH } from "../face/host.js";
52
53
  import { TerminationPolicy } from "../face/termination.js";
53
54
  /** The nominal fixed-frame cells shared by every shell (byte-identical words — the
@@ -129,7 +130,7 @@ const FIX_SHELL = [
129
130
  ...FRAME_ITEMS,
130
131
  WORK_CAPABILITY,
131
132
  ...FIX_TYPED_INSTRUCTIONS,
132
- "**fix:** read `INPUT_REVIEWS` (open findings) + the plan context (`INPUT_WAVE_BRIEF` on a wave line — the complete plan mirror; `INPUT_PLAN` on the branch line — the plan document; `INPUT_SPEC` on the branch line — the design spec, a conformance reference, never the judged document). Fix ALL findings (blocker/warn/nit), verifying against `INPUT_REVIEWS` none remain open. Fix + write the draft at `OUTPUT_HANDOFF` per `## Handoff schema` in one process; draft write failure → `status: BLOCKED`; retry = full re-run (idempotent).",
133
+ "**fix:** read `INPUT_REVIEWS` (open findings) + the plan context (`INPUT_WAVE_BRIEF` on a wave line — the complete plan mirror; `INPUT_PLAN` on the branch line — the plan document; `INPUT_SPEC` on the wave and branch lines — the design spec, a conformance reference, never the judged document; `INPUT_OVERALL` on those two lines — that spec's parent charter, a conformance reference too). Fix ALL findings (blocker/warn/nit), verifying against `INPUT_REVIEWS` none remain open. Fix + write the draft at `OUTPUT_HANDOFF` per `## Handoff schema` in one process; draft write failure → `status: BLOCKED`; retry = full re-run (idempotent).",
133
134
  '**Dispositions:** every requested finding needs a disposition keyed by its `id` exactly as the requesting carrier prints it (`F1`, `F2`, … — the summary is description only), valued `{ "status": "fixed" | "rejected", "reason"?: "…" }` — a missing or mis-keyed disposition fails the round.',
134
135
  RULINGS_READING,
135
136
  EVIDENCE_ITEM,
@@ -264,11 +265,21 @@ export const SEVERITY_RUBRIC_SLOTS = {
264
265
  artifact: "{artifact}",
265
266
  audience: "{audience}",
266
267
  };
268
+ /** The rubric's opening calibration line — a stance, not criteria prose: the tier
269
+ * boundaries themselves come from the criteria registry below. */
270
+ const RUBRIC_PREAMBLE = "Calibrate findings by real severity — not everything is a blocker.";
271
+ /** The calibration tail — the same-grade consistency duty, the vision
272
+ * (silence-is-not-permission) sentence with its two slots, the set-aside ledger and
273
+ * the closing acknowledgement. It shares the fragment with every review axes guide,
274
+ * and it is NOT a second copy of the tier criteria: those are rows in
275
+ * `contract/review-criteria.ts`. */
276
+ const CALIBRATION_TAIL = "Within one run, a defect already graded in the same class keeps that grade; crossing grades names its reason in the finding. The reviewed {artifact} is a vision, not an exhaustive enumeration — behavior it is silent on is judged by what a reasonable {audience} would expect; its silence is not permission, and a finding's severity grades that expectation, not whether the text mentions the trigger. Before your verdict, list every behavior you considered and set aside as outside the reviewed scope — one line each with the reason; nothing set aside is dropped silently; an empty list means you set nothing aside. Acknowledge what was done well before listing findings (accurate praise earns the rest of the report trust).";
267
277
  /** The severity rubric — the ONE calibration fragment every review axes guide
268
- * shares: the four blocker questions, the warn/nit tiers, the same-grade
269
- * consistency duty, the vision (silence-is-not-permission) sentence with its two
270
- * slots, the set-aside ledger and the closing acknowledgement. */
271
- export const SEVERITY_RUBRIC = "Calibrate findings by real severity — not everything is a blocker. A finding is a blocker when any one of these holds: (a) the declared acceptance gate, contract or prompt is violated; (b) a legal input escapes the declared failure face (a blank input returns 500, an unknown id is not a 404); (c) the gate fails or the suite can never go red (an inert grep · a dead guard · an unconditional skip); (d) a security or privacy defect. Debt inside the contract is a warn (duplicated policy · stale docstring · a missing coverage case). Style, naming and line-wrapping is a nit. Within one run, a defect already graded in the same class keeps that grade; crossing grades names its reason in the finding. The reviewed {artifact} is a vision, not an exhaustive enumeration — behavior it is silent on is judged by what a reasonable {audience} would expect; its silence is not permission, and a finding's severity grades that expectation, not whether the text mentions the trigger. Before your verdict, list every behavior you considered and set aside as outside the reviewed scope — one line each with the reason; nothing set aside is dropped silently; an empty list means you set nothing aside. Acknowledge what was done well before listing findings (accurate praise earns the rest of the report trust).";
278
+ * shares. Its tier body is ASSEMBLED from the criteria registry (every row's
279
+ * `body` → `duty` → `counterExample`, tiers in blocker → warn → nit order), so the
280
+ * registry is the only corpus of tier prose; the calibration tail rides here, and
281
+ * `reviewGuideOf` fills the two slots. */
282
+ export const SEVERITY_RUBRIC = `${RUBRIC_PREAMBLE} ${CRITERIA.renderRubric()} ${CALIBRATION_TAIL}`;
272
283
  /** The slot values per criteria body — the ONE registry the filled fragment reads.
273
284
  * `{artifact}` = the reviewed product's name; `{audience}` = the subject whose
274
285
  * expectation judges the artifact's silence. The two spec-shaped targets share the
@@ -289,6 +300,13 @@ export const reviewGuideOf = (key) => {
289
300
  const text = REVIEW_BODY_TEXT[key];
290
301
  return SEVERITY_RUBRIC.replaceAll(SEVERITY_RUBRIC_SLOTS.artifact, text.artifact).replaceAll(SEVERITY_RUBRIC_SLOTS.audience, text.audience);
291
302
  };
303
+ /** One review kind's numbered lens question list (design spec §3.2 · §6.1) — the
304
+ * `LENS_QUESTIONS.forReviewKind` projection rendered as `1. …` lines, appended to
305
+ * that kind's axes guide so the questions ride the `**Criteria —` bytes. The list is
306
+ * the table's projection, never a second copy: deleting a row shortens this list. */
307
+ const lensQuestionBlock = (kind) => LENS_QUESTIONS.forReviewKind(kind)
308
+ .map((row, index) => `${index + 1}. ${row.question}`)
309
+ .join("\n");
292
310
  /** The closed-wave discipline's ONE sentence (P30 §2.7) — the document review axes'
293
311
  * shared body: a finding on an already-closed task block's content face is answered
294
312
  * by the document, never by moving the work. Both document criteria bodies select
@@ -318,24 +336,45 @@ const docCharterAxes = (guide) => `Follow URC: single-cycle, lens-tagged finding
318
336
  * copy. */
319
337
  export const REVIEWS = {
320
338
  wave: {
321
- lensEnum: ["standards", "spec", "buildability"],
322
- axesGuide: `Standards axis (repo coding standards + code-review smell baseline) + Spec axis (wave brief / plan requirements) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): run \`git diff origin/<BASE_BRANCH>..HEAD\` yourself (BASE_BRANCH as named in the round context; on a missing artifact judge the working tree) — every changed file must fall within the wave brief's file surface (\`**Files:**\` seams) or be attributable to the plan / reviewed intent; an unattributable changed file is a candidate finding (severity by your judgment). The reviewer is the changed-surface judge — the engine reconciles nothing. ${reviewGuideOf("wave")}`,
339
+ lensEnum: ["standards", "spec", "buildability", "scope"],
340
+ pinLens: "standards",
341
+ axesGuide: `Standards axis (repo coding standards + code-review smell baseline) + Spec axis (wave brief / plan requirements) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): run \`git diff origin/<BASE_BRANCH>..HEAD\` yourself (BASE_BRANCH as named in the round context; on a missing artifact judge the working tree) — every changed file must fall within the wave brief's file surface (\`**Files:**\` seams) or be attributable to the plan / reviewed intent; an unattributable changed file is a candidate finding. The reviewer is the changed-surface judge — the engine reconciles nothing. ${reviewGuideOf("wave")}
342
+
343
+ ${lensQuestionBlock("wave")}`,
323
344
  },
324
345
  branch: {
325
- lensEnum: ["standards", "spec", "buildability"],
326
- axesGuide: `Same four axes as the wave review (branch-wide health: run \`git diff origin/<BASE_BRANCH>..HEAD\` + plan conformance) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): branch review IS the full diff — every changed file must be attributable to a finding, a plan requirement, or the reviewed intent; unrelated surface = candidate finding (severity by your judgment), normal finding → fix loop. ${reviewGuideOf("branch")} Three things a green run cannot show you: design — does the changed structure fit this codebase and is it the simplest structure that solves the plan's problem (over-engineering is a finding, not a preference); test adequacy — would these tests fail if the code broke (a run that cannot go red is not evidence); migration — does every breaking change name the path a not-yet-migrated consumer takes.`,
346
+ lensEnum: ["standards", "spec", "buildability", "scope"],
347
+ pinLens: "standards",
348
+ axesGuide: `Same four axes as the wave review (branch-wide health: run \`git diff origin/<BASE_BRANCH>..HEAD\` + plan conformance) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): branch review IS the full diff — every changed file must be attributable to a finding, a plan requirement, or the reviewed intent; unrelated surface = candidate finding, normal finding → fix loop. ${reviewGuideOf("branch")} Three things a green run cannot show you: design — does the changed structure fit this codebase and is it the simplest structure that solves the plan's problem (over-engineering is a finding, not a preference); test adequacy — would these tests fail if the code broke (a run that cannot go red is not evidence); migration — does every breaking change name the path a not-yet-migrated consumer takes.
349
+
350
+ ${lensQuestionBlock("branch")}`,
327
351
  },
328
352
  spec: {
329
353
  lensEnum: ["completeness", "consistency", "clarity"],
330
- axesGuide: docNarrativeAxes(reviewGuideOf("spec")),
354
+ // §7.2's own word for this corpus: two statements of one fact — the document's
355
+ // claim and the tree — disagree.
356
+ pinLens: "consistency",
357
+ axesGuide: `${docNarrativeAxes(reviewGuideOf("spec"))}
358
+
359
+ ${lensQuestionBlock("spec")}`,
331
360
  },
332
361
  overall: {
333
362
  lensEnum: ["scope", "inventory", "dependency", "acceptance", "boundary"],
334
- axesGuide: docCharterAxes(reviewGuideOf("overall")),
363
+ // The charter's criterion 6 is this row's home: the inventory and the tree
364
+ // disagree, so a pin that resolves nowhere reads as a ledger drift.
365
+ pinLens: "inventory",
366
+ axesGuide: `${docCharterAxes(reviewGuideOf("overall"))}
367
+
368
+ ${lensQuestionBlock("overall")}`,
335
369
  },
336
370
  plan: {
337
371
  lensEnum: ["completeness", "decomposition", "buildability"],
338
- axesGuide: `Follow URC: single-cycle, lens-tagged findings (completeness/decomposition/buildability) + spec conformance — the plan is judged against its design spec at \`INPUT_SPEC\` (the plan's \`spec\` front-matter target): every spec requirement must map to a task, and a spec requirement with no owning task is a completeness finding + the writing-plans self-check + verification evidence — the reviewer runs the repository's typecheck and test commands and self-reports the dual evidence + Claimed→pin: every behavior claim (usage-line attribution · semantic contract · byte face) must cite a colocated pin (path:line + the assertion face) — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding. ${CLOSED_WAVE_DISCIPLINE} ${reviewGuideOf("plan")}`,
372
+ // A step naming a coordinate the tree does not have is a step that cannot be
373
+ // executed against the tree as it stands.
374
+ pinLens: "buildability",
375
+ axesGuide: `Follow URC: single-cycle, lens-tagged findings (completeness/decomposition/buildability) + spec conformance — the plan is judged against its design spec at \`INPUT_SPEC\` (the plan's \`spec\` front-matter target): every spec requirement must map to a task, and a spec requirement with no owning task is a completeness finding + the writing-plans self-check + verification evidence — the reviewer runs the repository's typecheck and test commands and self-reports the dual evidence + Claimed→pin: every behavior claim (usage-line attribution · semantic contract · byte face) must cite a colocated pin (path:line + the assertion face) — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding. ${CLOSED_WAVE_DISCIPLINE} ${reviewGuideOf("plan")}
376
+
377
+ ${lensQuestionBlock("plan")}`,
339
378
  },
340
379
  };
341
380
  /** The criteria-body selection — the ONE target → criteria map. Four targets select
@@ -343,6 +382,22 @@ export const REVIEWS = {
343
382
  * narrative body (`spec`). Keeping the mapping here (never in the row literals)
344
383
  * means a target cannot silently drift onto another target's criteria. */
345
384
  export const reviewBodyOf = (type) => type === "phase-spec" || type === "single-spec" ? "spec" : type;
385
+ /** The lens an engine-authored pin row carries on one target's face (design spec
386
+ * §7.2) — the ONE derivation the read-back's injection point reads. The value is
387
+ * the face's declared `pinLens`, and it is cross-checked against that face's own
388
+ * `lensEnum` here: the menu and the injected row are written for different readers
389
+ * (the child's prompt vs the carrier), so a drifted pair must throw at its first
390
+ * dispatch instead of reaching a carrier as a label the same round's prompt calls
391
+ * impossible. `guides` is the declared table, injectable so the gate itself is
392
+ * pinnable. */
393
+ export const pinLensOf = (type, guides = REVIEWS) => {
394
+ const key = reviewBodyOf(type);
395
+ const row = guides[key];
396
+ if (!row.lensEnum.includes(row.pinLens)) {
397
+ throw new Error(`the pin lens "${row.pinLens}" is not declared by the ${key} lens menu (${row.lensEnum.join(" | ")})`);
398
+ }
399
+ return row.pinLens;
400
+ };
346
401
  /** One review variant row (§3.7) — the fixed prefix folds the SELECTED criteria
347
402
  * body + its lens INLINE (the `INPUT_CRITERIA`/`INPUT_LENS` round-context tokens
348
403
  * are gone) and shares the REVIEW_CONTEXT dynamic tail. The target word labels the
@@ -436,7 +491,11 @@ export const CLAUSES = {
436
491
  "cl:no-secret-access": "Never read, print, or derive a user secret — no keychain access (`security find-generic-password` / `security dump-keychain` / `login.keychain-db`), no `~/.ssh/*`, `~/.aws/credentials`, `~/.netrc`, no host CLI credential store, and no token-bearing environment variable (`*_TOKEN` / `*_API_KEY` / `*_SECRET`). A missing or failing credential is never yours to obtain: report it as `status: BLOCKED` on a work round or as a finding on a review round, then continue with the rest. A secret that reaches a report, evidence file, handoff draft, commit, or issue body has leaked — if one is already visible in your inputs, redact it as `[REDACTED]` and never echo its value.",
437
492
  "cl:sync-completion": "This dispatch is one-shot and non-interactive: end your turn with anything still running and the process exits — the work and the handoff die with it. So do not end your turn — a background command, a background subagent, or any yield-and-wait path such as `bg_run` / `bg_delegate` — before the handoff draft is written. Finish nested work in this same turn: complete it synchronously in this process turn, then write the handoff and finish.",
438
493
  };
439
- /** The dispatch-prompt data plane — the typed template-contract surface. $version 23
494
+ /** The dispatch-prompt data plane — the typed template-contract surface. $version 24
495
+ * names the wave line in the fix shell's anchor clause (P37 §4.1): the wave line now
496
+ * carries the same `INPUT_SPEC` conformance reference and the `INPUT_OVERALL` parent
497
+ * charter as the branch line, so the clause a maintainer reads can no longer
498
+ * attribute those anchors to the branch line alone. $version 23
440
499
  * calibrates the shared body's five faces (§2.6 G · H · I · J · K): the freeze
441
500
  * clause limits itself to the round's declared `capability: may.amend` scope and
442
501
  * the commit clause names the read-only round's absent commit; the capability
@@ -499,7 +558,7 @@ export const CLAUSES = {
499
558
  * prose return contract (`RETURN_PROSE` — nothing downstream parses the child's
500
559
  * stdout), and the per-type review criterion shells. */
501
560
  export const TEMPLATE_PROMPT = {
502
- $version: 23,
561
+ $version: 24,
503
562
  modes: MODE_PROMPTS,
504
563
  reviews: REVIEW_VARIANTS,
505
564
  return: RETURN_ZONE,
@@ -48,6 +48,25 @@ const FINDING = {
48
48
  line: { type: "integer" },
49
49
  summary: { type: "string" },
50
50
  fix: { type: "string" },
51
+ // P37 §2.1 — the blocker evidence slot. Declared OPTIONAL on the schema face by
52
+ // design: warn / nit findings owe no scenario, so a required `impact` would BLOCK
53
+ // legal drafts. A blocker's obligation is judged by `gradingViolations` (the
54
+ // grading gate), never by the shape walk — the shape only pins what a scenario IS.
55
+ impact: {
56
+ type: "object",
57
+ required: ["scenario"],
58
+ properties: { scenario: { type: "string" }, test: { type: "string" } },
59
+ },
60
+ // P37 §5 — the cross-round downgrade reason. Optional at the schema layer: only
61
+ // the cross-round identity + scenario identity judgment requests it.
62
+ regrade: { type: "string" },
63
+ // P37 §2.3 — the repair anchor a fix round locates the finding by. Never read by
64
+ // `rollup`; its `path` is a pin judged on the handoff read-back corpus.
65
+ contract: {
66
+ type: "object",
67
+ required: ["path", "anchor"],
68
+ properties: { path: { type: "string" }, anchor: { type: "string" } },
69
+ },
51
70
  },
52
71
  };
53
72
  /** The ONE carrier declaration — the five child-writable slots. DECLARATION ORDER IS
@@ -204,29 +223,142 @@ export class HandoffSchema {
204
223
  }
205
224
  /** The review conclusion rollup — status derived from the findings severities
206
225
  * (the rollup the retired JSON-return channel performed; a review never carries
207
- * a child-authored status). */
226
+ * a child-authored status). Unchanged by the grading gate: `rollup` counts
227
+ * blockers and nothing else, so the refusal is never a fourth conclusion. */
208
228
  rollup(findings) {
209
229
  const blockers = findings.filter((finding) => finding?.severity === "blocker").length;
210
230
  return blockers > 0 ? "CHANGES_REQUESTED" : findings.length > 0 ? "REVIEW_FIX" : "APPROVED";
211
231
  }
232
+ /** P37 §2.2 — the blocker evidence gate, a PURE predicate colocated with `rollup`.
233
+ * A finding graded `blocker` owes a non-blank `impact.scenario`; every blocker that
234
+ * lacks one is returned so the failure face can list them all (never one of two).
235
+ * Warn / nit findings owe nothing here, and the predicate never judges severity —
236
+ * the tier is the child's call, this gate only asks whether a blocker paid its
237
+ * evidence. `rollup` deliberately does not call it: a review conclusion is not a
238
+ * place to refuse a round, and `rollup`'s return type stays `RoundStatus`. */
239
+ gradingViolations(findings) {
240
+ if (!Array.isArray(findings))
241
+ return [];
242
+ const violations = [];
243
+ for (const entry of findings) {
244
+ const row = entry;
245
+ if (row?.severity !== "blocker")
246
+ continue;
247
+ const scenario = row.impact?.scenario;
248
+ if (typeof scenario === "string" && scenario.trim().length > 0)
249
+ continue;
250
+ violations.push({
251
+ ...(typeof row.id === "string" && row.id.length > 0 ? { id: row.id } : {}),
252
+ ...(typeof row.summary === "string" ? { summary: row.summary } : {}),
253
+ });
254
+ }
255
+ return violations;
256
+ }
212
257
  /** The draft findings presented as round findings — unknown severities dropped
213
- * (the capsule's blocker count + the outcome's face, never the judgment domain). */
258
+ * (the capsule's blocker count + the outcome's face, never the judgment domain).
259
+ * The three cells the cross-round regrade judgment reads ride along (P37 §2.1 ·
260
+ * §5.1): the engine-written `id`, the blocker's `impact` and the round's own
261
+ * `regrade`. Each cell is projected only when it keeps its declared shape — a
262
+ * malformed cell reads as absent, never as a fabricated value. */
214
263
  findingsOf(findings) {
215
264
  if (!Array.isArray(findings))
216
265
  return [];
217
266
  const rows = [];
218
267
  for (const entry of findings) {
219
- const severity = entry?.severity;
268
+ const row = entry;
269
+ const severity = row?.severity;
220
270
  if (severity !== "blocker" && severity !== "warn" && severity !== "nit")
221
271
  continue;
222
- const summary = entry?.summary;
272
+ const id = _a.#textOf(row?.id);
273
+ const impact = _a.#impactOf(row?.impact);
274
+ const regrade = _a.#textOf(row?.regrade);
223
275
  rows.push({
224
276
  severity: severity,
225
- summary: typeof summary === "string" ? summary : undefined,
277
+ summary: _a.#textOf(row?.summary),
278
+ ...(id === undefined ? {} : { id }),
279
+ ...(impact === undefined ? {} : { impact }),
280
+ ...(regrade === undefined ? {} : { regrade }),
226
281
  });
227
282
  }
228
283
  return rows;
229
284
  }
285
+ /** P37 §5.1 — the cross-round downgrade judgment, a PURE predicate over the two
286
+ * rounds' findings projections. Returns the current rows that were graded BELOW a
287
+ * matching earlier row, whose earlier `impact.scenario` was non-empty, and that
288
+ * carry no `regrade` reason: exactly the rows the display face marks.
289
+ *
290
+ * The four steps, in order: (1) locate the matching earlier row on EITHER of two
291
+ * keys — the `summary` text (the defect's description, which survives a reworded
292
+ * scenario), or the earlier row's `impact.scenario` verbatim (the scenario did not
293
+ * change, so the defect did not either — the key §5.1 registers alongside the first
294
+ * one, not instead of it); a multi-row hit is narrowed by the engine-written `id`,
295
+ * never keyed on `id` (it is a row number, so a re-numbered carrier would pair
296
+ * unrelated defects); (2) an unchanged or raised grade is no downgrade; (3) a
297
+ * lowered grade against a non-empty scenario owes a `regrade` reason; (4) a lowered
298
+ * grade whose earlier scenario was empty has no reference, so the defect is read as
299
+ * changed. Omission or rewriting of THIS round's scenario never retires the duty once
300
+ * a pair is made — only the earlier row's scenario is read for the reference. */
301
+ static downgrades(prior, current) {
302
+ return current.filter((row) => _a.#downgradeReference(prior, row) !== undefined &&
303
+ _a.#textOf(row.regrade) === undefined);
304
+ }
305
+ /** P37 §5.1 · §5.2 — the reasons the round DID state, in carrier row order. The
306
+ * counterpart of `downgrades`: the same downgrade judgment, read on the rows that
307
+ * carry their `regrade` cell. The two sets partition one judgment, so a display face
308
+ * can print the mark and the reasons from ONE criterion instead of re-deciding which
309
+ * row was downgraded. */
310
+ static regradeReasons(prior, current) {
311
+ // Rule zero (class-size limit): this file is well past the limit and predates it —
312
+ // splitting it is P39's work (design spec D95 ②), not this round's.
313
+ const reasons = [];
314
+ for (const row of current) {
315
+ if (_a.#downgradeReference(prior, row) === undefined)
316
+ continue;
317
+ const reason = _a.#textOf(row.regrade);
318
+ if (reason !== undefined)
319
+ reasons.push(reason);
320
+ }
321
+ return reasons;
322
+ }
323
+ /** The earlier row a current row was graded below — §5.1's steps 1 → 4, absent for
324
+ * every row that is not a downgrade. Step 1 compares TWO keys: the `summary` text and
325
+ * the earlier row's `impact.scenario` verbatim. Either hit pairs; a multi-row hit is
326
+ * narrowed by `id`. Rewriting BOTH the summary and this round's scenario is the only
327
+ * way to cut a pair, and that is a declaration that the defect changed. */
328
+ static #downgradeReference(prior, row) {
329
+ const matches = prior.filter((candidate) => (candidate.summary !== undefined && candidate.summary === row.summary) ||
330
+ (candidate.impact?.scenario !== undefined &&
331
+ candidate.impact.scenario === row.impact?.scenario));
332
+ if (matches.length === 0)
333
+ return undefined;
334
+ const narrowed = matches.filter((candidate) => row.id !== undefined && candidate.id === row.id);
335
+ const reference = (narrowed.length > 0 ? narrowed : matches)[0];
336
+ if (reference === undefined)
337
+ return undefined;
338
+ if (_a.#tierRankOf(row.severity) >= _a.#tierRankOf(reference.severity)) {
339
+ return undefined;
340
+ }
341
+ if (_a.#textOf(reference.impact?.scenario) === undefined)
342
+ return undefined;
343
+ return reference;
344
+ }
345
+ /** The tier ladder's rank — higher is more severe (blocker 2 · warn 1 · nit 0). */
346
+ static #tierRankOf(severity) {
347
+ return severity === "blocker" ? 2 : severity === "warn" ? 1 : 0;
348
+ }
349
+ /** A non-blank string cell, else undefined — the projection's ONE blank test. */
350
+ static #textOf(value) {
351
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
352
+ }
353
+ /** The blocker's scenario cell when it keeps its declared shape — a scenario-less
354
+ * impact is absent, never a row carrying an empty reference. */
355
+ static #impactOf(value) {
356
+ const scenario = _a.#textOf(value?.scenario);
357
+ if (scenario === undefined)
358
+ return undefined;
359
+ const test = _a.#textOf(value?.test);
360
+ return test === undefined ? { scenario } : { scenario, test };
361
+ }
230
362
  /** The plane's writable subset — the ONE projection every consumer reads (prompt
231
363
  * fence · read-back validator · dropped-key walk). The properties are CARRIER's
232
364
  * own slot declarations filtered in declaration order; the required set comes from
@@ -1404,17 +1404,15 @@ export class Ledger {
1404
1404
  /** The handoff findings presented as round findings — entries with an unknown severity
1405
1405
  * are dropped (never invented into the judgment domain). */
1406
1406
  #findingsOf(carrier) {
1407
+ // Rule zero (class-size limit): this file is well past the limit and predates it —
1408
+ // splitting it is P39's work (design spec D95 ②), not this round's.
1407
1409
  if (!Array.isArray(carrier.findings))
1408
1410
  return [];
1409
- const findings = [];
1410
- for (const entry of carrier.findings) {
1411
- const severity = entry?.severity;
1412
- if (severity !== "blocker" && severity !== "warn" && severity !== "nit")
1413
- continue;
1414
- const summary = entry?.summary;
1415
- findings.push({ severity, summary: typeof summary === "string" ? summary : undefined });
1416
- }
1417
- return findings;
1411
+ // The ONE projection (P37 §2.1 · §5.1): the handoff schema's own findings row,
1412
+ // over the whole carrier at once — a consumer of this face and a consumer of the
1413
+ // read-back face see the same cells (id / impact / regrade included), and the
1414
+ // unknown-severity drop is the same rule, applied once.
1415
+ return this.#handoffSchema.findingsOf(carrier.findings);
1418
1416
  }
1419
1417
  /** The blocker count of a handoff carrier's findings — the C5-1 severity count. */
1420
1418
  #blockerCountOf(carrier) {