@oscaner-skills/cdd-engine 2.0.0 → 3.0.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.
Files changed (84) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/package.json +4 -3
  4. package/src-next/__tests__/dead-decl.guard.test.ts +39 -0
  5. package/src-next/__tests__/floor.guard.test.ts +69 -0
  6. package/src-next/__tests__/issue-body.guard.test.ts +66 -0
  7. package/src-next/__tests__/phase-suffix.guard.test.ts +72 -0
  8. package/src-next/__tests__/smoke.integration.test.ts +60 -77
  9. package/src-next/__tests__/support/strip-comments.ts +99 -0
  10. package/src-next/__tests__/zero-dep.test.ts +6 -46
  11. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +39 -21
  12. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +40 -28
  13. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +40 -23
  14. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +38 -21
  15. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +21 -6
  16. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +22 -12
  17. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +23 -8
  18. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +21 -6
  19. package/src-next/contract/__tests__/declare.test.ts +251 -12
  20. package/src-next/contract/__tests__/doc.test.ts +214 -45
  21. package/src-next/contract/__tests__/dockey.guard.test.ts +58 -0
  22. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +81 -0
  23. package/src-next/contract/__tests__/frontmatter.test.ts +164 -0
  24. package/src-next/contract/__tests__/judge.test.ts +410 -172
  25. package/src-next/contract/__tests__/lint.test.ts +49 -39
  26. package/src-next/contract/__tests__/project.test.ts +60 -19
  27. package/src-next/contract/__tests__/structure-pin.test.ts +186 -0
  28. package/src-next/contract/declare.ts +179 -91
  29. package/src-next/contract/doc.ts +227 -164
  30. package/src-next/contract/frontmatter.ts +233 -0
  31. package/src-next/contract/home-extractors.ts +397 -0
  32. package/src-next/contract/invariants.ts +214 -69
  33. package/src-next/contract/judge.ts +28 -19
  34. package/src-next/contract/lint.ts +5 -41
  35. package/src-next/contract/project.ts +103 -43
  36. package/src-next/contract/skill-anatomy.ts +39 -11
  37. package/src-next/face/__tests__/board-view.test.ts +318 -115
  38. package/src-next/face/__tests__/capsule.test.ts +49 -25
  39. package/src-next/face/__tests__/channel-closure.guard.test.ts +28 -1
  40. package/src-next/face/__tests__/cli.test.ts +1091 -837
  41. package/src-next/face/__tests__/face.test.ts +5 -5
  42. package/src-next/face/__tests__/install-rows.guard.test.ts +58 -0
  43. package/src-next/face/__tests__/preview.test.ts +374 -0
  44. package/src-next/face/__tests__/projection.test.ts +5 -3
  45. package/src-next/face/__tests__/repo-root.guard.test.ts +120 -0
  46. package/src-next/face/__tests__/termination.test.ts +650 -0
  47. package/src-next/face/artifacts.ts +90 -37
  48. package/src-next/face/board-view.ts +128 -138
  49. package/src-next/face/capsule.ts +30 -16
  50. package/src-next/face/cli.ts +306 -97
  51. package/src-next/face/declare.ts +15 -18
  52. package/src-next/face/gate.ts +19 -18
  53. package/src-next/face/host.ts +6 -30
  54. package/src-next/face/lifecycle.ts +213 -188
  55. package/src-next/face/preview.ts +151 -0
  56. package/src-next/face/projection.ts +4 -1
  57. package/src-next/face/route-render.ts +39 -14
  58. package/src-next/face/termination.ts +573 -0
  59. package/src-next/face/words.ts +20 -2
  60. package/src-next/infra/__tests__/infra.test.ts +49 -3
  61. package/src-next/infra/__tests__/root.test.ts +56 -0
  62. package/src-next/infra/doc-roots.ts +29 -0
  63. package/src-next/infra/root.ts +73 -0
  64. package/src-next/infra/runtime.ts +12 -65
  65. package/src-next/infra/workspace.ts +95 -5
  66. package/src-next/render/__tests__/render.test.ts +92 -41
  67. package/src-next/render/__tests__/skeleton.test.ts +282 -64
  68. package/src-next/render/issue-body.ts +5 -2
  69. package/src-next/render/skeleton.ts +155 -90
  70. package/src-next/render/templates.ts +51 -56
  71. package/src-next/session/__tests__/graph.test.ts +11 -4
  72. package/src-next/session/__tests__/ledger.test.ts +3 -2
  73. package/src-next/session/__tests__/next.test.ts +100 -8
  74. package/src-next/session/__tests__/preflight.test.ts +79 -25
  75. package/src-next/session/__tests__/round-naming.test.ts +142 -0
  76. package/src-next/session/__tests__/run.test.ts +140 -128
  77. package/src-next/session/__tests__/wave.test.ts +11 -4
  78. package/src-next/session/ledger.ts +96 -24
  79. package/src-next/session/next.ts +116 -15
  80. package/src-next/session/preflight.ts +41 -10
  81. package/src-next/session/round-naming.ts +84 -0
  82. package/src-next/session/run.ts +24 -20
  83. package/templates/report/issue-body.json +0 -46
  84. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
@@ -43,17 +43,21 @@
43
43
  // Module-level exports are types / constant data / classes — zero behavior-carrying
44
44
  // bare functions (the composition root is the Cli class's static create factory).
45
45
 
46
- import { readFileSync } from "node:fs";
46
+ import { existsSync, readFileSync } from "node:fs";
47
+ import path from "node:path";
47
48
  import process from "node:process";
