@oscaner-skills/cdd-engine 4.6.0 → 4.8.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.
@@ -124,6 +124,52 @@ export class IssueBodyRenderer {
124
124
  }
125
125
  });
126
126
  }
127
+ errors.push(...this.#relatedErrors(input.related));
128
+ return errors;
129
+ }
130
+ /** The `related` tail's shape leg — the nested `{ open?, closed?, program? }` is the
131
+ * only shape `renderBody` reads, so any other shape (a flat array, `null`, a
132
+ * scalar) is refused with its field path instead of silently dropping the tail. An
133
+ * absent `related` stays legal. */
134
+ #relatedErrors(raw) {
135
+ if (raw === undefined)
136
+ return [];
137
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
138
+ return ["related: object with open / closed / program expected"];
139
+ const related = raw;
140
+ return [
141
+ ...this.#hitErrors("open", related.open),
142
+ ...this.#hitErrors("closed", related.closed),
143
+ ...(related.program === undefined
144
+ ? []
145
+ : this.#issueErrors("related.program", related.program, false)),
146
+ ];
147
+ }
148
+ /** The open / closed hit rows — the array shape plus every element's `issue` number
149
+ * (an open hit carries `component` / `reason` on top). */
150
+ #hitErrors(kind, raw) {
151
+ if (raw === undefined)
152
+ return [];
153
+ const base = `related.${kind}`;
154
+ if (!Array.isArray(raw))
155
+ return [`${base}: array of ${kind} hits expected`];
156
+ return raw.flatMap((hit, i) => this.#issueErrors(`${base}[${i}]`, hit, kind === "open"));
157
+ }
158
+ /** One `{ issue: number }` row — `withContext` adds the open hit's two string rows. */
159
+ #issueErrors(base, raw, withContext) {
160
+ const shape = withContext ? "issue / component / reason" : "issue";
161
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
162
+ return [`${base}: object with ${shape} required`];
163
+ const row = raw;
164
+ const errors = [];
165
+ if (typeof row.issue !== "number")
166
+ errors.push(`${base}.issue: number required`);
167
+ if (!withContext)
168
+ return errors;
169
+ for (const field of ["component", "reason"]) {
170
+ if (typeof row[field] !== "string" || row[field].length === 0)
171
+ errors.push(`${base}.${field}: non-empty string required`);
172
+ }
127
173
  return errors;
128
174
  }
129
175
  }
