@oscaner-skills/cdd-engine 4.7.0 → 4.9.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.
@@ -9,6 +9,8 @@
9
9
  // cross-doc-chain · section-scoped-domain ·
10
10
  // phase-design-spec-is-phase-spec;
11
11
  // the change-history family — change-history-version-unique ·
12
+ // change-history-header-columns · change-history-row-shape ·
13
+ // change-history-latest-matches-front-matter ·
12
14
  // front-matter-version-in-lineage ·
13
15
  // change-history-row-not-in-other-table · list-marker-not-doubled;
14
16
  // the identity legs — task-id-unique · phase-id-unique;
@@ -153,21 +155,56 @@ export class Invariant extends MarkdownPrimitives {
153
155
  }
154
156
  /** The doc's `## Change history` table — the ONE lineage read face all four doc
155
157
  * types expose (each parse record carries it, filled by the same table-section
156
- * read). The change-history strategies read ONLY through this accessor. */
158
+ * read). The change-history strategies read ONLY through this accessor. The
159
+ * record keeps the header and the body rows verbatim: a row whose cell count
160
+ * disagrees with the header is judged by `change-history-row-shape`, never
161
+ * repaired or dropped here. */
157
162
  changeHistory(ctx) {
158
163
  return ctx.parsed.tables["Change history"];
159
164
  }