48
49
  import { type Command, CommanderError } from "commander";
49
50
  import { declaredRegistries } from "../contract/declare.ts";
50
51
  import { PlanDocType } from "../contract/doc.ts";
52
+ import { FrontMatterExtractor } from "../contract/frontmatter.ts";
53
+ import { FileExistenceInvariant } from "../contract/invariants.ts";
51
54
  import { Contract } from "../contract/judge.ts";
52
55
  import type { DocKey } from "../contract/project.ts";
53
56
  import { Projector } from "../contract/project.ts";
54
57
  import { Translator } from "../contract/translate.ts";
55
58
  import { ConfigLoader } from "../infra/config.ts";
56
59
  import { GitClient } from "../infra/git.ts";
60
+ import { type RepoPath, RepoRoot } from "../infra/root.ts";
57
61
  import { Workspace, WorkspaceRoot } from "../infra/workspace.ts";
58
62
  import { BriefRenderer } from "../render/brief.ts";
59
63
  import { IssueBodyRenderer } from "../render/issue-body.ts";
@@ -75,22 +79,18 @@ import { ARGV_CHANNEL, type CliLeafName, type CliVerb } from "./declare.ts";
75
79
  import { CliGate } from "./gate.ts";
76
80
  import { GraphView } from "./graph-view.ts";
77
81
  import { HostDetect } from "./host.ts";
78
- import {
79
- type CliIo,
80
- CliLifecycle,
81
- type DispatchScene,
82
- type SyncProcess,
83
- SyncRunner,
84
- } from "./lifecycle.ts";
82
+ import { type CliIo, CliLifecycle, type DispatchScene } from "./lifecycle.ts";
83
+ import { Preview } from "./preview.ts";
85
84
  import { CommandTreeBuilder } from "./projection.ts";
85
+ import { type ChildRunner, Terminator } from "./termination.ts";
86
86
  import { Words } from "./words.ts";
87
87
 
88
88
  // ---------------------------------------------------------------------------
89
89
  // the re-exported seams + the dispatch production default — the split contract's
90
90
  // lifecycle face owns the dispatch/readback plane (face/lifecycle.ts) and the
91
91
  // shared seams it rides; the composition root re-exports them here unchanged so
92
- // the module's public surface never drifts (CliIo · SyncProcess · SyncRunner ·
93
- // ProcessEnvLike · DispatchScene · BaseArtifact · HarnessDispatch).
92
+ // the module's public surface never drifts (CliIo · ChildRunner · ProcessEnvLike ·
93
+ // DispatchScene · BaseArtifact · HarnessDispatch).
94
94
  // ---------------------------------------------------------------------------
95
95
 
96
96
  export type { BaseArtifact } from "./artifacts.ts";
@@ -98,15 +98,13 @@ export type {
98
98
  CliIo,
99
99
  DispatchScene,
100
100
  ProcessEnvLike,
101
- SyncProcess,
102
- } from "./lifecycle.ts";
103
- export {
104
- CliLifecycle as HarnessDispatch,
105
- SyncRunner,
106
101
  } from "./lifecycle.ts";