@@ -121,7 +121,7 @@ const FIX_SHELL = [
121
121
  WORK_CAPABILITY,
122
122
  ...FIX_TYPED_INSTRUCTIONS,
123
123
  "**fix:** read `INPUT_REVIEWS` (open findings) + the plan context (`INPUT_WAVE_BRIEF` on a wave line — the complete plan mirror; `INPUT_PLAN` on the plan/branch lines — the plan document; `INPUT_SPEC` on the spec line — the spec 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).",
124
- '**Dispositions:** every requested finding needs a disposition keyed by its own summary text (verbatim), valued `{ "status": "fixed" | "rejected", "reason"?: "…" }` — a missing or mis-keyed disposition fails the round.',
124
+ '**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.',
125
125
  EVIDENCE_ITEM,
126
126
  ...LICENSE_ITEMS,
127
127
  // T5 (v0.3) — The work plane's ONE strict-schema sentence: every top-level draft
@@ -144,7 +144,9 @@ const DOCS_FIX_SHELL = [
144
144
  ...FRAME_ITEMS,
145
145
  WORK_CAPABILITY,
146
146
  "**docs-fix:** apply `INPUT_REVIEWS` (all severities) directly to the judged doc — `INPUT_PLAN` on a plan-doc line, `INPUT_SPEC` on a spec-doc line — removing fixed findings; record the path in `artifacts.doc` and report the round in `status` (APPROVED once every finding is applied, else BLOCKED + the reason in `notes`). Fix + write the draft at `OUTPUT_HANDOFF` per `## Handoff schema` in one process; retry = full re-run (idempotent).",
147
- '**Dispositions:** every requested finding needs a disposition keyed by its own summary text (verbatim), valued `{ "status": "fixed" | "rejected", "reason"?: "…" }` — a missing or mis-keyed disposition fails the round.',
147
+ "**Change-history rows:** a new `## Change history` row bumps the front-matter `version:` in the same edit — the header version is the lineage's newest numeric version, and the two can never disagree.",
148
+ "**Table cells:** never hard-wrap a table cell — a wrapped continuation parses as a row whose cell count disagrees with the header, and the lineage row it was meant to be stops registering.",
149
+ '**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.',
148
150
  ...LICENSE_ITEMS,
149
151
  // The generic strict-schema sentence — the SAME one the work shells carry: the
150
152
  // injected declaration is the draft's single field source, zero per-mode field
@@ -267,6 +269,13 @@ export const reviewGuideOf = (key) => {
267
269
  const text = REVIEW_BODY_TEXT[key];
268
270
  return SEVERITY_RUBRIC.replaceAll(SEVERITY_RUBRIC_SLOTS.artifact, text.artifact).replaceAll(SEVERITY_RUBRIC_SLOTS.audience, text.audience);
269
271
  };
272
+ /** The closed-wave discipline's ONE sentence (P30 §2.7) — the document review axes'
273
+ * shared body: a finding on an already-closed task block's content face is answered
274
+ * by the document, never by moving the work. Both document criteria bodies select
275
+ * it, so the duty cannot fork between the plan variant and the spec shapes; the
276
+ * engine routes nothing on it (no finding classification, no dispatch branch) — it is
277
+ * prompt text, judged by the reviewer. */
278
+ export const CLOSED_WAVE_DISCIPLINE = "Closed waves are history: a finding on the content face of an already-closed task block is answered by amending the document to align with the delivered split — never by carrying work into or out of a closed task, and a finding that would rewrite the historical split is not raised.";
270
279
  /** The spec-shaped documents' narrative criteria body — the phase-spec line's URC
271
280
  * + its program-conformance clause, the ONE body both spec-shaped target rows
272
281
  * select (the filled rubric is what differs per row). The charter's own criteria
@@ -276,7 +285,7 @@ export const reviewGuideOf = (key) => {
276
285
  * today's tree happens to have: a line number is not a pin, a prose count is the
277
286
  * guard's business, and a present-tense description of today's shape belongs to the
278
287
  * plan. Nothing gates the writing moment — the review is where a violation surfaces. */
279
- const docNarrativeAxes = (guide) => `Follow URC: single-cycle, lens-tagged findings (completeness/consistency/clarity) + 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 by module path + symbol name — a line number is not a pin; a count ("N places" · "N rows" · "N modules") must be stated as pinned by the named guard or test; a present-tense description of today's shape belongs to the plan — in a design spec a measurement input is a lens-tagged finding unless restated as a condition that must hold — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding + program conformance — judge the phase against its parent overall at \`INPUT_OVERALL\` (the charter its \`program:\` names): the phase must sit inside the scope the overall's Phase inventory registered for it, and a phase that reaches beyond it is a completeness finding. ${guide}`;
288
+ const docNarrativeAxes = (guide) => `Follow URC: single-cycle, lens-tagged findings (completeness/consistency/clarity) + 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 by module path + symbol name — a line number is not a pin; a count ("N places" · "N rows" · "N modules") must be stated as pinned by the named guard or test; a present-tense description of today's shape belongs to the plan — in a design spec a measurement input is a lens-tagged finding unless restated as a condition that must hold — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding + program conformance — judge the phase against its parent overall at \`INPUT_OVERALL\` (the charter its \`program:\` names): the phase must sit inside the scope the overall's Phase inventory registered for it, and a phase that reaches beyond it is a completeness finding. ${CLOSED_WAVE_DISCIPLINE} ${guide}`;
280
289
  /** The charter's criteria body — the six things a program charter owns, and only
281
290
  * those. It carries none of the implementation-face evidence duty the narrative
282
291
  * body carries (running the repository's commands, pinning every claim): a charter
@@ -306,7 +315,7 @@ export const REVIEWS = {
306
315
  },
307
316
  plan: {
308
317
  lensEnum: ["completeness", "decomposition", "buildability"],
309
- 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. ${reviewGuideOf("plan")}`,
318
+ 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")}`,
310
319
  },
311
320
  };
312
321
  /** The criteria-body selection — the ONE target → criteria map. Four targets select
@@ -42,6 +42,10 @@ import { TargetFaceTable, targetFaces, } from "./faces.js";
42
42
  import { DISPATCH_REASON, PIPELINE_FACES, } from "./next.js";
43
43
  import { PipelineFrontier } from "./pipeline.js";
44
44
  import { WaveGate } from "./wave.js";
45
+ /** The stable prefix of one hash end in a refusal's diagnosis — long enough to tell the
46
+ * two ends apart at a glance, short enough for one line (§2.5 leaves the exact
47
+ * completeness to the implementation; the two ends must stay distinguishable). */
48
+ export const DRIFT_HASH_PREFIX = 12;
45
49
  /**
46
50
  * DispatchAuthority — the ONE dispatch verdict (§2.1/§2.2). One `verdict` call walks
47
51
  * the three legs in priority order and returns the single verdict the CLI renders,
@@ -49,7 +53,9 @@ import { WaveGate } from "./wave.js";
49
53
  *
50
54
  * Rule zero on the ≤200-line class cap (broke by design, not by accident): the three
51
55
  * legs are one short-circuit chain over one `next:` assembly — extracted, the chain's
52
- * order moves to a caller and a refusal can name a round another leg contradicts.
56
+ * order moves to a caller and a refusal can name a round another leg contradicts. The
57
+ * drift diagnosis (§2.5) rides the same chain: it is read off the hop the refusal
58
+ * already names, and its ONE rendering site is `message`.
53
59
  */
54
60
  export class DispatchAuthority {
55
61
  /** The wave face's five rows — this leg's wave judge (the judgment body stays in
@@ -71,15 +77,21 @@ export class DispatchAuthority {
71
77
  return this.#lineLeg(request);
72
78
  }
73
79
  /** message(verdict, render) — the ONE refusal line (§2.6): `reason · next: ` plus
74
- * the command the hop renders, or `reason · <wording>` on the structure leg. */
80
+ * the command the hop renders, or `reason · <wording>` on the structure leg. A drift
81
+ * refusal carries its mandatory diagnosis (§2.5) between the reason and the hop, so
82
+ * the CLI prints layer · line key · both hash ends without a second wording source. */
75
83
  message(verdict, render) {
84
+ const reason = _a.#driftReasonText(verdict);
76
85
  if (verdict.next === null) {
77
86
  return render.detail === undefined || render.detail === ""
78
- ? verdict.reason
79
- : `${verdict.reason} · ${render.detail}`;
87
+ ? reason
88
+ : `${reason} · ${render.detail}`;
80
89
  }
81
90
  const command = render.command === undefined ? "" : render.command(verdict.next);
82
- return `${verdict.reason} · next: ${command}`;
91
+ // The reopen flag rides the command the renderer produced — the SAME review
92
+ // command, one flag added (`--recover`), never a second literal (P30 §2.3).
93
+ const recover = verdict.recover === true ? " --recover" : "";
94
+ return `${reason} · next: ${command}${recover}`;
83
95
  }
84
96
  /** The structure leg's verdict — the seam's refusal re-expressed as this chain's
85
97
  * first row. Its token is the refusing gate's own id (the table's structure rows:
@@ -109,15 +121,42 @@ export class DispatchAuthority {
109
121
  const station = this.#stationOf(face, request.line);
110
122
  if (station === null)
111
123
  continue;
112
- const next = this.#hopOf(request.line);
113
- const reason = station === "drift" ? DISPATCH_REASON.docDrift.token : next.reason;
114
- return { allowed: false, leg: "upstream", reason, next };
124
+ return this.#stationRefusal(station, request.line);
115
125
  }
116
126
  return null;
117
127
  }
118
- /** One upstream face's station sign — ① first (a moved reviewed identity refuses as
119
- * `doc-drift` whatever the closure cell says), then ② (the face has not closed for
120
- * the request, so the frontier's own hop reason rules). */
128
+ /** One upstream station's refusal (§2.3/§2.4) — the reason and the `next:` are read
129
+ * off the SAME station sign: a moved brief names `brief-drift` and points at that
130
+ * batch's wave review (never the pipeline frontier's branch hop, which belongs to a
131
+ * different face's fact), a moved document names `doc-drift` and points at the
132
+ * frontier's own hop, and an unclosed face keeps the hop's own reason. */
133
+ #stationRefusal(station, facts) {
134
+ if (station.kind === "brief-drift") {
135
+ return this.#refusal("upstream", DISPATCH_REASON.briefDrift.token, this.#waveReviewHop(facts, station.batch), facts);
136
+ }
137
+ const next = this.#hopOf(facts);
138
+ const reason = station.kind === "doc-drift" ? DISPATCH_REASON.docDrift.token : next.reason;
139
+ return this.#refusal("upstream", reason, next, facts);
140
+ }
141
+ /** The wave review hop of a drifted batch (P29 §2.4) — the ONE assembly
142
+ * (`Ledger#nextHopOf`) with the moved-brief cell injected and the wave target of the
143
+ * FIRST drifted open batch, so the refusal's `next:` is `review --type wave --tasks
144
+ * <batch> --plan <plan>` and its reason is the brief's own token. */
145
+ #waveReviewHop(facts, batch) {
146
+ const planPath = facts.pipeline.planPath;
147
+ return facts.ledger.nextHopOf({
148
+ type: "wave",
149
+ key: batch,
150
+ route: { kind: "review" },
151
+ target: { type: "wave", id: batch, plan: planPath ?? undefined },
152
+ briefDrift: true,
153
+ docClassOf: facts.docClassOf,
154
+ });
155
+ }
156
+ /** One upstream face's station sign (§2.1/§2.3) — ① first (a moved reviewed identity
157
+ * refuses whatever the closure cell says), then ② (the face has not closed for the
158
+ * request, so the frontier's own hop reason rules). The wave face reports the
159
+ * BRIEF's movement, the doc faces the document's — two layers, two tokens. */
121
160
  #stationOf(face, facts) {
122
161
  if (face === "wave")
123
162
  return this.#waveStation(facts);
@@ -129,12 +168,18 @@ export class DispatchAuthority {
129
168
  if (!_a.#docEntered(ledger, line))
130
169
  return null;
131
170
  if (ledger.reviewGate(line.key, line.doc, line.type).kind === "open")
132
- return "drift";
133
- return ledger.lineStateAt(line.key, line.type, line.doc) === "closed" ? null : "open";
171
+ return { kind: "doc-drift" };
172
+ return ledger.lineStateAt(line.key, line.type, line.doc) === "closed" ? null : { kind: "open" };
134
173
  }
135
174
  /** The wave face's station — read off the SAME two judges the frontier runs, never a
136
175
  * local walk: entered over the three dispatch modes, drifted over the derived
137
- * batches' reviewed briefs, exhausted over `closedWaves()`. */
176
+ * batches' reviewed briefs, exhausted over `closedWaves()`.
177
+ *
178
+ * P29 §2.1 — the drift read is NOT retroactive: a batch whose tasks all sit in
179
+ * `closedWaves()` is filtered out before `briefDrifted` runs. A closed wave has no
180
+ * round left to reopen, so its stale brief is nobody's `next:` (the #438 face: a
181
+ * finished run's plan edit blocked the branch review). Only an OPEN batch's brief
182
+ * movement refuses the faces below the wave face. */
138
183
  #waveStation(facts) {
139
184
  const graph = facts.pipeline.planGraph;
140
185
  if (graph === null)
@@ -142,10 +187,25 @@ export class DispatchAuthority {
142
187
  const frontier = this.#frontierOf(facts);
143
188
  if (!frontier.wavesEntered(graph))
144
189
  return null;
145
- const drifted = graph.batches().some((batch) => facts.ledger.briefDrifted(batch.join(",")));
146
- if (drifted)
147
- return "drift";
148
- return frontier.wavesExhausted(graph) ? null : "open";
190
+ const batch = _a.#firstDriftedOpenBatch(graph, facts.ledger);
191
+ if (batch !== null)
192
+ return { kind: "brief-drift", batch };
193
+ return frontier.wavesExhausted(graph) ? null : { kind: "open" };
194
+ }
195
+ /** The FIRST open batch whose task-only brief moved (`graph.batches()` order — the
196
+ * ONE order §2.4 makes executable) — null when every batch is either closed or
197
+ * undrifted. The closure cell is `closedWaves()`, the same read the frontier's
198
+ * exhaustion uses: a batch is closed when every one of its tasks is. */
199
+ static #firstDriftedOpenBatch(graph, ledger) {
200
+ const closed = ledger.closedWaves();
201
+ for (const batch of graph.batches()) {
202
+ if (batch.every((id) => closed.has(id)))
203
+ continue;
204
+ const key = batch.join(",");
205
+ if (ledger.briefDrifted(key))
206
+ return key;
207
+ }
208
+ return null;
149
209
  }
150
210
  /** The line leg — this line's phase against the requested one, with the refusal's
151
211
  * `next` read from the pipeline frontier only when the line actually refuses. */
@@ -153,9 +213,64 @@ export class DispatchAuthority {
153
213
  const ruling = request.type === "wave" ? this.#waveRuling(request) : this.#docRuling(request);
154
214
  if (ruling.kind === "allowed")
155
215
  return { allowed: true };
156
- const next = this.#hopOf(request.line);
216
+ const next = ruling.kind === "row" && ruling.hop !== undefined ? ruling.hop : this.#hopOf(request.line);
157
217
  const reason = ruling.kind === "row" ? ruling.reason : next.reason;
158
- return { allowed: false, leg: "line", reason, next };
218
+ const recover = ruling.kind === "row" ? ruling.recover : undefined;
219
+ return this.#refusal("line", reason, next, request.line, recover);
220
+ }
221
+ /** One refusal, with its drift diagnosis attached when the reason is a drift token
222
+ * (§2.5 — one construction point, so no refusal has a second path to print by). The
223
+ * diagnosis reads the identity the hop itself names (`NextHop.target`), never a
224
+ * second lookup of which line moved. It is absent exactly when the target records no
225
+ * pair — a diagnosis never invents a fact, so an underivable identity prints the
226
+ * bare token. */
227
+ #refusal(leg, reason, next, facts, recover) {
228
+ const drift = _a.#isDriftReason(reason)
229
+ ? _a.#driftOf(next, facts)
230
+ : undefined;
231
+ const base = { allowed: false, leg, reason, next };
232
+ return {
233
+ ...base,
234
+ ...(drift === undefined ? {} : { drift }),
235
+ ...(recover === true ? { recover: true } : {}),
236
+ };
237
+ }
238
+ /** Whether a token names a moved reviewed identity — the two rows whose refusal line
239
+ * must carry the diagnosis (§2.5). */
240
+ static #isDriftReason(reason) {
241
+ return reason === DISPATCH_REASON.briefDrift.token || reason === DISPATCH_REASON.docDrift.token;
242
+ }
243
+ /** The diagnosis of the hop's OWN render target (§2.5) — a wave target is judged on
244
+ * its brief's task-only projection, every doc shape on its document revision, and the
245
+ * hop's target is the identity the refusal already names (never a second lookup of
246
+ * which line moved). Undefined when the target holds no identity on record: a
247
+ * diagnosis never invents a fact. */
248
+ static #driftOf(next, facts) {
249
+ const target = next.target;
250
+ if (target === null)
251
+ return undefined;
252
+ const brief = target.type === "wave";
253
+ const pair = brief
254
+ ? facts.ledger.briefDriftHashes(String(target.id))
255
+ : _a.#docDriftPair(target, facts);
256
+ return pair === null ? undefined : { layer: brief ? "brief" : "doc", ...pair };
257
+ }
258
+ /** The doc target's diagnosis read — the target's own type is the ledger key of the
259
+ * line it renders (`plan` / `branch` / the declared spec word), and a branch target
260
+ * carries its document in `plan`, every other shape in `id`. */
261
+ static #docDriftPair(target, facts) {
262
+ const doc = target.type === "branch" ? (target.plan ?? null) : target.id;
263
+ return doc === null ? null : facts.ledger.docDriftHashes(target.type, doc, target.type);
264
+ }
265
+ /** The refusal line's reason head — the token alone, or the token plus the mandatory
266
+ * diagnosis (§2.5): `layer=` · `line=` · `recorded=` · `current=` with a stable hash
267
+ * prefix per end. ONE rendering site, so the CLI cannot print a second wording. */
268
+ static #driftReasonText(verdict) {
269
+ const drift = verdict.drift;
270
+ if (drift === undefined)
271
+ return verdict.reason;
272
+ const prefix = (hash) => hash.slice(0, DRIFT_HASH_PREFIX);
273
+ return `${verdict.reason} · layer=${drift.layer} · line=${drift.line} · recorded=${prefix(drift.recorded)} · current=${prefix(drift.current)}`;
159
274
  }