160
- /** The first `vX.Y` version token on a line — the lineage row's identity read. */
161
- firstVersion(text) {
162
- const match = text.match(/v\d+\.\d+/);
163
- return match === null ? null : match[0];
165
+ /** The version token of a lineage row — the FIRST cell read ANCHORED: the cell must
166
+ * BE the version, never merely carry one (an in-cell prose mention of `spec v0.4`
167
+ * is not an identity). */
168
+ lineageVersion(row) {
169
+ const cell = (row[0] ?? "").trim();
170
+ return /^v\d+\.\d+$/.test(cell) ? cell : null;
171
+ }
172
+ /** The change-history rows that ARE lineage rows — the ones whose cell count matches
173
+ * the table's column header. A row whose cells disagree with the header (a
174
+ * hard-wrapped cell) is a SHAPE fact — reported by `change-history-row-shape`,
175
+ * never silently read as a lineage identity. Duplicate detection and the
176
+ * newest-row leg read ONLY this set. */
177
+ lineageRows(ctx) {
178
+ const table = this.changeHistory(ctx);
179
+ const width = table.headerRow?.length ?? 0;
180
+ if (width === 0)
181
+ return [];
182
+ return table.rows.filter((row) => row.length === width);
183
+ }
184
+ /** The anchored cell-0 versions of EVERY change-history body row, whatever its width.
185
+ * Membership is the one read a shape-ragged row must not starve: when the header
186
+ * version lives only on the newest row and that row hard-wraps, the version is still
187
+ * the document's own lineage (its shape is a separate defect).
188
+ * `front-matter-version-in-lineage` reads this set; the duplicate and newest-row legs
189
+ * keep `historyVersions`. */
190
+ membershipVersions(ctx) {
191
+ return this.changeHistory(ctx)
192
+ .rows.map((row) => this.lineageVersion(row))
193
+ .filter((version) => version !== null);
194
+ }
195
+ /** The numeric comparison rank of a version token — the lineage's newest row is a
196
+ * NUMERIC read (`v0.10` outranks `v0.9`), never a lexical one. */
197
+ versionRank(version) {
198
+ const [major, minor] = version.replace(/^v/, "").split(".");
199
+ return Number(major) * 1_000_000 + Number(minor);
164
200
  }
165
201
  /** The doc's Change-history row versions, in row order — the ONE lineage identity
166
- * read every lineage strategy shares (one copy on the base, zero per-strategy
167
- * private duplicates). */
202
+ * read the duplicate and newest-row strategies share (one copy on the base, zero
203
+ * per-strategy private duplicates). Header-width rows only: a shape-ragged row is
204
+ * no lineage identity (membership's wider read is `membershipVersions`). */
168
205
  historyVersions(ctx) {
169
- return this.changeHistory(ctx)
170
- .rows.map((row) => this.firstVersion(row[0] ?? ""))
206
+ return this.lineageRows(ctx)
207
+ .map((row) => this.lineageVersion(row))
171
208
  .filter((version) => version !== null);
172
209
  }
173
210
  /** The identity index every slug-keyed strategy looks up through — the caller's
@@ -382,17 +419,79 @@ export class ChangeHistoryVersionUniqueInvariant extends Invariant {
382
419
  evaluate(ctx) {
383
420
  const findings = [];
384
421
  const seenVersions = new Set();
385
- for (const row of this.changeHistory(ctx).rows) {
386
- const version = this.firstVersion(row[0] ?? "");
387
- if (version !== null && seenVersions.has(version)) {
422
+ for (const version of this.historyVersions(ctx)) {
423
+ if (seenVersions.has(version)) {
388
424
  findings.push(this.finding(ctx, "Change history", `duplicate change-history version: ${version} registers more than once`, "keep each lineage version in exactly one Change-history row"));
389
425
  }
390
- if (version !== null)
391
- seenVersions.add(version);
426
+ seenVersions.add(version);
392
427
  }
393
428
  return findings;
394
429
  }
395
430
  }
431
+ /** change-history-row-shape — a Change-history body row whose cell count disagrees with
432
+ * the table's column header is a rendering defect (a hard-wrapped cell parsed as its
433
+ * own row). The row is REPORTED, never silently dropped from the lineage read. */
434
+ export class ChangeHistoryRowShapeInvariant extends Invariant {
435
+ name = "change-history-row-shape";
436
+ evaluate(ctx) {
437
+ const table = this.changeHistory(ctx);
438
+ const width = table.headerRow?.length ?? 0;
439
+ if (width === 0)
440
+ return [];
441
+ const findings = [];
442
+ for (const row of table.rows) {
443
+ if (row.length === width)
444
+ continue;
445
+ findings.push(this.finding(ctx, "Change history", `a Change-history row carries ${row.length} cells against the ${width}-column header`, "keep the row on one line — a hard-wrapped cell parses as a row of its own"));
446
+ }
447
+ return findings;
448
+ }
449
+ }
450
+ /** The DECLARED `## Change history` column set — the header must equal it cell for
451
+ * cell (after `trim`). The row-shape leg judges a row against whatever the header
452
+ * declares; this declaration is what makes the header itself a judged fact. */
453
+ export const CHANGE_HISTORY_COLUMNS = ["Version", "date", "summary", "author"];
454
+ /** change-history-header-columns — the `## Change history` header must BE the declared
455
+ * column set: a grown, dropped or renamed column silently redefines what every row
456
+ * means, so it is reported once, independently of the row widths (the two legs are
457
+ * orthogonal: this one reads the header, `change-history-row-shape` reads the rows
458
+ * against that header). An absent section / header judges nothing here. */
459
+ export class ChangeHistoryHeaderColumnsInvariant extends Invariant {
460
+ name = "change-history-header-columns";
461
+ evaluate(ctx) {
462
+ const header = this.changeHistory(ctx).headerRow;
463
+ if (header === null || header.length === 0)
464
+ return [];
465
+ const cells = header.map((cell) => cell.trim());
466
+ const declared = CHANGE_HISTORY_COLUMNS;
467
+ const conforms = cells.length === declared.length && cells.every((cell, index) => cell === declared[index]);
468
+ if (conforms)
469
+ return [];
470
+ return [
471
+ this.finding(ctx, "Change history", `the Change-history header reads "${cells.join(" | ")}" against the declared "${declared.join(" | ")}"`, `write the header as | ${declared.join(" | ")} | — the column set is declared, not free-form`),
472
+ ];
473
+ }
474
+ }
475
+ /** change-history-latest-matches-front-matter — the front-matter `version:` IS the
476
+ * lineage's newest numeric version: appending a row lifts both in the same edit, so
477
+ * the two sides can never disagree. */
478
+ export class ChangeHistoryLatestMatchesFrontMatterInvariant extends Invariant {
479
+ name = "change-history-latest-matches-front-matter";
480
+ evaluate(ctx) {
481
+ const headerVersion = ctx.head.version;
482
+ if (headerVersion === null)
483
+ return [];
484
+ const versions = this.historyVersions(ctx);
485
+ if (versions.length === 0)
486
+ return [];
487
+ const latest = versions.reduce((newest, version) => this.versionRank(version) > this.versionRank(newest) ? version : newest);
488
+ if (latest === headerVersion)
489
+ return [];
490
+ return [
491
+ this.finding(ctx, "version", `the header version ${headerVersion} is not the newest lineage version ${latest}`, `align the two in one edit — bump the version front-matter key to ${latest}, or add the row that reaches ${headerVersion}`),
492
+ ];
493
+ }
494
+ }
396
495
  /** task-id-unique — every `### Task N:` id registers exactly once (plan). */
397
496
  export class TaskIdUniqueInvariant extends Invariant {
398
497
  name = "task-id-unique";
@@ -762,20 +861,22 @@ export class HollowInvariant extends Invariant {
762
861
  * the endpoints and the age of the row carrying the value are the author's
763
862
  * presentation choice, never a judgment input (a newest-first lineage, a
764
863
  * non-monotone frozen history and an ascending one all judge the same). The fix
765
- * names the header key, never a row to reorder. */
864
+ * names the header key, never a row to reorder. Membership reads EVERY body row's
865
+ * anchored cell 0 (`membershipVersions`), so a version carried only by a
866
+ * shape-ragged row still counts as lineage. */
766
867
  export class FrontMatterVersionInLineageInvariant extends Invariant {
767
868
  name = "front-matter-version-in-lineage";
768
869
  evaluate(ctx) {
769
870
  const headerVersion = ctx.head.version;
770
871
  if (headerVersion === null)
771
872
  return [];
772
- const historyVersions = this.historyVersions(ctx);
773
- if (historyVersions.length === 0)
873
+ const membership = this.membershipVersions(ctx);
874
+ if (membership.length === 0)
774
875
  return [];
775
- if (historyVersions.includes(headerVersion))
876
+ if (membership.includes(headerVersion))
776
877
  return [];
777
878
  return [
778
- this.finding(ctx, "version", `the header version ${headerVersion} is outside the document's own lineage`, `the version front-matter key must belong to the Change-history row versions: ${historyVersions.join(", ")}`),
879
+ this.finding(ctx, "version", `the header version ${headerVersion} is outside the document's own lineage`, `the version front-matter key must belong to the Change-history row versions: ${membership.join(", ")}`),
779
880
  ];
780
881
  }
781
882
  }
@@ -17,14 +17,16 @@
17
17
  // list — these declarations are the rule surface. One rule = one strategy: the
18
18
  // multi-surface strategies of the old family were split per leg (uniqueness → three,
19
19
  // order → one section-order row, selfBounded → one lineage row), so a declaration row
20
- // never hides a second rule. The version-order leg and the header-equals-last-row leg
21
- // are not declared at all: ordering is presentation, not data integrity, and the
22
- // lineage judgment is membership-only.
20
+ // never hides a second rule. Version ORDER stays presentation, not data integrity; the
21
+ // header-to-newest-row agreement, the header's own column set and the row's cell shape
22
+ // are declared legs of their own (`change-history-latest-matches-front-matter` ·
23
+ // `change-history-header-columns` · `change-history-row-shape`), and the lineage
24
+ // identity read is membership-plus-anchor (the first cell must BE a version).
23
25
  //
24
26
  // Module-level exports are types / the declared data — zero behavior-carrying bare
25
27
  // functions.
26
- import { ChangeHistoryVersionUniqueInvariant, ContinuityInvariant, CrossDocChainInvariant, CrosslinkInvariant, DomainInvariant, FileExistenceInvariant, FrontMatterVersionInLineageInvariant, HollowInvariant, LedgerLayeringRule, LedgerTaskSetRule, LinkShapeInvariant, ListMarkerInvariant, PhaseDesignSpecIsPhaseSpecInvariant, PhaseIdUniqueInvariant, PresenceInvariant, ResidueInvariant, RowHomeInvariant, SectionOrderInvariant, SectionScopedDomainInvariant, SiblingScanInvariant, SlugRefInvariant, TaskIdUniqueInvariant, WaveWidthInvariant, } from "./invariants.js";
27
- /** The rule registry — doc scope 21 rows + ledger scope 2 rows = 23. */
28
+ import { ChangeHistoryHeaderColumnsInvariant, ChangeHistoryLatestMatchesFrontMatterInvariant, ChangeHistoryRowShapeInvariant, ChangeHistoryVersionUniqueInvariant, ContinuityInvariant, CrossDocChainInvariant, CrosslinkInvariant, DomainInvariant, FileExistenceInvariant, FrontMatterVersionInLineageInvariant, HollowInvariant, LedgerLayeringRule, LedgerTaskSetRule, LinkShapeInvariant, ListMarkerInvariant, PhaseDesignSpecIsPhaseSpecInvariant, PhaseIdUniqueInvariant, PresenceInvariant, ResidueInvariant, RowHomeInvariant, SectionOrderInvariant, SectionScopedDomainInvariant, SiblingScanInvariant, SlugRefInvariant, TaskIdUniqueInvariant, WaveWidthInvariant, } from "./invariants.js";
29
+ /** The rule registry — doc scope 24 rows + ledger scope 2 rows = 26. */
28
30
  export const RULE_REGISTRY = [
29
31
  { scope: "doc", id: "presence", docKeys: "all", create: () => new PresenceInvariant() },
30
32
  {
@@ -33,6 +35,24 @@ export const RULE_REGISTRY = [
33
35
  docKeys: "all",
34
36
  create: () => new ChangeHistoryVersionUniqueInvariant(),
35
37
  },
38
+ {
39
+ scope: "doc",
40
+ id: "change-history-row-shape",
41
+ docKeys: "all",
42
+ create: () => new ChangeHistoryRowShapeInvariant(),
43
+ },
44
+ {
45
+ scope: "doc",
46
+ id: "change-history-header-columns",
47
+ docKeys: "all",
48
+ create: () => new ChangeHistoryHeaderColumnsInvariant(),
49
+ },
50
+ {
51
+ scope: "doc",
52
+ id: "change-history-latest-matches-front-matter",
53
+ docKeys: "all",
54
+ create: () => new ChangeHistoryLatestMatchesFrontMatterInvariant(),
55
+ },
36
56
  { scope: "doc", id: "task-id-unique", docKeys: "all", create: () => new TaskIdUniqueInvariant() },
37
57
  {
38
58
  scope: "doc",
@@ -33,6 +33,15 @@ export class PlanTaskBlocksReader {
33
33
  static STEP_LINE = TaskBlockGrammar.STEP_LINE;
34
34
  /** The `— checkable:` clause separator. */
35
35
  static CHECKABLE = TaskBlockGrammar.CHECKABLE;
36
+ /** The placeholder spellings a `Files` value line may carry INSTEAD of a path — the
37
+ * wave's "this task changes no file" declaration: a blank value, the bare `none`
38
+ * and the parenthetical `(none)`. Matched case-insensitively on the trimmed,
39
+ * bullet- and label-stripped remainder, and token by token for a quoted one. */
40
+ static FILE_PLACEHOLDERS = new Set(["", "none", "(none)"]);
41
+ /** The optional line label a `Files` row may carry (`- Modify: …` · `- Test: …`) —
42
+ * stripped so the value's own token is what remains; a line without one keeps its
43
+ * whole remainder. */
44
+ static FILE_ROW_LABEL = /^[A-Za-z][\w ()/.+-]*?:\s+/;
36
45
  /** A dependency id token — the declared `DependsOn id` value domain (the SAME
37
46
  * source string the registry element carries). */
38
47
  static ID_TOKEN = new RegExp(TASK_ID_VALUE_PATTERN);
@@ -62,4 +71,41 @@ export class PlanTaskBlocksReader {
62
71
  section(content, heading) {
63
72
  return MarkdownTree.parse(content).sectionText(heading);
64
73
  }
74
+ /** The path tokens one block's `Files` declaration names — the read face behind the
75
+ * implement criterion's verification-wave cell (P30 §2.4). An empty result is a
76
+ * REAL claim ("this task changes no file"), so the read fails SAFE: an absent
77
+ * section, a blank value, a bare bullet and the `(none)` placeholder declare zero
78
+ * paths, while an unrecognized remainder is returned as one token — text this
79
+ * reader does not understand never reads as "no paths". */
80
+ filePathsOf(block) {
81
+ const field = block.fields.find((entry) => entry.key === "Files");
82
+ if (field === undefined)
83
+ return [];
84
+ const tokens = [];
85
+ for (const line of field.lines) {
86
+ for (const token of PlanTaskBlocksReader.#fileTokensOf(line))
87
+ tokens.push(token);
88
+ }
89
+ return tokens;
90
+ }
91
+ /** One `Files` value line's tokens — the quoted spans when the line quotes its paths
92
+ * (the plan convention), else the whole stripped remainder. The bullet marker is
93
+ * stripped with its trailing whitespace OR at the line's end, so a bare `-` bullet
94
+ * (a row that declares no path at all) reads as an empty value. */
95
+ static #fileTokensOf(line) {
96
+ const remainder = line
97
+ .replace(/^[-*+](?:\s+|$)/, "")
98
+ .replace(PlanTaskBlocksReader.FILE_ROW_LABEL, "")
99
+ .trim();
100
+ if (PlanTaskBlocksReader.FILE_PLACEHOLDERS.has(remainder.toLowerCase()))
101
+ return [];
102
+ const spans = [...remainder.matchAll(/`([^`]+)`/g)]
103
+ .map((match) => (match[1] ?? "").trim())
104
+ .filter((token) => token.length > 0);
105
+ // A line that quotes its paths declares exactly those; a quoted placeholder
106
+ // (`` `(none)` ``) declares none of them.
107
+ if (spans.length === 0)
108
+ return [remainder];
109
+ return spans.filter((token) => !PlanTaskBlocksReader.FILE_PLACEHOLDERS.has(token.toLowerCase()));
110
+ }
65
111
  }
@@ -44,6 +44,7 @@ import { RepoRoot } from "../infra/root.js";
44
44
  import { ENGINE_RUNTIME } from "../infra/runtime.js";
45
45
  import { SlugIndex } from "../infra/slug-index.js";
46
46
  import { Workspace, WorkspaceRoot } from "../infra/workspace.js";
47
+ import { CarrierIntegrity } from "../session/carrier-integrity.js";
47
48
  import { TaskGraph } from "../session/graph.js";
48
49
  import { Ledger, RoundRecords } from "../session/ledger.js";
49
50
  import { PipelineFrontier } from "../session/pipeline.js";
@@ -265,13 +266,12 @@ export class BoardView {
265
266
  }
266
267
  /** One round's findings count — the `findings` array length of the carrier the round
267
268
  * persisted (the judge plane's declared field). Zero when the record carries no
268
- * carrier path or the file is absent/unreadable/unparseable (present facts only,
269
- * never a throw on a read face). */
269
+ * carrier path or the file is absent (present facts only). P31 §2.2 — the read goes
270
+ * through the ONE checked seam: a carrier whose bytes no longer match the recorded
271
+ * digest THROWS (`carrier-mismatch` rides the CLI's blocked channel), never a
272
+ * silent zero. */
270
273
  static #findingsCountOf(record) {
271
- const at = record.carrierPath;
272
- if (at === null)
273
- return 0;
274
- const text = BoardView.#read(at);
274
+ const text = CarrierIntegrity.readFor(record);
275
275
  if (text === null)
276
276
  return 0;
277
277
  try {
package/dist/face/cli.js CHANGED
@@ -60,6 +60,7 @@ import { Workspace, WorkspaceRoot } from "../infra/workspace.js";
60
60
  import { BriefRenderer } from "../render/brief.js";
61
61
  import { IssueBodyRenderer } from "../render/issue-body.js";
62
62
  import { TemplateAssembler } from "../render/templates.js";
63
+ import { CarrierMismatchError } from "../session/carrier-integrity.js";
63
64
  import { DispatchAuthority, } from "../session/dispatch-authority.js";
64
65
  import { TargetFaceTable, targetFaces, } from "../session/faces.js";
65
66
  import { TaskGraph } from "../session/graph.js";
@@ -82,6 +83,11 @@ import { CommandTreeBuilder } from "./projection.js";
82
83
  import { Terminator } from "./termination.js";
83
84
  import { Words } from "./words.js";
84
85
  export { CliLifecycle as HarnessDispatch } from "./lifecycle.js";
86
+ /** The `--recover` double-gap refusal (P30 §2.1③) — NEITHER leg holds: no stale
87
+ * in-flight record stands on this tree, and the line is not at drift ∧ pending-fix.
88
+ * The command dispatches nothing: a flag that silently degrades into an ordinary
89
+ * dispatch is exactly the silent fallback §2.1③ forbids. */
90
+ const RECOVER_NOTHING = "--recover has nothing to take over and nothing to reopen — no stale in-flight record stands on this tree (①), and this line is not at drift ∧ pending-fix (②); nothing was dispatched";
85
91
  /**
86
92
  * The Cli — the command face's parse/run surface over the assembled object graph.
87
93
  * runArgv() parses through the commander program and rejects unknown flags (the
@@ -217,6 +223,15 @@ export class Cli {
217
223
  * invalid argument (incl. the preAction conditional-required) · excess args ·
218
224
  * missing required) → 2, an unexpected error → 1. */
219
225
  #normalizeExit(err) {
226
+ // P31 §2.2 — a carrier whose bytes no longer digest to the recorded value is a
227
+ // hard stop on the CDD_BLOCKED channel (the ordered-rank of every blocked gate),
228
+ // with the existing blocked exit code. The read faces that can meet it (board's
229
+ // `+N` count, the fix criterion's input, the ledger's carrier read) all throw it
230
+ // through their own seam.
231
+ if (err instanceof CarrierMismatchError) {
232
+ this.#io.stderr(`${this.#words.station("blocked")} ${err.message}\n`);
233
+ return 1;
234
+ }
220
235
  if (err instanceof CommanderError) {
221
236
  if (err.code === "commander.help")
222
237
  return err.exitCode === 0 ? 0 : 2;
@@ -516,7 +531,7 @@ export class Cli {
516
531
  // The explicit takeover flag — VOID under --dry-run: the preview face never
517
532
  // acquires, so a takeover there would have no write channel at all. The
518
533
  // preview still judges the same gate, sees the same holder facts, and exits 1.
519
- stealStale: !parsed.dryRun && parsed.args.stealStale === "true",
534
+ recover: !parsed.dryRun && parsed.args.recover === "true",
520
535
  });
521
536
  // The per-invocation batch cursor: the in-memory done set mirrors the on-disk
522
537
  // ledger's closed waves (the C5 closure single face) — NOT a "every non-group
@@ -546,6 +561,20 @@ export class Cli {
546
561
  scene.state.markDone(id);
547
562
  }
548
563
  const expected = verb === "implement" ? "implement" : verb === "fix" ? "fix" : scene.face.product.reviewLead;
564
+ // THE `--recover` judgment (P30 §2.1①–③), at the composition root and BEFORE the
565
+ // dispatch verdict: the takeover lands first, the supersede stamp second and the
566
+ // `N+1` review dispatch third — the order is fixed HERE, never inside `step()`.
567
+ // A STRUCTURE refusal keeps its own face: the recovery legs are skipped, so a dirty
568
+ // tree or a live holder is never displaced by an argument.
569
+ const recovery = !parsed.dryRun &&
570
+ parsed.args.recover === "true" &&
571
+ this.#authority.structureRefusal(preflight) === null
572
+ ? await this.#recoverRun(verb, type, scene, parsed, inflight)
573
+ : null;
574
+ if (recovery !== null && recovery.kind === "blocked") {
575
+ this.#io.stderr(`${this.#words.station("blocked")} ${recovery.message}\n`);
576
+ return 1;
577
+ }
549
578
  // THE dispatch verdict (P27 §2.2) — ONE authority over the three legs, in
550
579
  // priority order: the structure leg (the pre-flight verdict just judged), the
551
580
  // upstream station leg, then this line's own phase. A refusal is ONE verdict —
@@ -615,7 +644,7 @@ export class Cli {
615
644
  if (!parsed.dryRun && type === "wave" && scene.planText !== null)
616
645
  scene.briefPath = this.#gate.renderBrief(scene, parsed);
617
646
  const statuses = [];
618
- const dispatch = this.#dispatchOf(scene, parsed);
647
+ const dispatch = await this.#dispatchOf(scene, parsed, recovery?.harness ?? null);
619
648
  const run = new Lifecycle({
620
649
  face: scene.face,
621
650
  state: scene.state,
@@ -755,10 +784,77 @@ export class Cli {
755
784
  * retired synthetic approval (`() => ({ status: "APPROVED", findings: [] })`)
756
785
  * has no remaining caller: a preview books no round and fabricates no
757
786
  * conclusion. */
758
- #dispatchOf(scene, parsed) {
787
+ async #dispatchOf(scene, parsed, recovered = null) {
759
788
  if (this.#dispatch !== null)
760
789
  return this.#dispatch;
761
- const harness = new CliLifecycle({
790
+ const harness = recovered ?? this.#lifecycleOf(scene, parsed);
791
+ // The abort fold already ran at the composition root's `--recover` judgment
792
+ // (`#recoverRun`) when a harness was handed in; the injected/default face keeps
793
+ // its own fold here, so the takeover always precedes this dispatch's own record.
794
+ if (recovered === null && !parsed.dryRun && parsed.args.recover === "true") {
795
+ await harness.foldAbort();
796
+ }
797
+ return harness.step();
798
+ }
799
+ /** The `--recover` judgment (spec §2.1①–③) — the two legs, judged in order and
800
+ * allowed to stack:
801
+ * ① the ABORT leg — a stale in-flight record is taken over and, when it still
802
+ * names the killed round, folded into the ledger (`foldAbort`);
803
+ * ② the REOPEN leg — `review` on a doc / branch line only, at drift ∧ pending-fix,
804
+ * with no round in flight: the old review is stamped `supersededBy` and the
805
+ * dispatch that follows allocates `N+1`;
806
+ * ③ neither → the double-gap BLOCKED, naming both missing conditions, and no
807
+ * dispatch at all.
808
+ * The ORDER is the ruling (§2.1④): the abort fold first, the stamp second, the
809
+ * `N+1` dispatch third — it lives here, not in `step()`'s internals. `fix --recover`
810
+ * and `implement --recover` take leg ① only (never a reopen), wave lines likewise
811
+ * (their reopen face stays P29's brief-drift). */
812
+ async #recoverRun(verb, type, scene, parsed, inflight) {
813
+ const harness = this.#lifecycleOf(scene, parsed);
814
+ const stale = (await inflight.staleState()) !== null;
815
+ if (stale)
816
+ await harness.foldAbort();
817
+ const reopened = await this.#reopenLeg(verb, type, scene, inflight);
818
+ if (stale || reopened)
819
+ return { kind: "allowed", harness };
820
+ return { kind: "blocked", message: RECOVER_NOTHING };
821
+ }
822
+ /** The reopen leg (spec §2.3) — its three conditions judged here, and the stamp
823
+ * written when all hold: ① `reviewGate` open (the doc drifted), ② a fix still owed
824
+ * (`pendingFix`), ③ no round in flight (a live holder was refused upstream; a stale
825
+ * one was already taken over). Trigger face pinned: `review` on a doc / branch line
826
+ * ONLY — `fix` / `implement` and the wave line never reopen. Returns whether the
827
+ * supersede stamp landed. */
828
+ async #reopenLeg(verb, type, scene, inflight) {
829
+ if (verb !== "review")
830
+ return false;
831
+ if (type !== "branch" && !TargetFaceTable.isDocShape(type))
832
+ return false;
833
+ const identity = this.#gate.lineIdentity(scene);
834
+ if (identity.key === null || identity.doc === null)
835
+ return false;
836
+ const state = await inflight.inspect();
837
+ if (state.kind !== "absent" || existsSync(inflight.lockPath()))
838
+ return false;
839
+ const ledger = scene.ledger;
840
+ if (ledger.reviewGate(identity.key, identity.doc, type).kind !== "open")
841
+ return false;
842
+ if (!ledger.pendingFix(identity.key, type))
843
+ return false;
844
+ const completed = ledger.completedCycles(identity.key, "review", type);
845
+ if (completed.length === 0)
846
+ return false;
847
+ // The next review cycle is the latest completed review's + 1 — allocated BEFORE
848
+ // the stamp lands (the spec's fixed action order), and it is exactly the cycle the
849
+ // following dispatch allocates (the register's cycle count is unchanged by a stamp).
850
+ const latest = Math.max(...completed);
851
+ return ledger.supersedeReview(identity.key, type, latest, latest + 1);
852
+ }
853
+ /** The invocation's lifecycle harness — the production dispatch face, held by the
854
+ * composition root so the abort fold can ride the SAME instance that dispatches
855
+ * (the takeover precedes the stamp, spec §2.1④). */
856
+ #lifecycleOf(scene, parsed) {
857
+ return new CliLifecycle({
762
858
  env: process.env,
763
859
  sync: this.#sync,
764
860
  template: this.#template,
@@ -774,11 +870,10 @@ export class Cli {
774
870
  overallLink: scene.overallLink,
775
871
  },
776
872
  reviews: parsed.paths.reviews,
777
- // The explicit takeover flag (`--steal-stale`): the ONLY path that displaces a
873
+ // The explicit takeover flag (`--recover`): the ONLY path that displaces a
778
874
  // standing in-flight record — and only when its holder is dead.
779
- stealStale: parsed.args.stealStale === "true",
875
+ recover: parsed.args.recover === "true",
780
876
  });
781
- return harness.step();
782
877
  }
783
878
  /** The branch scope anchor (BASE_BRANCH) — the base artifact's branch name read
784
879
  * from the line's own workspace (`base.json`, the same `base get` source the CLI
@@ -60,8 +60,8 @@ export const ARGV_CHANNEL = {
60
60
  help: "the base artifact's source channel",
61
61
  },
62
62
  force: { flag: "--force", type: "bool", help: "override the existing base artifact" },
63
- stealStale: {
64
- flag: "--steal-stale",
63
+ recover: {
64
+ flag: "--recover",
65
65
  type: "bool",
66
66
  help: "take over a standing in-flight record whose holder is dead (the only takeover path)",
67
67
  },
@@ -146,11 +146,7 @@ export const CLI_COMMANDS = [
146
146
  name: "implement",
147
147
  description: `run the task implement phase — at most ${MAX_TASKS_PER_WAVE} tasks per wave`,
148
148
  example: `cdd implement --tasks 1,2 --plan ${ENGINE_DOC_ROOTS.plans}/p3.md`,
149
- keys: [
150
- { key: "tasks", required: true },
151
- { key: "plan", required: true },
152
- { key: "stealStale" },
153
- ],
149
+ keys: [{ key: "tasks", required: true }, { key: "plan", required: true }, { key: "recover" }],
154
150
  },
155
151
  {
156
152
  name: "review",
@@ -162,7 +158,7 @@ export const CLI_COMMANDS = [
162
158
  { key: "plan" },
163
159
  { key: "spec" },
164
160
  { key: "round" },
165
- { key: "stealStale" },
161
+ { key: "recover" },
166
162
  ],
167
163
  },
168
164
  {
@@ -175,7 +171,7 @@ export const CLI_COMMANDS = [
175
171
  { key: "reviews" },
176
172
  { key: "spec" },
177
173
  { key: "plan" },
178
- { key: "stealStale" },
174
+ { key: "recover" },
179
175
  ],
180
176
  },
181
177
  {