102
+ export { CliLifecycle as HarnessDispatch } from "./lifecycle.ts";
103
+ export type { ChildOutcome, ChildRun, ChildRunner } from "./termination.ts";
107
104
  /** The composition options — every collaborator injectable (tests substitute the
108
- * hermetic ones: io / dispatch / repoRoot / stdin); the production defaults wire
109
- * the living process. */
105
+ * hermetic ones: io / dispatch / stdin); the production defaults wire the living
106
+ * process. The repo root is NEVER injectable (T2): it derives from the ONE
107
+ * conversion point (the git top level of the working directory — §2.4/§2.6). */
110
108
  export interface CliOptions {
111
109
  io?: CliIo;
112
110
  config?: ConfigLoader;
@@ -114,9 +112,7 @@ export interface CliOptions {
114
112
  words?: Words;
115
113
  translator?: Translator;
116
114
  git?: GitClient;
117
- sync?: SyncProcess;
118
- cwd?: string;
119
- repoRoot?: string;
115
+ sync?: ChildRunner;
120
116
  dryRun?: boolean;
121
117
  dispatch?: DispatchStep | null;
122
118
  preflight?: PreFlight;
@@ -130,9 +126,23 @@ export interface WorkScene extends DispatchScene {
130
126
  planText: string | null;
131
127
  type: TargetType;
132
128
  face: TargetFace;
133
- target: { kind: "branch" } | { kind: "doc"; doc: string } | null;
129
+ target: { kind: "branch" } | { kind: "plan"; doc: string } | { kind: "spec"; doc: string } | null;
134
130
  state: RunState;
135
131
  router: NextStepRouter;
132
+ /** The plan's `spec:` front-matter link target (plan docs only) — the plan-review
133
+ * round context's spec anchor; null off the plan face. */
134
+ specLink: string | null;
135
+ }
136
+
137
+ /** The path-typed argv values (T3 §2.3) — split out of the generic `args` record
138
+ * so the funnel's normalized `RepoPath` brand reaches the scene/read faces with
139
+ * NO downcast (branch-review-1 F7). The funnel is the ONE landing: before it runs
140
+ * the three fields are null; after it they carry the branded repoRoot-relative
141
+ * value (or null when the flag was absent). */
142
+ export interface PathArgs {
143
+ plan: RepoPath | null;
144
+ spec: RepoPath | null;
145
+ reviews: RepoPath | null;
136
146
  }
137
147
 
138
148
  /** The thin-shell → run-body input — the .action shell maps commander's parsed
@@ -145,11 +155,14 @@ export interface WorkScene extends DispatchScene {
145
155
  export interface RunInput {
146
156
  /** The nested leaf word (schema get|gen · base set|get) — null on the verbs. */
147
157
  leaf: CliLeafName | null;
148
- /** The declared keys' values — normalized strings (undefined-flagged keys absent). */
158
+ /** The declared keys' values — normalized strings (undefined-flagged keys absent;
159
+ * the path-typed keys are split into `paths` by the funnel). */
149
160
  args: Record<string, string>;
161
+ /** The path-typed argv values — the funnel's branded `RepoPath` landing (F7). */
162
+ paths: PathArgs;
150
163
  /** The positional values (the schema <type> — the parseTypeKey-normalized key). */
151
164
  positionals: readonly string[];
152
- /** The invocation's synthetic-dispatch scope (the --dry-run program flag). */
165
+ /** The invocation's read-only preview scope (the --dry-run program flag). */
153
166
  dryRun: boolean;
154
167
  }
155
168
 
@@ -166,9 +179,7 @@ export class Cli {
166
179
  readonly #projector: Projector;
167
180
  readonly #words: Words;
168
181
  readonly #git: GitClient;
169
- readonly #sync: SyncProcess;
170
- readonly #cwd: string;
171
- readonly #repoRoot: string | null;
182
+ readonly #sync: ChildRunner;
172
183
  readonly #dryRun: boolean;
173
184
  readonly #dispatch: DispatchStep | null;
174
185
  readonly #template: TemplateAssembler;
@@ -213,9 +224,7 @@ export class Cli {
213
224
  this.#wireTreeOutput(this.#program);
214
225
  this.#wireActions();
215
226
  this.#git = opts.git ?? new GitClient();
216
- this.#sync = opts.sync ?? new SyncRunner();
217
- this.#cwd = opts.cwd ?? process.cwd();
218
- this.#repoRoot = opts.repoRoot ?? null;
227
+ this.#sync = opts.sync ?? new Terminator();
219
228
  this.#dryRun = opts.dryRun ?? false;
220
229
  this.#dispatch = opts.dispatch ?? null;
221
230
  this.#template = opts.template ?? new TemplateAssembler();
@@ -334,7 +343,8 @@ export class Cli {
334
343
  leafNode("base", "get").action(async (_opts: unknown, command: Command) => {
335
344
  this.#exitCode = await this.#runBase(command, this.#runInput("get", command));
336
345
  });
337
- leafNode("issue", "render").action(async () => {
346
+ leafNode("issue", "render").action(async (_opts: unknown, command: Command) => {
347
+ this.#assertDryRunScope(command, this.#dryRunOf(command));
338
348
  this.#exitCode = this.#artifacts.runIssue();
339
349
  });
340
350
  // the board observability command — a pure read (no preflight gate)
@@ -349,13 +359,15 @@ export class Cli {
349
359
  * and renders the phase/program board + the `next:` derivation to stdout. A
350
360
  * missing slug is a usage error (exit 2, commander's own byte); a slug matching
351
361
  * nothing on disk renders the not-found face and exits 2; a present doc line
352
- * carrying no `- **Doc type**:` declaration renders its BLOCKED marker and exits 2
362
+ * carrying no `doc-type:` key renders its BLOCKED marker and exits 2
353
363
  * (spec §12 · D34). The host is detected once for the pipeline-entry ref render
354
364
  * (REFS[ref][host], the same judgment the capsule injects — never hard-coded). */
355
365
  async #runBoard(node: Command, parsed: RunInput): Promise<number> {
366
+ this.#assertDryRunScope(node, parsed.dryRun);
356
367
  const slug = parsed.positionals[0];
357
368
  if (slug === undefined) this.#usage(node, "cdd board: missing <slug>");
358
- const repoRoot = await this.#repoRootOf(parsed);
369
+ const repoRoot = await this.#rootOf();
370
+ if (repoRoot === null) return 1;
359
371
  if (!BoardView.hasNode(slug, repoRoot)) {
360
372
  this.#io.stderr(`cdd board: no docs match slug ${slug}\n`);
361
373
  return 2;
@@ -384,11 +396,37 @@ export class Cli {
384
396
  return {
385
397
  leaf,
386
398
  args,
399
+ // The path-typed values land empty — the funnel (`#funnel`) is the ONE
400
+ // normalization site that fills them with the branded repoRoot-relative form.
401
+ paths: { plan: null, spec: null, reviews: null },
387
402
  positionals: command.processedArgs as string[],
388
- dryRun: this.#dryRun || globals.dryRun === true,
403
+ dryRun: this.#dryRunOf(command),
389
404
  };
390
405
  }
391
406
 
407
+ /** The invocation's `--dry-run` scope — the constructor flag OR the program-scope
408
+ * flag (the flag is declared on the program node, so a leaf's own opts would miss
409
+ * it; `optsWithGlobals` merges the parent chain). The ONE derivation the run input
410
+ * and the scope guard read — never a second copy of the merge rule. */
411
+ #dryRunOf(command: Command): boolean {
412
+ const globals = command.optsWithGlobals() as Record<string, unknown>;
413
+ return this.#dryRun || globals.dryRun === true;
414
+ }
415
+
416
+ /** The `--dry-run` scope guard (P11 T5 · §3.5) — the preview semantics belong to
417
+ * the three work verbs alone. A pure command carrying the program flag is a usage
418
+ * rejection (exit 2), never a silently ignored flag: a no-op flag the consumer has
419
+ * to remember to skip is a mind-share defect, not a convenience. The usage byte is
420
+ * the owning node's commander-native usage line (the same `#usage` face every run
421
+ * body's rejection rides). */
422
+ #assertDryRunScope(node: Command, dryRun: boolean): void {
423
+ if (!dryRun) return;
424
+ this.#usage(
425
+ node,
426
+ "--dry-run previews the next dispatch step and its expected artifacts — it applies to implement / review / fix only",
427
+ );
428
+ }
429
+
392
430
  /** Configure every node's output into the injected io (commander writes its
393
431
  * help/error bytes through the node that produced them — a subcommand's help
394
432
  * uses the subcommand's own output configuration, so the whole tree must be
@@ -407,12 +445,20 @@ export class Cli {
407
445
 
408
446
  /** One work command's run — assemble the scene, advance the requested phase (the
409
447
  * lifecycle's single dispatch step per frame), render the capsule lines. */
410
- async #runWork(verb: CliVerb, node: Command, parsed: RunInput): Promise<number> {
411
- const type = (parsed.args.type ?? "wave") as TargetType;
412
- if (type === "wave" && parsed.args.tasks === undefined) {
448
+ async #runWork(verb: CliVerb, node: Command, raw: RunInput): Promise<number> {
449
+ const type = (raw.args.type ?? "wave") as TargetType;
450
+ if (type === "wave" && raw.args.tasks === undefined) {
413
451
  this.#usage(node, `cdd ${verb} --type wave: missing required --tasks <n|n,n,…>`);
414
452
  }
415
- const scene = await this.#sceneOf(verb, type, node, parsed);
453
+ // The repo root (the ONE conversion point, T2) + the input funnel (T3 §2.3) run
454
+ // FIRST — before the scene or any downstream face reads a path arg, so the whole
455
+ // run (scene + ledger + dispatch `--reviews`) speaks ONE normalized argv shape.
456
+ const repoRoot = await this.#rootOf();
457
+ if (repoRoot === null) return 1;
458
+ const root = new RepoRoot(repoRoot);
459
+ const parsed = this.#funnel(root, raw);
460
+ const scene = await this.#sceneOf(verb, type, node, root, parsed);
461
+ if (scene === null) return 1;
416
462
 
417
463
  // THE pre-flight seam (P4.1 T1 · design §1): the single dispatch gate —
418
464
  // tree-clean → graph → wave → doc-contract — ONE call, the whole sequence
@@ -420,8 +466,18 @@ export class Cli {
420
466
  // + the verdict render (zero re-implemented gate here). A refused verdict
421
467
  // returns before any brief/lifecycle: no child dispatch ever runs. The
422
468
  // dirty-tree / doc-contract refusals ride the CDD_BLOCKED channel; the
423
- // graph / wave refusals keep the pre-existing refusal face.
424
- const docPath = scene.target !== null && scene.target.kind === "doc" ? scene.target.doc : "";
469
+ // graph / wave refusals keep the pre-existing refusal face. The doc-face read
470
+ // path is the repoRoot-relative branded `RepoPath` (T4 §2.2 — a bare `string`
471
+ // never reaches the read faces `BoardView.readDocType`/`PreFlightDoc.path`; the
472
+ // CLI feeds the funnel-shaped relative value, each read face erasing to the
473
+ // absolute syscall form through its OWN `RepoRoot`). Both branches yield the
474
+ // brand through the ONE conversion entry (`relativize` of the doc path; the
475
+ // empty path relativizes to the empty `RepoPath`) — no cast (F3).
476
+ const docRel = root.relativize(
477
+ scene.target !== null && (scene.target.kind === "plan" || scene.target.kind === "spec")
478
+ ? scene.target.doc
479
+ : "",
480
+ );
425
481
  const preflight = await this.#preflight.vet({
426
482
  verb: verb as "implement" | "review" | "fix",
427
483
  type,
@@ -433,11 +489,11 @@ export class Cli {
433
489
  type === "spec" || type === "plan"
434
490
  ? {
435
491
  // The ONE declaration reading face (spec §12 · D34) — both the spec and
436
- // the plan dispatch read the doc's `- **Doc type**:` header declaration;
437
- // a declaration-less doc reads null and the seam BLOCKs (zero command-type
492
+ // the plan dispatch read the doc's front-matter `doc-type:` key;
493
+ // a key-less doc reads null and the seam BLOCKs (zero command-type
438
494
  // carve-out, zero filename-suffix fallback).
439
- docKey: BoardView.readDocType(docPath),
440
- path: docPath,
495
+ docKey: BoardView.readDocType(root, docRel),
496
+ path: docRel,
441
497
  }
442
498
  : null,
443
499
  });
@@ -446,11 +502,26 @@ export class Cli {
446
502
  return 1;
447
503
  }
448
504
 
505
+ // The real run's first write point (P11 · §4.2): the workspace — and the
506
+ // namespace's `.gitignore` keep-out marker — is built HERE, after the
507
+ // pre-flight verdict and before the brief render / the child dispatch, for
508
+ // EVERY face (wave / spec / plan / branch). Scene assembly no longer
509
+ // pre-creates it, so a read-only command leaves `.kairos/` absent while a
510
+ // real dispatch always lands in an existing workspace (the child's
511
+ // OUTPUT_REPORT / OUTPUT_HANDOFF targets, and the keep-out marker published
512
+ // before the child can dirty the tree). `Workspace.writeJson` keeps its own
513
+ // internal ensure; `CliGate#renderBrief` no longer ensures. The `--dry-run`
514
+ // preview never reaches it — the preview path returns before any write
515
+ // (P11 T5 · §3.2: a preview is a pure read).
516
+ if (!parsed.dryRun) scene.workspace.ensure();
517
+
449
518
  // The unconditional extract (§4.1): every wave-face dispatch re-renders the
450
519
  // brief from the CURRENT plan text — implement, review and fix alike (a
451
520
  // mid-run plan amendment reflects into the next dispatch; no "exists → leave
452
521
  // it" reuse). The doc/branch faces carry no wave brief (planText is null there).
453
- if (type === "wave" && scene.planText !== null)
522
+ // The preview skips it — the brief is a WRITE (`Workspace#writeText`), and the
523
+ // preview names the same path through RoundNaming instead of rendering it.
524
+ if (!parsed.dryRun && type === "wave" && scene.planText !== null)
454
525
  scene.briefPath = this.#gate.renderBrief(scene, parsed);
455
526
  const expected =
456
527
  verb === "implement" ? "implement" : verb === "fix" ? "fix" : scene.face.product.reviewLead;
@@ -493,8 +564,8 @@ export class Cli {
493
564
  // structurally never passed to the child (the lifecycle's hard "child zero-dispatch"
494
565
  // guarantee; the CLI already returned above when the seam refused).
495
566
  preflight: { gate: () => (preflight.ok ? null : preflight) },
496
- dispatch: (frame) => {
497
- const outcome = dispatch(frame);
567
+ dispatch: async (frame) => {
568
+ const outcome = await dispatch(frame);
498
569
  statuses.push(outcome.status ?? null);
499
570
  return outcome;
500
571
  },
@@ -503,7 +574,7 @@ export class Cli {
503
574
  this.#words,
504
575
  ARGV_CHANNEL,
505
576
  HostDetect.detect(process.env),
506
- scene.workspace.root.repoRoot,
577
+ scene.workspace.root.basis,
507
578
  ),
508
579
  planPath: scene.planPath,
509
580
  });
@@ -551,7 +622,16 @@ export class Cli {
551
622
  }
552
623
  break;
553
624
  }
554
- const step = run.advance();
625
+ // The `--dry-run` preview (P11 T5 · §3.3) — the SAME frame the real run would
626
+ // dispatch, rendered as the five-row forecast instead of dispatched: the
627
+ // frontier read above is the preview's single step source (zero second
628
+ // derivation), and the early return means no write point below ever runs
629
+ // (`renderBrief` skipped above, `#bookkeep`/`#reject` never reached).
630
+ if (parsed.dryRun) {
631
+ for (const line of new Preview({ scene }).render(verb, frame)) this.#io.stdout(`${line}\n`);
632
+ return 0;
633
+ }
634
+ const step = await run.advance();
555
635
  if (step === null) break;
556
636
  // The dispatch-entry gate's refusal (the lifecycle's hard child zero-dispatch wiring —
557
637
  // structurally unreachable here: the seam already returned above on refusal).
@@ -571,6 +651,9 @@ export class Cli {
571
651
  // next was already consumed). The ledger-mirrored cursor above + markTerminal
572
652
  // together keep one wave phase per invocation.
573
653
  if (lastStatus === "BLOCKED" || lastStatus === "TIMEOUT") {
654
+ // The timeout counter's call site (§4.2): a TIMEOUT round lands, the count
655
+ // goes up by one — the counter's only production writer.
656
+ if (lastStatus === "TIMEOUT") scene.ledger.incrementTimeoutCount();
574
657
  for (const line of latest) this.#io.stdout(`${line}\n`);
575
658
  return 1;
576
659
  }
@@ -593,16 +676,17 @@ export class Cli {
593
676
  return 0;
594
677
  }
595
678
 
596
- /** The dispatch seam — the injected override, else the dry-run synthetic approval,
597
- * else the harness production default. */
679
+ /** The dispatch seam — the injected override, else the harness production default.
680
+ * The call itself is unconditional (the caller resolves the step before the
681
+ * preview branch), but under `--dry-run` the preview path returns before the
682
+ * step is INVOKED — `dispatch(frame)` is never called (P11 T5 · §3.2) — so the
683
+ * retired synthetic approval (`() => ({ status: "APPROVED", findings: [] })`)
684
+ * has no remaining caller: a preview books no round and fabricates no
685
+ * conclusion. */
598
686
  #dispatchOf(scene: WorkScene, parsed: RunInput): DispatchStep {
599
687
  if (this.#dispatch !== null) return this.#dispatch;
600
- if (parsed.dryRun || this.#dryRun) {
601
- return () => ({ status: "APPROVED", findings: [] });
602
- }
603
688
  const harness = new CliLifecycle({
604
689
  env: process.env,
605
- cwd: this.#cwd,
606
690
  sync: this.#sync,
607
691
  config: this.#config,
608
692
  template: this.#template,
@@ -613,8 +697,9 @@ export class Cli {
613
697
  planPath: scene.planPath,
614
698
  briefPath: scene.briefPath,
615
699
  baseBranch: this.#baseBranchOf(scene),
700
+ specLink: scene.specLink,
616
701
  },
617
- findings: parsed.args.findings ?? null,
702
+ reviews: parsed.paths.reviews,
618
703
  });
619
704
  return harness.step();
620
705
  }
@@ -659,8 +744,12 @@ export class Cli {
659
744
  if (verdict.gate === "wave" && verdict.reason === "split" && scene.planText !== null) {
660
745
  const graph = new TaskGraph(new PlanDocType("plan").parse(scene.planText.split("\n")));
661
746
  const closed = scene.ledger.closedWaves();
747
+ // The graph title's plan path renders repoRoot-relative (D47 · the ONE shape;
748
+ // `scene.planPath` is argv-origin) — normalized through the scene's OWN basis
749
+ // value object (F2: never a per-call re-wrap).
750
+ const titlePlan = scene.workspace.root.basis.relativize(scene.planPath ?? "");
662
751
  for (const line of this.#graphView
663
- .render(graph.report(closed), `graph: ${scene.planPath ?? ""}`)
752
+ .render(graph.report(closed), `graph: ${titlePlan}`)
664
753
  .split("\n"))
665
754
  this.#io.stderr(` ${line}\n`);
666
755
  }
@@ -672,60 +761,93 @@ export class Cli {
672
761
 
673
762
  /** Assemble one work command's scene: the workspace (repo root + the plan/spec
674
763
  * slug), the ledger, the run state (TaskGraph from the plan parse for the task
675
- * face, the empty single-target state otherwise), the fixed target. */
764
+ * face, the empty single-target state otherwise), the fixed target. The repo root
765
+ * is derived at the ONE conversion point (T2) — a cwd outside a git repo returns
766
+ * null, which the caller turns into the BLOCKED exit (§2.6). The path-typed argv
767
+ * values ride the input funnel (T3 · `#funnel`) so the scene consumes canonical
768
+ * repoRoot-relative `RepoPath`s. */
676
769
  async #sceneOf(
677
770
  verb: CliVerb,
678
771
  type: TargetType,
679
772
  node: Command,
773
+ root: RepoRoot,
680
774
  parsed: RunInput,
681
- ): Promise<WorkScene> {
775
+ ): Promise<WorkScene | null> {
682
776
  const config = this.#config;
683
777
  const face = targetFaces[type];
684
- const repoRoot = await this.#repoRootOf(parsed);
685
- const root = new WorkspaceRoot(repoRoot, config.handoffNamespace().workspaceRoot);
686
- const planPath = parsed.args.plan ?? null;
687
- const specPath = parsed.args.spec ?? null;
778
+ const repoRoot = root.absolute;
779
+ const rootPath = new WorkspaceRoot(repoRoot, config.handoffNamespace().workspaceRoot);
780
+ // The argv paths ride the ONE funnel (T3 §2.3): the READ faces consume the branded
781
+ // `RepoPath` (`parsed.paths`), while the scene's own `planPath`/`target.doc` — the
782
+ // facts the ledger persists and the syscalls read — are the value object's `resolve`
783
+ // erasure (the absolute syscall form; their persisted shape is T4's face). Both
784
+ // derive from the same funnel, so there is zero second normalization — the brand
785
+ // reaches here with NO downcast (F7).
786
+ const planRel = parsed.paths.plan;
787
+ const planPath = planRel === null ? null : root.resolve(planRel);
788
+ const specRel = parsed.paths.spec;
789
+ const specPath = specRel === null ? null : root.resolve(specRel);
688
790
 
689
791
  let slug: string;
690
792
  let planText: string | null = null;
793
+ let specLink: string | null = null;
691
794
  let target: WorkScene["target"] = null;
692
795
  switch (type) {
693
796
  case "wave": {
694
- if (planPath === null)
797
+ if (planPath === null || planRel === null)
695
798
  this.#usage(node, `cdd ${verb} --type wave: missing required --plan <path>`);
696
799
  slug = Workspace.slugFromDoc(planPath);
697
- planText = this.#artifacts.readText(node, planPath);
800
+ planText = this.#artifacts.readText(node, root, planRel);
698
801
  break;
699
802
  }
700
803
  case "spec": {
701
804
  if (specPath === null)
702
805
  this.#usage(node, `cdd ${verb} --type spec: missing required --spec <path>`);
703
806
  slug = Workspace.slugFromDoc(specPath);
704
- target = { kind: "doc", doc: specPath };
705
- break;
706
- }
707
- case "plan": {
708
- if (planPath === null)
709
- this.#usage(node, `cdd ${verb} --type plan: missing required --plan <path>`);
710
- slug = Workspace.slugFromDoc(planPath);
711
- planText = this.#artifacts.readText(node, planPath);
712
- target = { kind: "doc", doc: planPath };
807
+ target = { kind: "spec", doc: specPath };
713
808
  break;
714
809
  }
810
+ case "plan":
811
+ // fallthrough to the shared plan-sourced derivation below
715
812
  case "branch": {
716
- // The branch line carries no commit identity: the audit target is the
717
- // branch itself, its workspace identity is the plan path (a required
718
- // fact — the branch review/fix faces carry `--plan`), and the review's
719
- // scope anchor (BASE_BRANCH) is engine-injected from the base artifact.
720
- if (planPath === null)
721
- this.#usage(node, `cdd ${verb} --type branch: missing required --plan <path>`);
813
+ // The plan-doc seam (shared by the plan + branch lines): the target plan
814
+ // must exist (a required fact for both — the branch review/fix faces carry
815
+ // `--plan`), its text is read ONCE, and the plan's design-spec reference
816
+ // (the `spec:` front-matter key — the §2.2 delivery seam: the ONE head-
817
+ // REQUIRED parse call site) is derived from that text as the round context's
818
+ // extra read input (no second file read). Rebased to repoRoot-relative
819
+ // (D46 · T3): the raw header form is markdown link-space (relative to the
820
+ // plan's own dir), so it is first resolved to an absolute path, then routed
821
+ // through the ONE value object (`RepoRoot.relativize`) — every round-context
822
+ // path token speaks ONE basis (the child is spawned at cwd = repoRoot). The
823
+ // plan review judges the plan doc; the branch line carries no commit identity
824
+ // (the audit target is the branch itself, its workspace identity is the plan
825
+ // path, and the review's scope anchor BASE_BRANCH is engine-injected from the
826
+ // base artifact) — both faces carry the plan + its spec anchor.
827
+ if (planPath === null || planRel === null)
828
+ this.#usage(node, `cdd ${verb} --type ${type}: missing required --plan <path>`);
722
829
  slug = Workspace.slugFromDoc(planPath);
723
- target = { kind: "branch" };
830
+ planText = this.#artifacts.readText(node, root, planRel);
831
+ const split = FrontMatterExtractor.split(planText);
832
+ const rawSpecLink =
833
+ new PlanDocType("plan").parse(split.body.split("\n"), split.head).chain.specLink
834
+ ?.target ?? null;
835
+ specLink =
836
+ rawSpecLink === null
837
+ ? null
838
+ : root.relativize(this.#resolveSpecLink(repoRoot, planPath, rawSpecLink));
839
+ target = type === "plan" ? { kind: "plan", doc: planPath } : { kind: "branch" };
724
840
  break;
725
841
  }
726
842
  }
727
843
 
728
- const workspace = new Workspace(root, slug).ensure();
844
+ // The workspace is NOT built here (P11 · §4.2): scene assembly is a READ face —
845
+ // the real run's single write point builds it (`Cli#runWork`'s explicit ensure,
846
+ // every face), so a read-only command never creates `.kairos/`. The one-time
847
+ // legacy migration retired with this build: the `Workspace.readJson` read-time
848
+ // normalization is the ONE heal path, covering `base.json` alongside
849
+ // `progress.json` (a second healing point is gone).
850
+ const workspace = new Workspace(rootPath, slug);
729
851
  const ledger = new Ledger(workspace, config);
730
852
  const state =
731
853
  type === "wave"
@@ -742,14 +864,84 @@ export class Cli {
742
864
  state,
743
865
  router: new NextStepRouter(),
744
866
  briefPath: null,
867
+ specLink,
868
+ };
869
+ }
870
+
871
+ /** The input funnel — the ONE path normalization landing (T3 · §2.3): every
872
+ * path-typed argv value is relativized to the repo root EXACTLY once, here,
873
+ * before the scene or any downstream face reads it, so no face ever sees a raw
874
+ * argv path shape. The covered face: `--plan` · `--spec` · `--reviews` (the
875
+ * schema `--output skeleton` `<target>` positional and base `--plan` reach the
876
+ * SAME landing through `#relativizePath` — branch-review-1 F6: one relativize+warn
877
+ * helper, one landing). An out-of-repo input (a `..` segment after relativize) is
878
+ * ACCEPTED with a stderr warning — the shape is what is judged, never the location
879
+ * (§2.10). */
880
+ #funnel(root: RepoRoot, parsed: RunInput): RunInput {
881
+ const raw = parsed.args;
882
+ // The three path keys move OUT of the generic string record into the branded
883
+ // `paths` face (F7) — splitting them out means the raw path string exists in
884
+ // exactly ONE form downstream (the normalized `RepoPath`), never duplicated
885
+ // (the Data Clumps F2 targets).
886
+ const { plan, spec, reviews, ...rest } = raw;
887
+ return {
888
+ ...parsed,
889
+ args: rest,
890
+ paths: {
891
+ plan: plan === undefined ? null : this.#relativizePath(root, plan),
892
+ spec: spec === undefined ? null : this.#relativizePath(root, spec),
893
+ reviews: reviews === undefined ? null : this.#relativizePath(root, reviews),
894
+ },
745
895
  };
746
896
  }
747
897
 
748
- /** The repo root — the --root override, else the injected root, else the git top
749
- * level, else the cwd. */
750
- async #repoRootOf(parsed?: RunInput): Promise<string> {
751
- const override = parsed?.args.root;
752
- return override ?? this.#repoRoot ?? (await this.#git.topLevel(this.#cwd)) ?? this.#cwd;
898
+ /** The ONE path normalization landing (T3 §2.3 · F6) — relativize a raw argv path
899
+ * to the branded repoRoot-relative `RepoPath` through the value object, then warn
900
+ * on the stderr CDD_WARN channel when the result lies outside the repo. The
901
+ * work-command funnel (`#funnel`) and the pure-command path argv (schema
902
+ * `--output skeleton` `<target>` · base `--plan`) all reach THIS helper, so there
903
+ * is literally ONE relativize+warn site. An out-of-repo input (a `..` segment after
904
+ * relativize) is ACCEPTED — the shape is what is judged, never the location
905
+ * (§2.10). An empty input normalizes to the empty path (no warning). */
906
+ #relativizePath(root: RepoRoot, raw: string): RepoPath {
907
+ const rel = root.relativize(raw);
908
+ if (rel.split(path.sep).includes("..")) {
909
+ this.#io.stderr(`${this.#words.station("warn")} path is outside the repository: ${rel}\n`);
910
+ }
911
+ return rel;
912
+ }
913
+
914
+ /** The repo root — the ONE conversion point (T2 · §2.4/§2.6): the single
915
+ * working-dir → git-top-level resolution of the engine. Zero injection seams
916
+ * (`--root` is retired; the composition options carry no root/cwd), zero
917
+ * fallback. A cwd outside any git repository (a null top level) is a missing
918
+ * run-environment fact: the existing CDD_BLOCKED channel carries the reason and
919
+ * the caller exits 1 (never a usage error — exit 2). */
920
+ async #rootOf(): Promise<string | null> {
921
+ const root = await this.#git.topLevel(process.cwd());
922
+ if (root === null) {
923
+ const blocked = this.#words.station("blocked");
924
+ this.#io.stderr(
925
+ `${blocked} cannot resolve the repository root — the current directory is not inside a git repository (run cdd from within the repo)\n`,
926
+ );
927
+ return null;
928
+ }
929
+ return root;
930
+ }
931
+
932
+ /** The plan's `spec:` link target resolved to an ABSOLUTE path (D46) — the
933
+ * plan-review round context's `INPUT_SPEC` (the round-context exit relativizes it
934
+ * to repoRoot along with every other path token). The raw header form is markdown
935
+ * link-space (relative to the plan's own dir — the skeleton's form) or a repoRoot
936
+ * form; the resolution IS the doc-contract's own chain-link judgment, delegated
937
+ * to its ONE home (`FileExistenceInvariant.targetPath`) so a future contract
938
+ * change cannot silently diverge from this mirror (P9 branch-review-1 F8 — never
939
+ * a re-implemented chain). The fallback (neither reading exists) resolves against
940
+ * the plan's own dir — the link-space semantic — so the exit still receives an
941
+ * absolute path (the doc-contract's file-existence finding owns the truly-missing
942
+ * case). */
943
+ #resolveSpecLink(repoRoot: string, planPath: string, target: string): string {
944
+ return FileExistenceInvariant.targetPath(repoRoot, planPath, target, (p) => existsSync(p));
753
945
  }
754
946
 
755
947
  // ---------------------------------------------------------------------------
@@ -764,6 +956,7 @@ export class Cli {
764
956
  * schema-type table (`SCHEMA_TYPE_KEYS` in face/declare.ts: the primary DocKey
765
957
  * spellings + the legacy alias normalized to kebab, spec §5.3). */
766
958
  async #runSchema(node: Command, parsed: RunInput): Promise<number> {
959
+ this.#assertDryRunScope(node, parsed.dryRun);
767
960
  const [type, target] = parsed.positionals;
768
961
  if (type === undefined) this.#usage(node, "cdd schema get: missing <type>");
769
962
  const output = parsed.args.output ?? "json";
@@ -773,7 +966,14 @@ export class Cli {
773
966
  if (target === undefined) {
774
967
  this.#usage(node, "cdd schema get --output skeleton: missing <target>");
775
968
  }
776
- return this.#artifacts.runSchemaSkeleton(node, type, target);
969
+ // The positional `<target>` reaches the SAME one normalization landing (T3 §2.3
970
+ // · F6) as the work-command path argv (`#relativizePath`), then is erased
971
+ // through the value object at the write boundary.
972
+ const repoRoot = await this.#rootOf();
973
+ if (repoRoot === null) return 1;
974
+ const root = new RepoRoot(repoRoot);
975
+ const targetPath = this.#relativizePath(root, target);
976
+ return this.#artifacts.runSchemaSkeleton(node, root, type, targetPath);
777
977
  }
778
978
  if (target !== undefined) {
779
979
  this.#usage(
@@ -788,20 +988,29 @@ export class Cli {
788
988
  /** `cdd base <set|get> --plan <path>` — the base artifact read/write (T20: the
789
989
  * command face `base`; the artifact file carries the base face too). */
790
990
  async #runBase(node: Command, parsed: RunInput): Promise<number> {
791
- const planPath = parsed.args.plan;
792
- if (planPath === undefined) {
991
+ this.#assertDryRunScope(node, parsed.dryRun);
992
+ const planArg = parsed.args.plan;
993
+ if (planArg === undefined) {
793
994
  this.#usage(node, "cdd base: missing --plan — the sole target is --plan <path>");
794
995
  }
996
+ const repoRoot = await this.#rootOf();
997
+ if (repoRoot === null) return 1;
998
+ const root = new RepoRoot(repoRoot);
999
+ // The base `--plan` reaches the SAME one normalization landing (T3 §2.3 · F6) as
1000
+ // the work-command path argv: the stored artifact's path field speaks the ONE
1001
+ // canonical shape (repoRoot-relative).
1002
+ const planPath = this.#relativizePath(root, planArg);
1003
+ // The workspace is not built here (P11 · §4.2): `base set` builds it through
1004
+ // `Workspace.writeJson`'s internal ensure, while the read-only `base get`
1005
+ // creates nothing. The read rides `Workspace.readJson`, so the P9 read-time
1006
+ // normalization covers `base.json` (the retired migration's job).
795
1007
  const workspace = new Workspace(
796
- new WorkspaceRoot(
797
- await this.#repoRootOf(parsed),
798
- this.#config.handoffNamespace().workspaceRoot,
799
- ),
1008
+ new WorkspaceRoot(repoRoot, this.#config.handoffNamespace().workspaceRoot),
800
1009
  Workspace.slugFromDoc(planPath),
801
- ).ensure();
802
- const path = workspace.resolve("base.json");
803
- if (parsed.leaf === "set") return this.#artifacts.baseSet(node, parsed, planPath, path);
804
- if (parsed.leaf === "get") return this.#artifacts.baseGet(path);
1010
+ );
1011
+ if (parsed.leaf === "set")
1012
+ return this.#artifacts.baseSet(node, parsed, planPath, workspace, root);
1013
+ if (parsed.leaf === "get") return this.#artifacts.baseGet(workspace, root);
805
1014
  this.#usage(node, "cdd base: missing <set|get> subcommand");
806
1015
  }
807
1016