160
275
  /** The wave face's rows — the three-verb gate judged whole (its order IS the
161
276
  * judgment: a shape matching an earlier row keeps that earlier row's cause). */
@@ -213,9 +328,15 @@ export class DispatchAuthority {
213
328
  return { kind: "allowed" };
214
329
  }
215
330
  // A pending fix is the line's own row: the fix it awaits is a present fact, and
216
- // the refusal names it whatever the requested verb was.
217
- if (phase.phase === "fix")
218
- return { kind: "row", reason: DISPATCH_REASON.pendingFix.token };
331
+ // the refusal names it whatever the requested verb was. On a DRIFTED line the same
332
+ // row is reopenable — the `next:` is then the review round the `--recover` flag
333
+ // reopens (P30 §2.3), never the fix the old design already outran.
334
+ if (phase.phase === "fix") {
335
+ const reopen = _a.#reopenHop(facts, request.type);
336
+ return reopen === null
337
+ ? { kind: "row", reason: DISPATCH_REASON.pendingFix.token }
338
+ : { kind: "row", reason: DISPATCH_REASON.pendingFix.token, recover: true, hop: reopen };
339
+ }
219
340
  if (phase.phase !== null)
220
341
  return { kind: "hop" };
221
342
  // The closed line: the doc shapes name their unchanged reviewed identity (the
@@ -226,6 +347,41 @@ export class DispatchAuthority {
226
347
  reason: unchanged ? DISPATCH_REASON.unchanged.token : DISPATCH_REASON.faceClosed.token,
227
348
  };
228
349
  }
350
+ /** Whether the line sits at the REOPENABLE face — `reviewGate` open (the document
351
+ * drifted past what the review bound) AND a fix still owed (P30 §2.3's condition
352
+ * pair ①②). Read from the ledger's own derivations (`reviewGate` · `pendingFix`),
353
+ * never a second walk: the refusal's `--recover` hint and the CLI's reopen leg judge
354
+ * the same pair. */
355
+ static #reopenable(facts, type) {
356
+ const { lineKey: key, doc, ledger } = facts;
357
+ if (key === null || doc === null)
358
+ return false;
359
+ if (type === "wave")
360
+ return false;
361
+ return ledger.reviewGate(key, doc, type).kind === "open" && ledger.pendingFix(key, type);
362
+ }
363
+ /** The reopenable line's REVIEW hop — the round `--recover` makes dispatchable, built
364
+ * through the ONE hop assembly (`Ledger#nextHopOf`) so the refusal's `next:` is the
365
+ * same command the capsule and the board render (P30 §2.3). Null when the line is
366
+ * not reopenable (the refusal then keeps the frontier's own hop). */
367
+ static #reopenHop(facts, type) {
368
+ if (!_a.#reopenable(facts, type))
369
+ return null;
370
+ const { lineKey: key, doc } = facts;
371
+ if (key === null || doc === null)
372
+ return null;
373
+ // The render target's own shape (a branch line carries its plan as `plan`, every
374
+ // doc shape carries the document as `id`) — the frontier's own construction.
375
+ const target = type === "branch" ? { type: "branch", id: "branch", plan: doc } : { type, id: doc };
376
+ return facts.ledger.nextHopOf({
377
+ type,
378
+ key,
379
+ route: { kind: "review" },
380
+ target,
381
+ doc,
382
+ docClassOf: facts.docClassOf,
383
+ });
384
+ }
229
385
  /** The phase the requested verb dispatches on this face — the review verb asks for
230
386
  * the face's OWN review lead (the branch line's `branch-review`). */
231
387
  #expectedPhase(type, verb) {
@@ -28,11 +28,18 @@
28
28
  // behavior-carrying bare functions (the plan's zero-bare-function discipline).
29
29
  /** One finding row — the shared base declaration of the judge plane (severity +
30
30
  * lens + summary required; the extra review columns — section / line / fix — are
31
- * declared optional, and unknown extra fields ride along). */
31
+ * declared optional, and unknown extra fields ride along).
32
+ *
33
+ * `id` is declared OPTIONAL on purpose (P30 §2.5): the engine writes the stable key
34
+ * (`F1`, `F2` … in carrier order) at materialize and overwrites whatever the child
35
+ * put there, so the prompt shows the field exists while the child owes nothing. A
36
+ * required `id` would push an engine-owned value onto the child and add a pointless
37
+ * read-back BLOCK face for a field the engine always rewrites. */
32
38
  const FINDING = {
33
39
  type: "object",
34
40
  required: ["severity", "lens", "summary"],
35
41
  properties: {
42
+ id: { type: "string" },
36
43
  severity: { type: "string", enum: ["blocker", "warn", "nit"] },
37
44
  lens: { type: "string" },
38
45
  section: { type: "string" },
@@ -29,6 +29,7 @@
29
29
  //
30
30
  // Module-level exports are types / the error class / the class — zero
31
31
  // behavior-carrying bare functions.
32
+ var _a;
32
33
  import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
33
34
  import path from "node:path";
34
35
  import lockfile from "proper-lockfile";
@@ -63,6 +64,15 @@ export class InFlight {
63
64
  static LOCK_STALE_MS = 12 * 60 * 60 * 1000;
64
65
  /** The lock's refresh interval (ms). */
65
66
  static LOCK_UPDATE_MS = 60 * 1000;
67
+ /** The three takeover reasons of a stale tree — ONE literal per morphology (spec
68
+ * §2.1①: a dead holder, a corrupt record with a leftover lock, a lock with no record
69
+ * behind it). Shared by `acquire({ recover })`'s pre-step and the abort fold, so a
70
+ * takeover can never be named two ways. */
71
+ static STEAL_REASON = {
72
+ deadHolder: "the holder is dead",
73
+ corruptRecord: "the record is corrupt and the lock is left behind",
74
+ lockOnly: "a lock without a record",
75
+ };
66
76
  #root;
67
77
  #slug;
68
78
  #liveness;
@@ -76,7 +86,7 @@ export class InFlight {
76
86
  }
77
87
  /** The record's absolute path (`<workspaceRoot>/in-flight.json`). */
78
88
  path() {
79
- return path.join(this.#root.path, InFlight.FILE);
89
+ return path.join(this.#root.path, _a.FILE);
80
90
  }
81
91
  /** The lock directory's absolute path (`proper-lockfile`'s default carrier). */
82
92
  lockPath() {
@@ -96,19 +106,19 @@ export class InFlight {
96
106
  * → live-holder guard → lock → record. The guard is the class's OWN fail-closed
97
107
  * check that a standing record is never displaced while its holder lives: the
98
108
  * pre-flight gate is the primary guard, this one keeps the invariant true for any
99
- * other write point. `stealStale` only acts HERE: a standing record whose holder is
109
+ * other write point. `recover` only acts HERE: a standing record whose holder is
100
110
  * dead (or a corrupt record with a leftover lock) is taken over first; a live holder
101
111
  * is never displaced. A failed lock throws `HoldingError` carrying the holder's
102
112
  * facts and leaves the record bytes untouched. */
103
113
  async acquire(record, options = {}) {
104
114
  this.ensureMarker();
105
- if (options.stealStale === true)
115
+ if (options.recover === true)
106
116
  await this.#stealIfDead();
107
117
  await this.#refuseLiveHolder();
108
118
  try {
109
119
  this.#unlock = await lockfile.lock(this.path(), {
110
- stale: InFlight.LOCK_STALE_MS,
111
- update: InFlight.LOCK_UPDATE_MS,
120
+ stale: _a.LOCK_STALE_MS,
121
+ update: _a.LOCK_UPDATE_MS,
112
122
  realpath: false,
113
123
  retries: 0,
114
124
  });
@@ -187,7 +197,22 @@ export class InFlight {
187
197
  return { kind: "absent" };
188
198
  return { kind: "corrupt", locked: existsSync(this.lockPath()) };
189
199
  }
190
- /** Take the record over explicitly — the `--steal-stale` path. The precondition is
200
+ /** The tree's STALE in-flight — the three takeover morphologies of spec §2.1①
201
+ * define the answer, so every reader names the same stale face: a dead holder's
202
+ * readable record, a corrupt record with a leftover lock, or a lock with no record
203
+ * behind it. Null when the tree is FREE or a LIVE holder stands (a live holder is
204
+ * never displaced). ONE predicate for `acquire({ recover })`'s pre-step, the abort
205
+ * fold and the composition root's reopen judgment — a stale tree can never be
206
+ * named two ways. */
207
+ async staleState() {
208
+ const state = await this.inspect();
209
+ if (state.kind === "held")
210
+ return state.alive ? null : state;
211
+ if (state.kind === "corrupt")
212
+ return state.locked ? state : null;
213
+ return existsSync(this.lockPath()) ? state : null;
214
+ }
215
+ /** Take the record over explicitly — the `--recover` path. The precondition is
191
216
  * that the holder cannot be alive: a readable record whose pid is live is refused
192
217
  * (the flag never crosses "alive → no takeover"); a corrupt record has no live
193
218
  * fact to honor and is cleared. Clears the lock, then the record. */
@@ -209,22 +234,21 @@ export class InFlight {
209
234
  rmSync(this.path(), { force: true });
210
235
  return record;
211
236
  }
212
- /** The `stealStale` pre-step of acquire: take over a standing record whose holder is
237
+ /** The `recover` pre-step of acquire: take over a standing record whose holder is
213
238
  * dead, a corrupt record with a leftover lock, or a lock remnant with no record —
214
- * and do nothing while the holder is alive (the lock then refuses the acquire). */
239
+ * and do nothing while the holder is alive (the lock then refuses the acquire).
240
+ * The morphology predicate is `staleState()`; this only names the takeover. */
215
241
  async #stealIfDead() {
216
- const state = await this.inspect();
217
- if (state.kind === "held" && !state.alive) {
218
- await this.steal("the holder is dead");
242
+ const stale = await this.staleState();
243
+ if (stale === null)
219
244
  return;
220
- }
221
- if (state.kind === "corrupt" && state.locked) {
222
- await this.steal("the record is corrupt and the lock is left behind");
245
+ if (stale.kind === "held") {
246
+ await this.steal(_a.STEAL_REASON.deadHolder);
223
247
  return;
224
248
  }
225
- if (state.kind === "absent" && existsSync(this.lockPath())) {
226
- await this.steal("a lock without a record");
227
- }
249
+ await this.steal(stale.kind === "corrupt"
250
+ ? _a.STEAL_REASON.corruptRecord
251
+ : _a.STEAL_REASON.lockOnly);
228
252
  }
229
253
  /** The refusal message — the holder's identity facts as plain text (the words
230
254
  * table owns the CLI's held report; this is the thrown carrier's own summary). */
@@ -232,7 +256,7 @@ export class InFlight {
232
256
  if (holder === null) {
233
257
  return `another dispatch holds the in-flight lock under ${this.#root.path} — the standing record is unreadable (dispatch ${this.#slug} refuses to overwrite it)`;
234
258
  }
235
- return `another dispatch is in flight: pid ${holder.pid} (${holder.command}), slug ${holder.slug}, started ${new Date(holder.startedAt).toISOString()} — it must finish, or its record must be taken over with --steal-stale`;
259
+ return `another dispatch is in flight: pid ${holder.pid} (${holder.command}), slug ${holder.slug}, started ${new Date(holder.startedAt).toISOString()} — it must finish, or its record must be taken over with --recover`;
236
260
  }
237
261
  /** The record write — the JSON shape through the ONE atomic write seam, with the
238
262
  * repo's single trailing newline. */
@@ -275,8 +299,10 @@ export class InFlight {
275
299
  attempt: typeof row.attempt === "number" ? row.attempt : null,
276
300
  briefHash: typeof row.briefHash === "string" ? row.briefHash : null,
277
301
  plan: typeof row.plan === "string" ? row.plan : null,
302
+ dispatchBase: typeof row.dispatchBase === "string" ? row.dispatchBase : null,
278
303
  sampledAt: typeof row.sampledAt === "number" ? row.sampledAt : null,
279
304
  verdict: typeof row.verdict === "string" ? row.verdict : null,
280
305
  };
281
306
  }
282
307
  }
308
+ _a = InFlight;