@dzhechkov/harness-cli 0.4.6 → 0.5.1

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.
package/src/cli.ts CHANGED
@@ -7,16 +7,21 @@
7
7
  import { appendFileSync, chmodSync, closeSync, cpSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
8
8
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
- import { execFileSync, execSync, spawn } from 'node:child_process';
11
- import { createHash } from 'node:crypto';
10
+ import { execFileSync, execSync, spawn, type ChildProcess } from 'node:child_process';
11
+ import { createHash, randomBytes } from 'node:crypto';
12
12
  import { homedir, tmpdir } from 'node:os';
13
13
  import { createRequire } from 'node:module';
14
14
 
15
15
  import {
16
16
  createSkill,
17
17
  getSkillInfo,
18
- isTargetName,
19
- listSkills,
18
+ listSkillsDetailed,
19
+ formatSkillLoadFailures,
20
+ formatSkillApplyFailures,
21
+ resolveTargetName,
22
+ formatTargetProblem,
23
+ formatTargetAliasNote,
24
+ TARGET_NAMES_SORTED,
20
25
  runDoctor,
21
26
  runInit,
22
27
  resolvePackageSkillRoots,
@@ -49,8 +54,38 @@ import {
49
54
  runVerify,
50
55
  runInitAgentsMd,
51
56
  runInitGeminiMd,
57
+ runSyncAgentsPolicy,
58
+ runSyncCodexHooks,
59
+ resolveCodexHome,
60
+ withNamedLockSync,
61
+ // dz workflow run (feature dz-workflow-run): the pure scheduler + the dispatch adapters.
62
+ TRACE_RUNID_RE,
63
+ WF_RUN_OWNER_HOST,
64
+ preflight,
65
+ runWorkflow,
66
+ makeClaudePDispatcher,
67
+ makeCodexExecDispatcher,
68
+ type ChildRunner,
69
+ type Dispatcher,
70
+ type DispatchResult,
71
+ type RunStore,
72
+ type RunnerInputs,
73
+ type SchedulerDeps,
74
+ type WfRunState,
75
+ NamedLockTimeoutError,
76
+ NamedLockCompromisedError,
77
+ type CodexHooksSyncReport,
78
+ type ParityCell,
79
+ type ParityFeature,
80
+ type ParityReportCell,
81
+ type RuntimeCapability,
82
+ POLICY_SOURCES,
83
+ detectPolicyDrift,
84
+ hasPolicyFence,
52
85
  TARGET_NAMES,
53
86
  buildParityMatrix,
87
+ downgradeForStaleEvidence,
88
+ findStaleTranscriptEvidence,
54
89
  TARGET_CAPABILITIES,
55
90
  TARGET_SHORT_LABELS,
56
91
  WORKFLOW_TEMPLATES_RETIRED_MESSAGE,
@@ -215,6 +250,7 @@ import {
215
250
  buildChallengeBrief,
216
251
  planDiscriminationCheck,
217
252
  classifyDiscrimination,
253
+ classifyExecutionEvidence,
218
254
  pickAdversaryModel,
219
255
  CHALLENGE_QUESTIONS,
220
256
  loadOutcomes,
@@ -320,6 +356,24 @@ import {
320
356
  renderDomainBoostNote,
321
357
  renderDomainCutNote,
322
358
  parseReqeDebt,
359
+ // qe-bridge (feature qe-bridge-claude, ADR-001): the pure half of the reverse QE bridge.
360
+ KNOWN_CLAUDE,
361
+ isSafeClaudeId,
362
+ claudeProbeArgs,
363
+ claudeReviewArgs,
364
+ interpretClaudeProbe,
365
+ modelFamily,
366
+ buildBridgePrompt,
367
+ parseBridgeOutput,
368
+ buildBridgeFailureRecord,
369
+ buildBridgeSignoffRecord,
370
+ renderBridgeReport,
371
+ isSafeSlug,
372
+ hasUnsafePathChars,
373
+ hasDotDotSegment,
374
+ type BridgeFamily,
375
+ type BridgeFailureReason,
376
+ type NamedExtract,
323
377
  buildReqeBrief,
324
378
  settleReqeDebt,
325
379
  renderReqeList,
@@ -343,7 +397,9 @@ import {
343
397
  planImport,
344
398
  } from '@dzhechkov/harness-core';
345
399
  import type { MutationEntryResult, MutationObservation, MutationRegistryEntry } from '@dzhechkov/harness-core';
400
+ import type { SkillApplyFailure, SkillLoadFailure } from '@dzhechkov/harness-core';
346
401
  import type { ReqeDebt } from '@dzhechkov/harness-core';
402
+ import type { ClassifyResultRow, ExecutionEvidence } from '@dzhechkov/harness-core';
347
403
  import type { IdeaRecord, IdeaStatus } from '@dzhechkov/harness-core';
348
404
  import type { Family, ModelRung, Candidate as BtoCandidate, DimScores } from '@dzhechkov/harness-core';
349
405
  import type { SetupSpec } from '@dzhechkov/harness-core';
@@ -355,7 +411,7 @@ import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, S
355
411
  const USAGE = `dz - DZ cross-platform harness CLI
356
412
 
357
413
  Usage:
358
- dz init --target <name> [--skills-dir <dir>] [--project <dir>] [--preset <name>] [--select id,id,...] [--force] [--enrich]
414
+ dz init --target <name> [--skills-dir <dir>] [--project <dir>] [--preset <name>] [--select id,id,...] [--force] [--enrich] [--no-hooks] [--no-verify] (--target codex ALSO installs the user-global dz veto+recall hooks and LIVE-verifies them (ADR-001 §8); --no-hooks = skills only; --no-verify skips the live probe and can never report ready)
359
415
  dz verify [--skills-dir <dir>] [--target <name>]
360
416
  dz sync [--canonical <dir>] [--project <dir>] [--dry-run] [--force]
361
417
  dz update (alias of sync)
@@ -390,6 +446,7 @@ Usage:
390
446
  dz epoch-replay --score <judgments.json> --work-order <file> [--slice <name>] [--json] (un-blind against the pre-registered assignment → SUPPORTED only when the two 95% Wilson CIs are DISJOINT, else FALSIFIED / INCONCLUSIVE)
391
447
  dz score --slug <feature> [--project <dir>] [--json] (process scorecard for ONE feature-adr run, from its artifacts: ADR confirmation, discrimination, cross-model QE grade, live verification, README-first, learning loop, amendments — descriptive-only, a low score exits 0)
392
448
  dz reqe [--slug <feature> [--done --report <f>]] [--json] (the re-QE debt ledger: a usage-switched run whose Step-8 QE ran on the coder's OWN family records a debt; list debts, print the cross-family review brief, settle FAIL-CLOSED against a graded report — the settlement lands in 08_qe_report.md)
449
+ dz qe-bridge --family claude --slug <feature> [--coder-family codex|claude] [--model <id>] [--files a,b] [--out <f>] [--timeout <s>] [--allow-same-family] [--json] (the REVERSE QE bridge: run an INDEPENDENT Claude reviewer over a feature's Step-8 artifacts from ANY host — a Codex session included, plain shell, no Claude agent plane needed — and land a PARSED signoff. The reviewer runs ISOLATED: an EMPTY temp cwd plus --safe-mode --strict-mcp-config --tools '' --no-session-persistence, so no CLAUDE.md/skills/plugins/hooks/MCP load, and the verdict is read from the --output-format json RESULT ENVELOPE — text a session customization printed onto the same stdout can never become a signoff. Probes the model before trusting it; sends SCOPED extracts with a loud 200k-char ceiling (never silent truncation); the grade must AGREE across three LAST-anchored channels (terminal marker line, fenced qe-bridge-signoff JSON, the report's own GRADE line) AND the marker must be the FINAL content — empty, gradeless, self-contradicting or miscounted output is one of 18 NAMED failures with an audit record under features/<slug>/.fa-state/qe-bridge/ (runId, resolved executable + binOverride, prompt sha256, channel offsets, requestedOut, reportWritten, retained raw stdout; 0600 files in a 0700 dir), never a clean review. A --coder-family that contradicts the recorded reqe debt is refused. Writes features/<slug>/08b_reqe_report.md, which dz reqe --done settles unchanged. DISCLOSURE: the extracts you scope are sent to the Claude runtime; the bridge cannot classify secrets. DZ_QE_BRIDGE_CLAUDE_BIN is a TEST SEAM, not a flag. exit 0 signoff parsed (ANY grade — it reports, it does not gate) / 1 named failure / 2 usage)
393
450
  dz mutation-gate [--package <dir>] [--registry <file>] [--test-cmd "<cmd>"] [--only <id[,id]>] [--timeout <ms>] [--rebaseline per-entry|final] [--keep-scratch] [--json] (prove each NAMED protection has a test that DISCRIMINATES: copy the package to a scratch dir, verify the baseline suite is green, apply each registry mutation, run the suite, REQUIRE red, restore. The red must be BEHAVIOURAL: a mutation that no longer parses is MUTATION_UNPARSEABLE; a red run whose OWN output reports a test FILE failing to load (node --test file-level not-ok with exitCode, vitest Failed Suites) is MUTATION_LOAD_FATAL — the signal comes from the same run as the failing count, never from a separate isolated import; red output whose shape matches no known runner is INCONCLUSIVE (a runner-coverage gap, loud, never PROVEN); a count far above the entry's bound is OVER_FAILING; a restored tree that does not reproduce green makes the entry INCONCLUSIVE (flaky). Mutation writes are realpath-contained to the scratch copy: a symlink escape or a node_modules/ target is refused (exit 2), the real tree is never written. A mutation that does not apply, a green suite, or an inconclusive run is a FAILURE — never a skip. exit 0 all proven / 1 gate failed / 2 setup error)
394
451
  dz backlog add "<idea>" [--effort 1-5] [--proposal <text>] [--dry-run] [--project <dir>] [--json] (capture an idea: semantic dedup against existing ideas via the Brain vector engine (DUPLICATE>=0.92 merges, RELATED links, NEW creates) + GoalMap alignment; --dry-run classifies without writing)
395
452
  dz backlog list [--status <s>] [--goal <id>] [--project <dir>] [--json] (list captured ideas, filterable by status/goal)
@@ -404,7 +461,7 @@ Usage:
404
461
  dz backlog enrich <id> [--project <dir>] [--json] (stage the idea2prd input scaffold in features/<slug>/ and hand off to the idea2prd-manual skill — the CLI never fabricates a PRD)
405
462
  dz backlog jira <id> [--project <dir>] [--json] (draft a Jira issue via the configurable adapter (backlog.jira.adapter: jira-mcp|copilot-mcp|none); none writes an auditable jira-outbox/<id>.json stub)
406
463
  dz backlog harmonize [--apply] [--threshold <0-1>] [--project <dir>] [--json] (batch semantic dedup of the backlog ideas; --dry-run default, --apply snapshots first)
407
- dz setup --target <name> [--preset <name>] [--select id,id,...] [--skills-dir <dir>] [--project <dir>] [--memory agentdb] [--no-memory] [--no-hooks] [--install-driver] [--force] [--enrich]
464
+ dz setup --target <name> [--preset <name>] [--select id,id,...] [--skills-dir <dir>] [--project <dir>] [--memory agentdb] [--no-memory] [--no-hooks] [--no-verify] [--install-driver] [--force] [--enrich] (--target codex ALSO installs + LIVE-verifies the codex hooks; an unverified hook exits non-zero WITHOUT aborting the rest of setup)
408
465
  dz teach "<pattern>" [--reward <0-1>] [--domain <name>] [--type rule|success-pattern|lesson-learned] [--project <dir>] [--no-mirror] (--project pins the learned store to <dir>/.dz, not the cwd — pin to a canonical brain)
409
466
  dz teach --from-json <file> [--project <dir>] [--no-mirror] (bulk-import a 'dz recall --all --json' export — share a learned store across machines)
410
467
  dz consolidate [--sessions-dir <dir>] [--project <dir>] [--no-mirror] [--prune-noise [--apply]] [--prune-quarantine [--apply]] (both prunes: DRY-RUN by default; --apply snapshots then deletes; prune-quarantine = expired unproven lessons ONLY, never coupled to noise)
@@ -441,6 +498,8 @@ Usage:
441
498
  (build-time: reconcile project grants vs installed skills' declared capabilities; dz never enforces — the host does)
442
499
  dz sync-upstream [--package <dir>] [--list] [--all]
443
500
  dz drift-check [--json] [--project <dir>] (CI gate: exit 1 if any shared skill drifted between its monorepo copies)
501
+ dz agents-sync [--project <dir>] [--check] [--json] (sync/verify the always-on policy fence in root AGENTS.md; exit 0 synced/written, 1 drift, 3 inconclusive)
502
+ dz hooks-sync --target codex [--check] [--verify] [--remove] [--json] (install/verify the dz veto + recall hooks in $CODEX_HOME/hooks.json; exit 0 armed+trusted, 1 not armed/drift, 3 inconclusive)
444
503
  dz sync-canonical <skill> [--check] [--from <dir>] [--auto] [--project <dir>] (heal every copy from skills-meta/<skill> or --from; no canonical + --check = compare copies to each other (exit 1 on drift); no canonical + write = refuse unless --auto (LOUD, picks most-complete copy); --check writes nothing)
445
504
  dz plugin [--version <ver>]
446
505
  dz downloads
@@ -452,6 +511,18 @@ Usage:
452
511
 
453
512
  Global: --version | -v [--json] (prints this CLI's own semver on one line, exit 0; "unknown" + exit 1 when unresolvable)
454
513
 
514
+ dz workflow run <plan.json> [--run-id <id>] [--resume <runId>] [--arg k=v]... [--coder-family codex|claude]
515
+ [--default-family codex|claude] [--budget <n>] [--max-wall-clock <s>] [--stage-timeout <s>]
516
+ [--budget-extra <n>] [--wall-clock-extra <s>] [--run-dir <dir>] [--allow-same-family-qe] [--json]
517
+ (INTERPRET a loop-plan/1 plan host-independently; writes trace/budget/checkpoints under .dz/loop-trace/<runId>/)
518
+
519
+ EXIT CODES - "workflow run" and "workflow-lint" have DIFFERENT tables, side by side:
520
+ run 0 completed | 1 failed (named reason) | 2 usage/invalid plan | 75 typed pause (sysexits EX_TEMPFAIL)
521
+ lint 0 clean | 1 findings | 3 inconclusive
522
+ 75 is NOT 3: 3 reads ignorable and collides with lint's inconclusive, while a pause strands resumable work.
523
+ On a pause the LAST stdout line is a "wf-pause-envelope/1" JSON object; a FAILURE emits none, so a wrapper
524
+ tells the two apart from stdout + exit code alone, without parsing prose.
525
+
455
526
  Workflows: author loop-plan/1 plans with dz workflow init/validate/render; gate them with dz workflow-lint; read runs with dz workflow-trace (the ADR-005 templates are retired)
456
527
 
457
528
  Targets: ${TARGET_NAMES.join(', ')}
@@ -461,6 +532,18 @@ Presets: ${PRESET_NAMES.join(', ')}`;
461
532
  export interface CliIo {
462
533
  readonly cwd?: string;
463
534
  readonly write?: (line: string) => void;
535
+ /**
536
+ * Diagnostics sink — **stderr**, defaulting to `console.error`.
537
+ *
538
+ * Before feature dz-cli-defects `CliIo` had no stderr seam at all, so every
539
+ * diagnostic (including the top-level error handler) landed on stdout and
540
+ * `dz list > skills.txt` wrote the error INTO the data file. `write` stays "data
541
+ * only"; `writeErr` is "diagnosis only".
542
+ *
543
+ * There is deliberately **no** fall-back to `write`: a test that wants to assert on
544
+ * stderr must inject `writeErr`, or the assertion would be theatre.
545
+ */
546
+ readonly writeErr?: (line: string) => void;
464
547
  /**
465
548
  * Pre-read STDIN content (injectable so `dz brain ground`'s hook path is testable without
466
549
  * an actual pipe). When omitted, the CLI reads fd 0 synchronously — but only for the one
@@ -531,6 +614,8 @@ function parseArgs(argv: string[]): ParsedArgs {
531
614
  }
532
615
 
533
616
  type Write = (line: string) => void;
617
+ /** Mirrors {@link Write}, but for the stderr seam (see {@link CliIo.writeErr}). */
618
+ type WriteErr = (line: string) => void;
534
619
 
535
620
  /**
536
621
  * Discover skill source directories: explicit `--skills-dir` if given, else
@@ -560,6 +645,14 @@ interface InstallSkillsResult {
560
645
  readonly skipped: number;
561
646
  /** Selected ids found in NO searched directory (empty when no `select` was given). */
562
647
  readonly missing: string[];
648
+ /** Skill dirs that could not be LOADED, across every searched directory (D1). */
649
+ readonly failures: SkillLoadFailure[];
650
+ /**
651
+ * Skills that loaded but could not be COMPILED or WRITTEN (fix round 1, QE F4).
652
+ * A separate list because it accuses a different artifact — the target tree, not
653
+ * the source `SKILL.md`.
654
+ */
655
+ readonly applyFailures: SkillApplyFailure[];
563
656
  }
564
657
 
565
658
  /**
@@ -597,10 +690,12 @@ async function installSkills(opts: {
597
690
  let written = 0;
598
691
  let skipped = 0;
599
692
  for (const s of results) { written += s.written; skipped += s.skipped; }
600
- return { results, dirsSearched: skillsDirs.length, written, skipped, missing: [...report.missing] };
693
+ return { results, dirsSearched: skillsDirs.length, written, skipped, missing: [...report.missing], failures: [...report.failures], applyFailures: [...report.applyFailures] };
601
694
  }
602
695
 
603
696
  const results: { id: string; written: number; skipped: number }[] = [];
697
+ const failures: SkillLoadFailure[] = [];
698
+ const applyFailures: SkillApplyFailure[] = [];
604
699
  for (const skillsDir of skillsDirs) {
605
700
  const r = await runInit({
606
701
  target,
@@ -613,6 +708,8 @@ async function installSkills(opts: {
613
708
  for (const skill of r.skills) {
614
709
  results.push({ id: skill.id, written: skill.written.length, skipped: skill.skipped.length });
615
710
  }
711
+ failures.push(...r.failures);
712
+ applyFailures.push(...r.applyFailures);
616
713
  }
617
714
 
618
715
  let written = 0;
@@ -620,7 +717,7 @@ async function installSkills(opts: {
620
717
  for (const s of results) { written += s.written; skipped += s.skipped; }
621
718
  const installed = new Set(results.map((s) => s.id));
622
719
  const missing = select !== undefined ? [...select].filter((id) => !installed.has(id)) : [];
623
- return { results, dirsSearched: skillsDirs.length, written, skipped, missing };
720
+ return { results, dirsSearched: skillsDirs.length, written, skipped, missing, failures, applyFailures };
624
721
  }
625
722
 
626
723
  /** Warn about preset/select ids that weren't found in any installed pack. */
@@ -636,12 +733,22 @@ function writeMissingSkillsHint(write: Write, missing: string[], presetName: str
636
733
  }
637
734
  }
638
735
 
639
- async function cmdInit(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): Promise<number> {
640
- const target = options.get('target');
641
- if (target === undefined || !isTargetName(target)) {
642
- write(`dz init: --target must be one of: ${TARGET_NAMES.join(', ')}`);
736
+ async function cmdInit(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr): Promise<number> {
737
+ const targetOpt = options.get('target');
738
+ if (targetOpt === undefined) {
739
+ // A missing `--target` is the same accusation as an unresolvable one, so it takes
740
+ // the same channel: diagnostics on stderr, stdout stays a data channel (ADR-002
741
+ // §Decision 2 / driver D6; fix round 1, QE F2).
742
+ writeErr(`dz init: --target must be one of: ${TARGET_NAMES_SORTED.join(', ')}`);
743
+ return 1;
744
+ }
745
+ const resolution = resolveTargetName(targetOpt);
746
+ if (resolution.kind === 'unknown') {
747
+ for (const line of formatTargetProblem('dz init', resolution)) writeErr(line);
643
748
  return 1;
644
749
  }
750
+ const target = resolution.target;
751
+ if (resolution.via === 'alias') writeErr(formatTargetAliasNote('dz init', targetOpt, target));
645
752
  const explicitSkillsDir = options.get('skills-dir');
646
753
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
647
754
 
@@ -679,19 +786,56 @@ async function cmdInit(options: Map<string, string>, flags: Set<string>, cwd: st
679
786
  write(` (searched ${r.dirsSearched} skill directories)`);
680
787
  }
681
788
  writeMissingSkillsHint(write, r.missing, presetName);
682
- return 0;
789
+
790
+ // Codex-targeted init DELIVERS the hooks and verifies them (ADR-001 §8). Skills alone are not the
791
+ // target's harness: the veto + recall legs are what `--target codex` promises.
792
+ // `--no-hooks` is the documented escape for "skills only" (the same flag `dz setup` already
793
+ // carries): hook delivery writes USER-GLOBAL config, so a command that only wants skills compiled
794
+ // must be able to say so — and every test that is about skills says it.
795
+ let codexHooksOk = true;
796
+ if (target === 'codex' && !flags.has('no-hooks')) {
797
+ const delivery = deliverCodexHooks({ project: projectRoot, verify: !flags.has('no-verify') }, undefined, 'dz init');
798
+ codexHooksOk = delivery.ok;
799
+ for (const line of delivery.stdout) write(line);
800
+ for (const line of delivery.stderr) writeErr(line);
801
+ }
802
+ // Skip-and-collect must not become skip-and-SILENCE: a skill that failed to load is
803
+ // named on stderr and the command exits 1 (it exited 1 before too — by throwing).
804
+ if (r.failures.length > 0 || r.applyFailures.length > 0) {
805
+ // Counts first, then the named block — the same shape `dz list` uses. The block's
806
+ // own header already says "N skipped", so this line carries what it cannot: how many
807
+ // DID install, so a reader can tell a mostly-fine install from a mostly-broken one.
808
+ //
809
+ // The two failure kinds are counted and rendered SEPARATELY (fix round 1, QE F4):
810
+ // an unwritable target directory is not a broken pack, and printing it as one names
811
+ // the wrong file.
812
+ const parts = [`${r.results.length} installed`];
813
+ if (r.failures.length > 0) parts.push(`${r.failures.length} skipped`);
814
+ if (r.applyFailures.length > 0) parts.push(`${r.applyFailures.length} failed to write`);
815
+ writeErr(`dz init: ${parts.join(', ')}`);
816
+ for (const line of formatSkillLoadFailures(r.failures)) writeErr(line);
817
+ for (const line of formatSkillApplyFailures(r.applyFailures)) writeErr(line);
818
+ return 1;
819
+ }
820
+ return codexHooksOk ? 0 : 1;
683
821
  }
684
822
 
685
- async function cmdVerify(options: Map<string, string>, cwd: string, write: Write): Promise<number> {
823
+ async function cmdVerify(options: Map<string, string>, cwd: string, write: Write, writeErr: WriteErr): Promise<number> {
686
824
  const skillsDir = resolve(cwd, options.get('skills-dir') ?? '.claude/skills');
687
825
  const targetOpt = options.get('target');
688
- if (targetOpt !== undefined && !isTargetName(targetOpt)) {
689
- write(`dz verify: --target must be one of: ${TARGET_NAMES.join(', ')}`);
690
- return 1;
826
+ let target: TargetName | undefined;
827
+ if (targetOpt !== undefined) {
828
+ const resolution = resolveTargetName(targetOpt);
829
+ if (resolution.kind === 'unknown') {
830
+ for (const line of formatTargetProblem('dz verify', resolution)) writeErr(line);
831
+ return 1;
832
+ }
833
+ target = resolution.target;
834
+ if (resolution.via === 'alias') writeErr(formatTargetAliasNote('dz verify', targetOpt, target));
691
835
  }
692
836
  const report = await runVerify({
693
837
  skillsDir,
694
- ...(targetOpt !== undefined ? { target: targetOpt } : {}),
838
+ ...(target !== undefined ? { target } : {}),
695
839
  });
696
840
  write(`dz verify (${report.target}): ${report.valid}/${report.total} skill(s) valid`);
697
841
  for (const skill of report.skills) {
@@ -700,7 +844,7 @@ async function cmdVerify(options: Map<string, string>, cwd: string, write: Write
700
844
  return report.valid === report.total ? 0 : 1;
701
845
  }
702
846
 
703
- async function cmdSync(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): Promise<number> {
847
+ async function cmdSync(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr): Promise<number> {
704
848
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
705
849
  const canonicalArg = options.get('canonical');
706
850
 
@@ -727,6 +871,14 @@ async function cmdSync(options: Map<string, string>, flags: Set<string>, cwd: st
727
871
  write(
728
872
  `dz sync${report.dryRun ? ' --dry-run' : ''}: ${inSync}/${total} in sync, ${missing} missing, ${drift} drift`,
729
873
  );
874
+ // Skip-and-collect (D1): the broken canonical skills are NAMED on stderr, and their
875
+ // presence keeps the exit code non-zero — a partial sync is not a clean sync.
876
+ if (report.failures.length > 0) {
877
+ // See `cmdInit` above: counts here, names in the block below.
878
+ writeErr(`dz sync: ${report.skills.length} compared, ${report.failures.length} skipped`);
879
+ for (const line of formatSkillLoadFailures(report.failures)) writeErr(line);
880
+ return 1;
881
+ }
730
882
  return missing === 0 && drift === 0 ? 0 : 1;
731
883
  }
732
884
 
@@ -773,19 +925,42 @@ function cmdCreateSkill(options: Map<string, string>, flags: Set<string>, cwd: s
773
925
  return 0;
774
926
  }
775
927
 
776
- function cmdList(options: Map<string, string>, cwd: string, write: Write): number {
928
+ /**
929
+ * `dz list` — skip-and-collect (feature dz-cli-defects, D1).
930
+ *
931
+ * One unparseable `SKILL.md` used to discard the ENTIRE listing with a message naming
932
+ * neither the file nor the count. Now the parseable skills list on stdout and the
933
+ * broken ones are named on stderr. The whole emit contract, in one place:
934
+ *
935
+ * | valid | skipped | stdout | stderr | exit |
936
+ * |-------|---------|--------|--------|------|
937
+ * | >0 | 0 | listing | *empty* | 0 |
938
+ * | >0 | >0 | listing of the valid ones | named summary | 1 |
939
+ * | 0 | >0 | *nothing* | named summary | 1 |
940
+ * | 0 | 0 | *nothing* | `no skills found in <dir>` | 1 |
941
+ *
942
+ * The last row is the ONE intentional departure from byte-identical output: that line
943
+ * used to go to stdout. Moving it keeps *stdout is data, stderr is diagnosis* whole —
944
+ * the invariant that makes `dz list > out.txt` trustworthy.
945
+ */
946
+ function cmdList(options: Map<string, string>, cwd: string, write: Write, writeErr: WriteErr): number {
777
947
  const skillsDir = resolve(cwd, options.get('skills-dir') ?? '.claude/skills');
778
- const skills = listSkills(skillsDir);
779
- if (skills.length === 0) {
780
- write(`dz list: no skills found in ${skillsDir}`);
948
+ const { skills, failures } = listSkillsDetailed(skillsDir);
949
+ if (skills.length === 0 && failures.length === 0) {
950
+ writeErr(`dz list: no skills found in ${skillsDir}`);
781
951
  return 1;
782
952
  }
783
- write(`${skills.length} skill(s) in ${skillsDir}:\n`);
784
- for (const skill of skills) {
785
- const desc = skill.description.length > 80 ? skill.description.slice(0, 77) + '...' : skill.description;
786
- write(` ${skill.id.padEnd(35)} ${desc}`);
953
+ if (skills.length > 0) {
954
+ write(`${skills.length} skill(s) in ${skillsDir}:\n`);
955
+ for (const skill of skills) {
956
+ const desc = skill.description.length > 80 ? skill.description.slice(0, 77) + '...' : skill.description;
957
+ write(` ${skill.id.padEnd(35)} ${desc}`);
958
+ }
787
959
  }
788
- return 0;
960
+ if (failures.length === 0) return 0;
961
+ writeErr(`dz list: ${skills.length} listed, ${failures.length} skipped in ${skillsDir}`);
962
+ for (const line of formatSkillLoadFailures(failures)) writeErr(line);
963
+ return 1;
789
964
  }
790
965
 
791
966
  function cmdInfo(options: Map<string, string>, args: ParsedArgs, cwd: string, write: Write): number {
@@ -1599,6 +1774,7 @@ async function cmdInstall(
1599
1774
  flags: Set<string>,
1600
1775
  cwd: string,
1601
1776
  write: Write,
1777
+ writeErr: WriteErr,
1602
1778
  installRunner?: (command: string, cwd: string) => void,
1603
1779
  ): Promise<number> {
1604
1780
  const pkg = options.get('_positional_0');
@@ -1608,10 +1784,13 @@ async function cmdInstall(
1608
1784
  }
1609
1785
 
1610
1786
  const targetOpt = options.get('target') ?? 'claude-code';
1611
- if (!isTargetName(targetOpt)) {
1612
- write(`dz install: --target must be one of: ${TARGET_NAMES.join(', ')}`);
1787
+ const targetResolution = resolveTargetName(targetOpt);
1788
+ if (targetResolution.kind === 'unknown') {
1789
+ for (const line of formatTargetProblem('dz install', targetResolution)) writeErr(line);
1613
1790
  return 1;
1614
1791
  }
1792
+ const target = targetResolution.target;
1793
+ if (targetResolution.via === 'alias') writeErr(formatTargetAliasNote('dz install', targetOpt, target));
1615
1794
 
1616
1795
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
1617
1796
 
@@ -1647,7 +1826,7 @@ async function cmdInstall(
1647
1826
 
1648
1827
  // Step 3: Use dz init with the resolved skills root as source
1649
1828
  const report = await runInit({
1650
- target: targetOpt,
1829
+ target,
1651
1830
  skillsDir: root.dir,
1652
1831
  projectRoot,
1653
1832
  force: flags.has('force'),
@@ -1666,21 +1845,36 @@ async function cmdInstall(
1666
1845
  if (root.layout === 'npx-template' && root.hasCompanionAssets) {
1667
1846
  write(` note: ${pkg} also ships commands/hooks/agents — \`npx -y ${pkg} init\` installs the full kit.`);
1668
1847
  }
1848
+ // Skip-and-collect at install time (D1 / the report's D2 amendment): the offending
1849
+ // SKILL.md came out of the DOWNLOADED TARBALL, so the path is rendered relative to
1850
+ // the package root (a `node_modules/**` absolute path is not actionable) and the
1851
+ // message says whose defect it is. Exit 1 — a pack that shipped an unloadable skill
1852
+ // did not fully install.
1853
+ if (report.failures.length > 0) {
1854
+ writeErr(`dz install: ${pkg} ships ${report.failures.length} unparseable skill(s) —`);
1855
+ for (const line of formatSkillLoadFailures(report.failures, { relativeTo: pkgDir })) writeErr(line);
1856
+ writeErr('This is a defect in the package, not in your project.');
1857
+ writeErr(`Workaround: npx -y ${pkg} init`);
1858
+ return 1;
1859
+ }
1669
1860
  return 0;
1670
1861
  }
1671
1862
 
1672
- function cmdCompose(options: Map<string, string>, cwd: string, write: Write): number {
1863
+ function cmdCompose(options: Map<string, string>, cwd: string, write: Write, writeErr: WriteErr): number {
1673
1864
  const combo = options.get('_positional_0');
1674
1865
  if (!combo) {
1675
1866
  write('dz compose: preset combination required (e.g., dz compose devops+mcp+web3)');
1676
1867
  return 1;
1677
1868
  }
1678
1869
  // --target is documented; honor it in the suggested install command (was hardcoded claude-code).
1679
- const target = options.get('target') ?? 'claude-code';
1680
- if (!isTargetName(target)) {
1681
- write(`dz compose: --target must be one of: ${TARGET_NAMES.join(', ')}`);
1870
+ const targetOpt = options.get('target') ?? 'claude-code';
1871
+ const composeResolution = resolveTargetName(targetOpt);
1872
+ if (composeResolution.kind === 'unknown') {
1873
+ for (const line of formatTargetProblem('dz compose', composeResolution)) writeErr(line);
1682
1874
  return 1;
1683
1875
  }
1876
+ const target = composeResolution.target;
1877
+ if (composeResolution.via === 'alias') writeErr(formatTargetAliasNote('dz compose', targetOpt, target));
1684
1878
  const presetNames = combo.split('+').map((s) => s.trim());
1685
1879
  const allSkills = new Set<string>();
1686
1880
  const resolved: string[] = [];
@@ -3897,12 +4091,19 @@ async function cmdBrain(
3897
4091
  return sub === undefined ? 0 : 1;
3898
4092
  }
3899
4093
 
3900
- async function cmdSetup(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): Promise<number> {
3901
- const target = options.get('target');
3902
- if (!target || !isTargetName(target)) {
3903
- write(`dz setup: --target required (${TARGET_NAMES.join(', ')})`);
4094
+ async function cmdSetup(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr): Promise<number> {
4095
+ const targetOpt = options.get('target');
4096
+ if (!targetOpt) {
4097
+ writeErr(`dz setup: --target required (${TARGET_NAMES_SORTED.join(', ')})`);
4098
+ return 1;
4099
+ }
4100
+ const setupResolution = resolveTargetName(targetOpt);
4101
+ if (setupResolution.kind === 'unknown') {
4102
+ for (const line of formatTargetProblem('dz setup', setupResolution)) writeErr(line);
3904
4103
  return 1;
3905
4104
  }
4105
+ const target = setupResolution.target;
4106
+ if (setupResolution.via === 'alias') writeErr(formatTargetAliasNote('dz setup', targetOpt, target));
3906
4107
 
3907
4108
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
3908
4109
  const presetName = options.get('preset');
@@ -3955,6 +4156,17 @@ async function cmdSetup(options: Map<string, string>, flags: Set<string>, cwd: s
3955
4156
  write(`║ (no skills resolved) ║`);
3956
4157
  }
3957
4158
 
4159
+ // Step 5 (ADR-001 §8): DELIVER the codex hooks and verify them live. Non-aborting — the rest of
4160
+ // setup has already run and the summary still prints; only the exit code carries the failure.
4161
+ let codexHooksOk = true;
4162
+ if (target === 'codex' && !flags.has('no-hooks')) {
4163
+ write(`║ 5. Delivering codex hooks (live verify)... ║`);
4164
+ const delivery = deliverCodexHooks({ project: projectRoot, verify: !flags.has('no-verify') }, undefined, 'dz setup');
4165
+ codexHooksOk = delivery.ok;
4166
+ for (const line of delivery.stdout) write(line);
4167
+ for (const line of delivery.stderr) writeErr(line);
4168
+ }
4169
+
3958
4170
  write(`╠══════════════════════════════════════════════════════╣`);
3959
4171
  write(`║ Setup: ${String(setupResult.completed).padStart(2)} done, ${String(setupResult.skipped).padStart(2)} skipped ║`);
3960
4172
  // Honest label derived from the ACTUAL wiring (runSetup's 'agentdb wiring' invariant check),
@@ -3974,7 +4186,9 @@ async function cmdSetup(options: Map<string, string>, flags: Set<string>, cwd: s
3974
4186
  + (install.dirsSearched > 1 ? ` (searched ${install.dirsSearched} skill dirs)` : ''));
3975
4187
  writeMissingSkillsHint(write, install.missing, selectArg !== undefined ? undefined : preset);
3976
4188
  }
3977
- return 0;
4189
+ // A hook that was written but never witnessed firing is NOT a completed setup (ADR-002 §5): the
4190
+ // step is reported failed, the process was not aborted.
4191
+ return codexHooksOk ? 0 : 1;
3978
4192
  }
3979
4193
 
3980
4194
  function cmdPretrain(options: Map<string, string>, cwd: string, write: Write): number {
@@ -4089,12 +4303,17 @@ function cmdRecommend(options: Map<string, string>, cwd: string, write: Write):
4089
4303
  return 0;
4090
4304
  }
4091
4305
 
4092
- function cmdUpgrade(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
4306
+ function cmdUpgrade(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr): number {
4093
4307
  const targetOpt = options.get('target') ?? 'claude-code';
4094
- if (!isTargetName(targetOpt)) {
4095
- write(`dz upgrade: --target must be one of: ${TARGET_NAMES.join(', ')}`);
4308
+ const upgradeResolution = resolveTargetName(targetOpt);
4309
+ if (upgradeResolution.kind === 'unknown') {
4310
+ for (const line of formatTargetProblem('dz upgrade', upgradeResolution)) writeErr(line);
4096
4311
  return 1;
4097
4312
  }
4313
+ // The dir map is keyed by the RESOLVED name — keying it by the raw `--target` would
4314
+ // let an alias validate and then miss the map.
4315
+ const upgradeTarget = upgradeResolution.target;
4316
+ if (upgradeResolution.via === 'alias') writeErr(formatTargetAliasNote('dz upgrade', targetOpt, upgradeTarget));
4098
4317
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
4099
4318
  const targetDirMap: Record<string, string> = {
4100
4319
  'claude-code': '.claude/skills', codex: '.agents/skills', opencode: '.opencode/skills',
@@ -4102,9 +4321,9 @@ function cmdUpgrade(options: Map<string, string>, flags: Set<string>, cwd: strin
4102
4321
  'agents-md': 'AGENTS.md', cursor: '.cursor/rules', gemini: 'GEMINI.md',
4103
4322
  windsurf: '.windsurf/rules',
4104
4323
  };
4105
- const mappedDir = targetDirMap[targetOpt];
4324
+ const mappedDir = targetDirMap[upgradeTarget];
4106
4325
  if (mappedDir === undefined) {
4107
- write(`dz upgrade: no skills directory mapping for target ${targetOpt}`);
4326
+ write(`dz upgrade: no skills directory mapping for target ${upgradeTarget}`);
4108
4327
  return 1;
4109
4328
  }
4110
4329
  const targetDir = join(projectRoot, mappedDir);
@@ -4122,7 +4341,7 @@ function cmdUpgrade(options: Map<string, string>, flags: Set<string>, cwd: strin
4122
4341
 
4123
4342
  const report = checkUpgrades(targetDir, canonicalDirs);
4124
4343
 
4125
- write(`\ndz upgrade — ${targetOpt} (${targetDir})`);
4344
+ write(`\ndz upgrade — ${upgradeTarget} (${targetDir})`);
4126
4345
  write(` Installed: ${report.installed} Needs update: ${report.needsUpdate} Up-to-date: ${report.upToDate} Custom: ${report.notInCanonical}\n`);
4127
4346
 
4128
4347
  for (const check of report.skills) {
@@ -4131,7 +4350,7 @@ function cmdUpgrade(options: Map<string, string>, flags: Set<string>, cwd: strin
4131
4350
  }
4132
4351
 
4133
4352
  if (report.needsUpdate > 0) {
4134
- write(`\n${report.needsUpdate} skill(s) need update. Run: dz init --target ${targetOpt} --force`);
4353
+ write(`\n${report.needsUpdate} skill(s) need update. Run: dz init --target ${upgradeTarget} --force`);
4135
4354
  }
4136
4355
  // ADR-001 (verify-apply-leg): verify what we just left on disk. A TAMPERED pack aborts.
4137
4356
  const sigFatal = reportPackVerification(projectRoot, options.get('pubkey'), flags.has('require-signing'), write);
@@ -4675,7 +4894,7 @@ function cmdPublish(options: Map<string, string>, flags: Set<string>, cwd: strin
4675
4894
  /* ADR-001): computed from the declarative model, never hand-written */
4676
4895
  /* ------------------------------------------------------------------ */
4677
4896
 
4678
- function cmdParity(options: Map<string, string>, flags: Set<string>, write: Write): number {
4897
+ function cmdParity(options: Map<string, string>, flags: Set<string>, write: Write, writeErr: WriteErr): number {
4679
4898
  const json = flags.has('json');
4680
4899
  if (flags.has('help')) {
4681
4900
  write('dz parity [--target <name>] [--json] — the computed feature×target map (never hand-written)');
@@ -4704,34 +4923,79 @@ function cmdParity(options: Map<string, string>, flags: Set<string>, write: Writ
4704
4923
  }
4705
4924
 
4706
4925
  const matrix = buildParityMatrix();
4707
- const target = options.get('target');
4708
- if (target !== undefined && !TARGET_NAMES.includes(target as (typeof TARGET_NAMES)[number])) {
4709
- if (json) write(JSON.stringify({ error: `unknown target "${target}"`, targets: TARGET_NAMES, exitCode: 1 }, null, 2));
4710
- else write(`dz parity: unknown target "${target}" one of: ${TARGET_NAMES.join(', ')}`);
4711
- return 1;
4926
+ // EVIDENCE staleness, folded into the report (fix round 2, R2-3). Derived from the records
4927
+ // themselves no `codex --version`, no subprocess, so `dz parity` stays a deterministic function
4928
+ // of the model. A cell whose deciding form rests on a transcript that is older than the newest
4929
+ // recording for the SAME target is reported `inconclusive`, never `full`: the round-1 gate could
4930
+ // already tell, and nothing a user runs was asking it.
4931
+ const staleEvidence = findStaleTranscriptEvidence();
4932
+ const staleByTarget = new Map<string, RuntimeCapability[]>();
4933
+ for (const s of staleEvidence) staleByTarget.set(s.target, [...(staleByTarget.get(s.target) ?? []), s.capability]);
4934
+ const reportCell = (feature: ParityFeature, t: TargetName, cell: ParityCell): ParityReportCell =>
4935
+ downgradeForStaleEvidence(feature, cell, staleByTarget.get(t) ?? []);
4936
+ const staleNote = (t: TargetName): string[] =>
4937
+ staleEvidence
4938
+ .filter((s) => s.target === t)
4939
+ .map((s) => ` ⚠ ${s.capability}: evidence recorded on ${s.recordedVersion ?? '(no runtime version recorded)'}, newest recording for this target is ${s.probedVersion ?? '(none)'} — INCONCLUSIVE until re-probed (${s.evidence ?? ''})`);
4940
+ // Site 8 of the D3 rewiring, closed in fix round 1 (QE F1). It shipped spelling its
4941
+ // own bare guard `TARGET_NAMES.includes(...)` and was therefore invisible to the AM-2
4942
+ // grep-guard, which searched for the token `isTargetName(` — a PRESENCE check on one
4943
+ // spelling where the property was "no call site bypasses the resolver". The guard in
4944
+ // `test/target-alias-cli.test.ts` now checks the class, and the sweep list is derived
4945
+ // from the help text so a ninth command cannot be missed the same way.
4946
+ const targetOpt = options.get('target');
4947
+ let target: TargetName | undefined;
4948
+ if (targetOpt !== undefined) {
4949
+ const parityResolution = resolveTargetName(targetOpt);
4950
+ if (parityResolution.kind === 'unknown') {
4951
+ // Both forms go to stderr: an error is not data, and `dz parity --json | jq`
4952
+ // must not be fed a diagnostic (ADR-002 §Decision 2 / driver D6).
4953
+ if (json) {
4954
+ writeErr(JSON.stringify({ error: `unknown target ${JSON.stringify(targetOpt)}`, suggestion: parityResolution.suggestion, targets: TARGET_NAMES_SORTED, exitCode: 1 }, null, 2));
4955
+ } else {
4956
+ for (const line of formatTargetProblem('dz parity', parityResolution)) writeErr(line);
4957
+ }
4958
+ return 1;
4959
+ }
4960
+ target = parityResolution.target;
4961
+ if (parityResolution.via === 'alias') writeErr(formatTargetAliasNote('dz parity', targetOpt, target));
4712
4962
  }
4713
4963
 
4714
4964
  if (json) {
4715
- const rows = matrix.map((r) => ({
4716
- id: r.feature.id,
4717
- title: r.feature.title,
4718
- cells: target !== undefined ? { [target]: r.cells[target as (typeof TARGET_NAMES)[number]] } : r.cells,
4719
- }));
4965
+ const shown = target !== undefined ? [target] : TARGET_NAMES;
4966
+ const rows = matrix.map((r) => {
4967
+ const cells: Record<string, ParityReportCell> = {};
4968
+ for (const t of shown) cells[t] = reportCell(r.feature, t, r.cells[t]);
4969
+ return { id: r.feature.id, title: r.feature.title, cells };
4970
+ });
4720
4971
  // A filtered response stays internally consistent: capabilities are filtered too (Codex QE gap 9).
4721
- const caps = target !== undefined ? { [target]: TARGET_CAPABILITIES[target as (typeof TARGET_NAMES)[number]] } : TARGET_CAPABILITIES;
4722
- write(JSON.stringify({ targets: target !== undefined ? [target] : TARGET_NAMES, capabilities: caps, features: rows }, null, 2));
4972
+ const caps = target !== undefined ? { [target]: TARGET_CAPABILITIES[target] } : TARGET_CAPABILITIES;
4973
+ write(JSON.stringify({
4974
+ targets: shown,
4975
+ capabilities: caps,
4976
+ // The evidence axis travels WITH the matrix: a consumer that reads `level` must be able to
4977
+ // read why a cell is inconclusive without a second command.
4978
+ staleEvidence: staleEvidence.filter((sv) => shown.includes(sv.target)),
4979
+ features: rows,
4980
+ }, null, 2));
4723
4981
  return 0;
4724
4982
  }
4725
4983
 
4726
4984
  if (target !== undefined) {
4727
- const t = target as (typeof TARGET_NAMES)[number];
4985
+ const t = target;
4728
4986
  write(`\ndz parity — ${t} (capabilities: ${TARGET_CAPABILITIES[t].join(', ')})\n`);
4729
4987
  for (const r of matrix) {
4730
- const c = r.cells[t];
4731
- const icon = c.level === 'full' ? '✓' : c.level === 'manual' ? '◐' : '—';
4732
- write(` ${icon} ${r.feature.title.padEnd(58)} ${c.level === 'none' ? 'not available on this target' : `via ${c.via ?? ''}`}`);
4733
- }
4734
- write('\n ✓ full (the complete experience) ◐ manual (works, you drive it by hand) — not available');
4988
+ const c = reportCell(r.feature, t, r.cells[t]);
4989
+ const icon = c.level === 'full' ? '✓' : c.level === 'manual' ? '◐' : c.level === 'inconclusive' ? '?' : '—';
4990
+ const detail = c.level === 'none'
4991
+ ? 'not available on this target'
4992
+ : c.level === 'inconclusive'
4993
+ ? `via ${c.via ?? ''} — INCONCLUSIVE: stale evidence for ${(c.staleEvidence ?? []).join(', ')}`
4994
+ : `via ${c.via ?? ''}`;
4995
+ write(` ${icon} ${r.feature.title.padEnd(58)} ${detail}`);
4996
+ }
4997
+ write('\n ✓ full (the complete experience) ◐ manual (works, you drive it by hand) ? evidence stale (re-probe) — not available');
4998
+ for (const line of staleNote(t)) write(line);
4735
4999
  return 0;
4736
5000
  }
4737
5001
 
@@ -4742,8 +5006,8 @@ function cmdParity(options: Map<string, string>, flags: Set<string>, write: Writ
4742
5006
  write(` ${'feature'.padEnd(52)} ${TARGET_NAMES.map((t) => (short[t] ?? t).padStart(4)).join('')}`);
4743
5007
  for (const r of matrix) {
4744
5008
  const cells = TARGET_NAMES.map((t) => {
4745
- const c = r.cells[t];
4746
- return (c.level === 'full' ? '✓' : c.level === 'manual' ? '◐' : '—').padStart(4);
5009
+ const c = reportCell(r.feature, t, r.cells[t]);
5010
+ return (c.level === 'full' ? '✓' : c.level === 'manual' ? '◐' : c.level === 'inconclusive' ? '?' : '—').padStart(4);
4747
5011
  }).join('');
4748
5012
  write(` ${r.feature.title.slice(0, 52).padEnd(52)} ${cells}`);
4749
5013
  }
@@ -5690,6 +5954,361 @@ function readDriftAllowlist(root: string): string[] {
5690
5954
  }
5691
5955
  }
5692
5956
 
5957
+ /** Refresh or verify the root AGENTS.md bearing-policy projection. */
5958
+ /**
5959
+ * `dz hooks-sync --target codex` (`crossrt-2-codex-hooks`, AM-14).
5960
+ *
5961
+ * ONE verb in the existing target vocabulary (`parity`, `delivery-check`, `--target`), extensible to
5962
+ * a future runtime without a third surface. **No alias** — `dz codex-hooks` resolves to nothing.
5963
+ *
5964
+ * Exit map (ADR-002 §5, pinned by test):
5965
+ * 0 = `armed` AND `trust: 'trusted'` — the ONLY outcome that may print a success word (AM-17)
5966
+ * 1 = not armed, armed-but-trust-pending, drift, or a refusal
5967
+ * 3 = inconclusive (including "no codex binary on PATH")
5968
+ */
5969
+ function cmdHooksSync(
5970
+ options: Map<string, string>,
5971
+ flags: Set<string>,
5972
+ cwd: string,
5973
+ write: Write,
5974
+ writeErr: WriteErr,
5975
+ ): number {
5976
+ const json = flags.has('json');
5977
+ const usage = 'dz hooks-sync --target codex [--check] [--verify] [--remove] [--json] [--project <dir>] [--no-verify]';
5978
+ if (flags.has('help')) {
5979
+ write(`${usage} — install/verify the dz veto + recall hooks in $CODEX_HOME/hooks.json`);
5980
+ return 0;
5981
+ }
5982
+ for (const flag of flags) {
5983
+ if (!['check', 'verify', 'no-verify', 'remove', 'json', 'help'].includes(flag)) {
5984
+ const message = `dz hooks-sync: unknown option --${flag}\n${usage}`;
5985
+ (json ? write : writeErr)(json ? JSON.stringify({ error: `unknown option --${flag}`, exitCode: 1 }) : message);
5986
+ return 1;
5987
+ }
5988
+ }
5989
+ for (const key of options.keys()) {
5990
+ if (key !== 'target' && key !== 'project' && key !== 'codex-home') {
5991
+ const message = key.startsWith('_positional_') ? `unexpected argument ${JSON.stringify(options.get(key))}` : `unknown option --${key}`;
5992
+ (json ? write : writeErr)(json ? JSON.stringify({ error: message, exitCode: 1 }) : `dz hooks-sync: ${message}\n${usage}`);
5993
+ return 1;
5994
+ }
5995
+ }
5996
+ // Every `--target` read in this CLI goes through resolveTargetName (alias support + one spelling
5997
+ // of the unknown-target message), pinned by `everyTargetGuardUsesResolveTargetName`.
5998
+ const targetOpt = options.get('target');
5999
+ if (targetOpt === undefined) {
6000
+ const message = '--target is required';
6001
+ (json ? write : writeErr)(json ? JSON.stringify({ error: message, exitCode: 1 }) : `dz hooks-sync: ${message}\n${usage}`);
6002
+ return 1;
6003
+ }
6004
+ const resolution = resolveTargetName(targetOpt);
6005
+ if (resolution.kind === 'unknown') {
6006
+ if (json) {
6007
+ write(JSON.stringify({ error: `unknown target ${targetOpt}`, exitCode: 1 }));
6008
+ } else {
6009
+ for (const line of formatTargetProblem('dz hooks-sync', resolution)) writeErr(line);
6010
+ }
6011
+ return 1;
6012
+ }
6013
+ const target = resolution.target;
6014
+ if (resolution.via === 'alias') writeErr(formatTargetAliasNote('dz hooks-sync', targetOpt, target));
6015
+ if (target !== 'codex') {
6016
+ // Deliberately narrow: only Codex has a hook carrier today. Naming the reason keeps a future
6017
+ // reader from assuming the other nine are simply unimplemented here.
6018
+ const message = `unsupported --target ${target} (only "codex" has a hook carrier today)`;
6019
+ (json ? write : writeErr)(json ? JSON.stringify({ error: message, exitCode: 1 }) : `dz hooks-sync: ${message}\n${usage}`);
6020
+ return 1;
6021
+ }
6022
+
6023
+ const codexHome = options.get('codex-home');
6024
+ const projectOpt = options.get('project');
6025
+ // `--no-verify` wins over `--verify`: an explicit refusal to measure is never overridden by the
6026
+ // flag that asks for a measurement.
6027
+ const report = runSyncCodexHooksGuarded(
6028
+ codexHooksSyncOptions({
6029
+ ...(codexHome !== undefined ? { codexHome } : {}),
6030
+ ...(projectOpt !== undefined ? { project: resolve(cwd, projectOpt) } : {}),
6031
+ check: flags.has('check'),
6032
+ remove: flags.has('remove'),
6033
+ verify: !flags.has('no-verify'),
6034
+ }),
6035
+ );
6036
+
6037
+ if (json) {
6038
+ write(JSON.stringify({ ...report, exitCode: report.exitCode }));
6039
+ return report.exitCode;
6040
+ }
6041
+
6042
+ for (const err of report.errors) writeErr(`dz hooks-sync: ${err}`);
6043
+ for (const warn of report.warnings) writeErr(`dz hooks-sync: warning: ${warn}`);
6044
+
6045
+ // SILENT in a home that never opted in — the leg-1 F12 lesson: a --check that chatters in every
6046
+ // unrelated project trains its reader to ignore it.
6047
+ if (flags.has('check') && !report.installed && report.errors.length === 0) return report.exitCode;
6048
+
6049
+ if (flags.has('remove')) {
6050
+ write(`dz hooks-sync: removed ${report.removed} managed entr(ies) from ${report.registryPath}`);
6051
+ return report.exitCode;
6052
+ }
6053
+
6054
+ // AM-17 / G-G: the success word is reachable ONLY from `report.ready` — armed AND trusted AND
6055
+ // WITNESSED blocking by a live, non-bypassed probe. The pre-fix version printed it off
6056
+ // `exitCode === 0 && trust && installed`, none of which is evidence that the guard fires.
6057
+ const summary = codexHooksSummary(report);
6058
+ for (const line of summary.stdout) write(line);
6059
+ for (const line of summary.stderr) writeErr(line);
6060
+ return report.exitCode;
6061
+ }
6062
+
6063
+ /* -------------------------------------------------------------------------- */
6064
+ /* Codex hook DELIVERY — one implementation, three call sites */
6065
+ /* -------------------------------------------------------------------------- */
6066
+
6067
+ export interface CodexHooksSyncInput {
6068
+ readonly codexHome?: string | undefined;
6069
+ readonly project?: string | undefined;
6070
+ readonly check?: boolean;
6071
+ readonly remove?: boolean;
6072
+ /** `false` = the user's `--no-verify`. Anything else runs the live probe. */
6073
+ readonly verify?: boolean;
6074
+ }
6075
+
6076
+ /**
6077
+ * The argv → operation mapping, extracted so it can be PINNED.
6078
+ *
6079
+ * It is the mapping that was broken: `--verify`, `--no-verify` and `--project` were parsed,
6080
+ * validated, listed in the usage line — and then never reached `runSyncCodexHooks`, so the CRITICAL
6081
+ * finding (a `ready` with no live proof behind it) lived entirely in three missing object keys.
6082
+ * A function that returns the options object is testable without a codex binary; an inline literal
6083
+ * is not.
6084
+ */
6085
+ export function codexHooksSyncOptions(input: CodexHooksSyncInput): Parameters<typeof runSyncCodexHooks>[0] {
6086
+ return {
6087
+ ...(input.codexHome !== undefined ? { codexHome: input.codexHome } : {}),
6088
+ ...(input.project !== undefined ? { project: input.project } : {}),
6089
+ check: input.check === true,
6090
+ remove: input.remove === true,
6091
+ verify: input.verify !== false,
6092
+ };
6093
+ }
6094
+
6095
+ export interface CodexHooksSummary {
6096
+ readonly ok: boolean;
6097
+ readonly stdout: readonly string[];
6098
+ readonly stderr: readonly string[];
6099
+ }
6100
+
6101
+ /**
6102
+ * What the user is told about a sync report — the ONE place the success word can be printed.
6103
+ *
6104
+ * `report.ready` is the whole gate: installed ∧ executable ∧ trusted ∧ a live, non-bypassed probe
6105
+ * that WITNESSED our block. Nothing else may print "ready" (AM-17 / G-G), and `--no-verify` never
6106
+ * can, because it never measured.
6107
+ */
6108
+ export function codexHooksSummary(report: CodexHooksSyncReport, label = 'dz hooks-sync'): CodexHooksSummary {
6109
+ const stdout: string[] = [];
6110
+ const stderr: string[] = [];
6111
+ if (report.ready) {
6112
+ stdout.push(`${label}: codex hooks installed and ARMED (trust: ${report.trust}) — VERIFIED by a live veto probe — ready`);
6113
+ return { ok: true, stdout, stderr };
6114
+ }
6115
+ if (report.installed) {
6116
+ const verdict = report.verify === null ? 'not verified (no live probe ran)' : `${report.verify.verdict} — ${report.verify.reason}`;
6117
+ // Say what the report ESTABLISHED, not a hopeful summary of it: `installed+trusted` used to
6118
+ // print verbatim even when the same line went on to report `trust: unknown` (the re-QE's
6119
+ // non-closure note). A message that argues with its own parenthesis teaches the reader to skip
6120
+ // the parenthesis.
6121
+ const established = report.trust === 'trusted' ? 'installed+trusted' : `installed, trust ${report.trust}`;
6122
+ stderr.push(`${label}: ${established}, NOT verified — ARMED = NO (trust: ${report.trust}, executable: ${report.executable}, verify: ${verdict})`);
6123
+ stderr.push('→ open an interactive Codex session in this directory, approve the two dz hooks, then re-run `dz hooks-sync --target codex --verify`');
6124
+ } else {
6125
+ stderr.push(`${label}: ARMED = NO — the managed entries are not present in the registry`);
6126
+ }
6127
+ return { ok: false, stdout, stderr };
6128
+ }
6129
+
6130
+ /**
6131
+ * ADR-001 §8: `dz setup` and `dz init --target codex` DELIVER the hooks and verify them.
6132
+ *
6133
+ * Non-aborting by contract (ADR-002 D6): the caller keeps going and folds `ok` into its own exit
6134
+ * code. Before this round no production path called `runSyncCodexHooks` at all — the operation, its
6135
+ * classifier and its exit map existed and were reachable only from the dedicated command
6136
+ * (independent review, finding 2).
6137
+ */
6138
+ /**
6139
+ * Serialize dz's own `hooks.json` read-merge-write behind the `codex-hooks` named lock
6140
+ * (feature qe-bridge-claude, ADR-001 D4-A — the exit condition of the accepted degradation in
6141
+ * `architecture/degradations.md`).
6142
+ *
6143
+ * The lock lives BESIDE the registry it guards (`$CODEX_HOME/.dz/locks/codex-hooks.lock`), not in
6144
+ * this repo: two dz processes running from two different worktrees share a `CODEX_HOME`, not a
6145
+ * project root, so a lock under the project would serialize nothing.
6146
+ *
6147
+ * READ-ONLY runs (`--check`) are NOT locked: they write nothing, and a check that can be blocked by
6148
+ * a writer would be a new failure mode in exchange for no guarantee.
6149
+ *
6150
+ * HONEST LIMIT: this is an ADVISORY lock. It serializes dz-side writers only; a foreign installer
6151
+ * (ruvnet-brain ships its own Codex hooks bundle) never takes it. For that case the pre-existing
6152
+ * mitigations remain the backstop — foreign entries preserved byte-for-byte, a timestamped backup
6153
+ * before every modifying write, and atomic temp+rename so no reader sees a partial file.
6154
+ */
6155
+ function runSyncCodexHooksLocked(options: Parameters<typeof runSyncCodexHooks>[0] = {}): CodexHooksSyncReport {
6156
+ if (options?.check === true) return runSyncCodexHooks(options);
6157
+ const codexHome = resolveCodexHome(options?.codexHome);
6158
+ // AM-35a is a SHIPPED property with a test: a run that refuses (no `codex` on PATH) must leave
6159
+ // CODEX_HOME untouched — dz does not create user-global state for a runtime that is not there.
6160
+ // Taking the lock creates `<codexHome>/.dz/locks/`, so when the guarded operation turned out to
6161
+ // write nothing, the lock scaffolding is removed again (empty-dir removals only: a directory that
6162
+ // still holds another process's live lock simply refuses to go).
6163
+ const preexisting = existsSync(join(codexHome, '.dz'));
6164
+ const tidyLockScaffold = (report: CodexHooksSyncReport): void => {
6165
+ if (preexisting || report.written || report.writes.length > 0) return;
6166
+ for (const dir of [join(codexHome, '.dz', 'locks'), join(codexHome, '.dz')]) {
6167
+ try {
6168
+ rmdirSync(dir);
6169
+ } catch { /* non-empty (someone else's lock) or gone — leave it */ }
6170
+ }
6171
+ };
6172
+ // ROUND-2 C2: the lock now wraps ONLY the registry read-plan-write transaction, passed in as the
6173
+ // operation's `criticalSection` seam. It used to wrap the WHOLE operation, including a live veto
6174
+ // probe that can block for ~300s — ten times the 30s stale threshold, after which a waiter is
6175
+ // entitled to break the lock and the holder is no longer excluding anyone. The probes mutate
6176
+ // nothing shared, so they run unlocked by design.
6177
+ let lockError: Error | null = null;
6178
+ const report = runSyncCodexHooks({
6179
+ ...options,
6180
+ criticalSection: <T>(fn: () => T): T => {
6181
+ try {
6182
+ return withNamedLockSync(codexHome, 'codex-hooks', fn);
6183
+ } catch (error) {
6184
+ if (error instanceof NamedLockTimeoutError || error instanceof NamedLockCompromisedError) {
6185
+ lockError = error;
6186
+ throw error;
6187
+ }
6188
+ throw error;
6189
+ }
6190
+ },
6191
+ });
6192
+ tidyLockScaffold(report);
6193
+ if (lockError !== null) throw lockError;
6194
+ return report;
6195
+ }
6196
+
6197
+ /** Wrap the delivery so a lock refusal becomes a REPORT (loud, nothing written), not a stack trace. */
6198
+ function runSyncCodexHooksGuarded(options: Parameters<typeof runSyncCodexHooks>[0] = {}): CodexHooksSyncReport {
6199
+ const codexHome = resolveCodexHome(options?.codexHome);
6200
+ try {
6201
+ return runSyncCodexHooksLocked(options);
6202
+ } catch (error) {
6203
+ if (error instanceof NamedLockTimeoutError || error instanceof NamedLockCompromisedError) {
6204
+ const why = error instanceof NamedLockTimeoutError
6205
+ ? `another dz process is writing ${join(codexHome, 'hooks.json')} (${error.message}) — NOTHING was written; retry once it finishes`
6206
+ : `the codex-hooks lock was broken while this run held it (${error.message}) — the registry write may have raced; re-run and re-verify`;
6207
+ return {
6208
+ codexHome,
6209
+ registryPath: join(codexHome, 'hooks.json'),
6210
+ installed: false,
6211
+ executable: false,
6212
+ written: false,
6213
+ removed: 0,
6214
+ foreignPreserved: 0,
6215
+ unattributable: 0,
6216
+ drift: [],
6217
+ trust: 'unknown',
6218
+ codexVersion: null,
6219
+ writes: [],
6220
+ verify: null,
6221
+ verified: false,
6222
+ ready: false,
6223
+ exitCode: 1,
6224
+ warnings: [],
6225
+ errors: [why],
6226
+ };
6227
+ }
6228
+ throw error;
6229
+ }
6230
+ }
6231
+
6232
+ export function deliverCodexHooks(
6233
+ input: CodexHooksSyncInput,
6234
+ sync: (options: Parameters<typeof runSyncCodexHooks>[0]) => CodexHooksSyncReport = runSyncCodexHooksGuarded,
6235
+ label = 'dz setup',
6236
+ ): CodexHooksSummary & { readonly report: CodexHooksSyncReport } {
6237
+ const report = sync(codexHooksSyncOptions(input));
6238
+ const summary = codexHooksSummary(report, label);
6239
+ const stderr = [...report.errors.map((e) => `${label}: ${e}`), ...report.warnings.map((w) => `${label}: warning: ${w}`), ...summary.stderr];
6240
+ return { ok: summary.ok, stdout: summary.stdout, stderr, report };
6241
+ }
6242
+
6243
+ function cmdAgentsSync(
6244
+ options: Map<string, string>,
6245
+ flags: Set<string>,
6246
+ cwd: string,
6247
+ write: Write,
6248
+ writeErr: WriteErr,
6249
+ ): number {
6250
+ const json = flags.has('json');
6251
+ const usage = 'dz agents-sync [--project <dir>] [--check] [--json]';
6252
+ if (flags.has('help')) {
6253
+ write(`${usage} — sync/verify the dz:policies fence in root AGENTS.md`);
6254
+ return 0;
6255
+ }
6256
+ for (const flag of flags) {
6257
+ if (!['check', 'json', 'help'].includes(flag)) {
6258
+ const message = `dz agents-sync: unknown option --${flag}\n${usage}`;
6259
+ (json ? write : writeErr)(json ? JSON.stringify({ error: `unknown option --${flag}`, exitCode: 1 }) : message);
6260
+ return 1;
6261
+ }
6262
+ }
6263
+ for (const key of options.keys()) {
6264
+ if (key !== 'project') {
6265
+ const message = key.startsWith('_positional_') ? `unexpected argument ${JSON.stringify(options.get(key))}` : `unknown option --${key}`;
6266
+ (json ? write : writeErr)(json ? JSON.stringify({ error: message, exitCode: 1 }) : `dz agents-sync: ${message}\n${usage}`);
6267
+ return 1;
6268
+ }
6269
+ }
6270
+
6271
+ const root = resolve(cwd, options.get('project') ?? '.');
6272
+ try {
6273
+ const report = runSyncAgentsPolicy({ projectRoot: root, check: flags.has('check') });
6274
+ const drifted = report.drift.filter((finding) => finding.status !== 'ok');
6275
+ const inconclusive = report.missing.length > 0;
6276
+ const failed = flags.has('check')
6277
+ ? report.changed || report.budget.overflow || drifted.length > 0
6278
+ : !report.inSync;
6279
+ const exitCode = inconclusive ? 3 : failed ? 1 : 0;
6280
+ if (json) {
6281
+ write(JSON.stringify({ ...report, sections: report.blocks, exitCode }));
6282
+ return exitCode;
6283
+ }
6284
+ if (inconclusive) {
6285
+ writeErr(`dz agents-sync: INCONCLUSIVE — unreadable or unanchored policy source(s): ${report.missing.join(', ')}`);
6286
+ writeErr('→ heal with: restore the named source anchors, then run dz agents-sync');
6287
+ return 3;
6288
+ }
6289
+ if (failed) {
6290
+ const effect = flags.has('check') ? 'AGENTS.md would change' : 'AGENTS.md was not rewritten';
6291
+ writeErr(`dz agents-sync: DRIFT — ${drifted.length} stale/missing section(s); ${effect}`);
6292
+ for (const finding of drifted) writeErr(` ${finding.id}: ${finding.file} (${finding.status})`);
6293
+ if (drifted.some((finding) => finding.id === 'dz:policies')) {
6294
+ writeErr('→ heal with: repair duplicate/unmatched dz:policies markers, then run dz agents-sync');
6295
+ } else {
6296
+ writeErr('→ heal with: dz agents-sync');
6297
+ }
6298
+ return 1;
6299
+ }
6300
+ const verb = report.written ? 'wrote' : 'in sync';
6301
+ write(`dz agents-sync: ${verb} — ${report.blocks.length} policy section(s), ${report.budget.bytes} bytes (${report.budget.pct}% of ${report.budget.cap})`);
6302
+ for (const warning of report.warnings) writeErr(`dz agents-sync: warning: ${warning}`);
6303
+ return 0;
6304
+ } catch (error) {
6305
+ const message = error instanceof Error ? error.message : String(error);
6306
+ if (json) write(JSON.stringify({ error: message, exitCode: 1 }));
6307
+ else writeErr(`dz agents-sync: ${message}`);
6308
+ return 1;
6309
+ }
6310
+ }
6311
+
5693
6312
  function cmdDriftCheck(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
5694
6313
  const root = resolve(cwd, options.get('project') ?? '.');
5695
6314
  // Default scope = PUBLISHED packages only: the `.claude/skills` dogfood copies legitimately lag the
@@ -5803,6 +6422,31 @@ function gatherReadmeCounts(root: string): { label: string; a: number; b: number
5803
6422
  function gatherGuardFacts(op: string, root: string, text: string | undefined, storeCap: number): Record<string, unknown> {
5804
6423
  const facts: Record<string, unknown> = { op };
5805
6424
  if (op === 'publish') {
6425
+ // agents-md-policy-sync: fixed registry, no tree walk. The pure detector
6426
+ // recomputes every expected hash from current source text; this gatherer
6427
+ // only supplies bytes. Any unexpected gather failure omits the fact, and
6428
+ // evaluateGuard records that advisory coverage gap in `notes`.
6429
+ try {
6430
+ const policyFiles = new Map<string, string | null>();
6431
+ for (const file of new Set(POLICY_SOURCES.map((source) => source.file))) {
6432
+ try { policyFiles.set(file, readFileSync(join(root, file), 'utf8')); }
6433
+ catch { policyFiles.set(file, null); }
6434
+ }
6435
+ let agentsMd: string | null = null;
6436
+ try { agentsMd = readFileSync(join(root, 'AGENTS.md'), 'utf8'); } catch { /* missing stamp evidence */ }
6437
+ const policyDrift = detectPolicyDrift(policyFiles, agentsMd, POLICY_SOURCES);
6438
+ facts['policyDrift'] = {
6439
+ applicable: policyDrift.applicable,
6440
+ // Did this repo OPT IN? A `dz:policies` fence in AGENTS.md is the only durable signal that
6441
+ // someone ran `dz agents-sync` here. Without it the advisory rule is out of scope and stays
6442
+ // silent; with it, unreadable sources become a loud note instead of a silent skip.
6443
+ fenced: hasPolicyFence(agentsMd),
6444
+ drifted: policyDrift.findings
6445
+ .filter((finding) => finding.status !== 'ok')
6446
+ .map((finding) => `${finding.id}:${finding.file}:${finding.status}`),
6447
+ };
6448
+ } catch { /* unexpected gather failure — omission becomes a visible guard note */ }
6449
+
5806
6450
  // Read every workspace manifest ONCE: build a name→version map, then resolve each `workspace:*` dep to the
5807
6451
  // version pnpm WOULD publish it as. In a pnpm workspace (pnpm-workspace.yaml present) `workspace:*` in source
5808
6452
  // is correct and gets rewritten at publish — so reporting it raw would be a FALSE gate. We mirror the rewrite:
@@ -6837,7 +7481,7 @@ async function cmdRetro(options: Map<string, string>, flags: Set<string>, cwd: s
6837
7481
  * --from-spec <spec.json> preview the scaffold (create / augment per file); the SKILL fills the spec
6838
7482
  * --apply with --from-spec: WRITE (create missing, AUGMENT existing — never clobber)
6839
7483
  */
6840
- function cmdFeatureAdrSetup(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
7484
+ function cmdFeatureAdrSetup(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr): number {
6841
7485
  let repoRoot = cwd;
6842
7486
  try { repoRoot = execSync('git rev-parse --show-toplevel', { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; } catch { /* not git */ }
6843
7487
 
@@ -6856,11 +7500,24 @@ function cmdFeatureAdrSetup(options: Map<string, string>, flags: Set<string>, cw
6856
7500
  // Its "runnable here" list is computed for --target (default agents-md, the AGENTS.md-class target class).
6857
7501
  const wantGates = flags.has('gates');
6858
7502
  const targetOpt = options.get('target');
6859
- if (targetOpt !== undefined && !isTargetName(targetOpt)) {
6860
- write(`dz feature-adr-setup: --target must be one of: ${TARGET_NAMES.join(', ')}`);
6861
- return 1;
7503
+ // Sites 7 AND 8 of the D3 rewiring. Site 8 (the coercion below) is NOT a guard — it
7504
+ // is a silent fallback, and a mechanical "replace isTargetName with resolveTargetName"
7505
+ // pass would miss it. With aliasing in place and the coercion left alone,
7506
+ // `dz feature-adr-setup --gates --target claude` would pass validation and then emit
7507
+ // for **agents-md**. So the coercion CONSUMES the resolution computed once, above;
7508
+ // `agents-md` is the default only when `--target` is ABSENT.
7509
+ let gatesTarget: TargetName = 'agents-md';
7510
+ if (targetOpt !== undefined) {
7511
+ const gatesResolution = resolveTargetName(targetOpt);
7512
+ if (gatesResolution.kind === 'unknown') {
7513
+ for (const line of formatTargetProblem('dz feature-adr-setup', gatesResolution)) writeErr(line);
7514
+ return 1;
7515
+ }
7516
+ gatesTarget = gatesResolution.target;
7517
+ if (gatesResolution.via === 'alias') {
7518
+ writeErr(formatTargetAliasNote('dz feature-adr-setup', targetOpt, gatesTarget));
7519
+ }
6862
7520
  }
6863
- const gatesTarget: TargetName = isTargetName(targetOpt ?? '') ? (targetOpt as TargetName) : 'agents-md';
6864
7521
 
6865
7522
  const specPath = options.get('from-spec');
6866
7523
  if (specPath === undefined && !wantGuards && !wantGates) {
@@ -6976,7 +7633,15 @@ function cmdChallenge(options: Map<string, string>, flags: Set<string>, cwd: str
6976
7633
  * --base <ref> the base ref to fail against (default HEAD)
6977
7634
  * --name '<filter>' optional -t test-name filter applied to every target
6978
7635
  * --runner '<cmd>' test runner (default `npx vitest run`)
6979
- * --json machine-readable {plan, results, verdict, finding}
7636
+ * --timeout <ms> per-run timeout (default 300000; a timed-out run is CANNOT_ISOLATE)
7637
+ * --json machine-readable {plan, results, tipTree, perTest, aggregate,
7638
+ * findings, measurementValid, primaryAction}
7639
+ *
7640
+ * This executor is THIN by design (house style: pure classifier + thin executor). It performs exactly the
7641
+ * I/O the pure gate cannot — stat, worktree, run, capture — and hands OBSERVATIONS back. It no longer
7642
+ * interprets anything: the pre-epoch load-error regex that lived here (`/cannot find module|failed to
7643
+ * load|.../i`) is DELETED, because a regex over a runner's stderr, written in the executor, is exactly the
7644
+ * probabilistic channel that minted `DISCRIMINATES` for `--runner false`.
6980
7645
  *
6981
7646
  * NEVER auto-aborts: a non-discriminating (false-green) test is reported as a HIGH finding for the owner to
6982
7647
  * decide (dz's rule — a false gate kills trust). Exit code is 0 on a clean run regardless of verdict; 2 only on
@@ -6996,6 +7661,9 @@ function cmdDiscriminationCheck(options: Map<string, string>, flags: Set<string>
6996
7661
  nameFilter !== undefined && nameFilter.trim() !== '' ? { file, name: nameFilter.trim() } : { file });
6997
7662
  const baseRef = options.get('base') ?? 'HEAD';
6998
7663
  const runnerOpt = options.get('runner');
7664
+ // R11: a hung runner is a loud non-answer, never a pass. Same default + parse shape as mutation-gate.
7665
+ const timeoutOpt = Number(options.get('timeout') ?? '300000');
7666
+ const timeoutMs = Number.isFinite(timeoutOpt) && timeoutOpt > 0 ? timeoutOpt : 300000;
6999
7667
 
7000
7668
  const plan = planDiscriminationCheck(runnerOpt !== undefined ? { baseRef, propertyTests, runner: runnerOpt } : { baseRef, propertyTests });
7001
7669
 
@@ -7009,82 +7677,186 @@ function cmdDiscriminationCheck(options: Map<string, string>, flags: Set<string>
7009
7677
  return 0;
7010
7678
  }
7011
7679
 
7012
- // Execute the plan in a temp worktree WE own; substitute {{WORKTREE}} and always clean up.
7013
- // `git worktree add` must CREATE the path, so compute a fresh non-existent one (do NOT mkdtemp it).
7014
- const worktree = join(mkdtempSync(join(tmpdir(), 'dz-disc-')), 'wt');
7015
- const results: { file: string; name?: string; outcome: 'pass' | 'fail' | 'error' }[] = [];
7016
- try {
7017
- // 1) add the detached worktree at base (git creates `worktree`; its parent already exists).
7018
- const addCmd = plan.commands[0]!.replace(/\{\{WORKTREE\}\}/g, worktree);
7019
- execSync(addCmd, { cwd: repoRoot, stdio: 'pipe', encoding: 'utf-8' });
7020
-
7021
- // 1b) a fresh worktree has NO node_modules — without this, every test fails to load (runner + deps
7022
- // unresolvable) and the gate collapses to always-VIA_ERROR, blind to false greens. Absolute-path
7023
- // symlinks point back at the main checkout's already-installed trees, robust across pnpm's layout.
7024
- const linkNodeModules = (relDir: string): void => {
7025
- const srcNm = join(repoRoot, relDir, 'node_modules');
7026
- if (!existsSync(srcNm)) return;
7027
- const dstNm = join(worktree, relDir, 'node_modules');
7028
- if (existsSync(dstNm)) return;
7029
- try { mkdirSync(dirname(dstNm), { recursive: true }); symlinkSync(srcNm, dstNm, 'dir'); } catch { /* best effort */ }
7030
- };
7031
- linkNodeModules('.'); // root (hoisted deps + .bin)
7032
- const pkgDirs = new Set<string>();
7033
- for (const t of plan.targets) {
7034
- let d = dirname(t.file);
7035
- while (d && d !== '.' && d !== sep) {
7036
- if (existsSync(join(repoRoot, d, 'package.json'))) { pkgDirs.add(d); break; }
7037
- d = dirname(d);
7680
+ // ── (1) stat + isFile, BEFORE the worktree (AM-6 / FR-A1) ──────────────────────────────────
7681
+ // R12: `stat` FOLLOWS symlinks on purpose. A dangling symlink lstat-exists but has no readable
7682
+ // content that IS absence of the named check. A directory stat-exists but is not a regular
7683
+ // file. Pre-epoch both reached the copy step, threw, and were caught into `outcome:'error'`,
7684
+ // which minted the near-pass DISCRIMINATES_VIA_ERROR (MEASURED — acid A1 / the dangling-symlink
7685
+ // and directory rows of features/wave1-instrument-repair/07_code_changes/acid-red-runs.md).
7686
+ const absent: { file: string; name?: string; outcome: 'absent'; evidence?: ExecutionEvidence }[] = [];
7687
+ const present: { file: string; name?: string }[] = [];
7688
+ for (const t of plan.targets) {
7689
+ let isRegular = false;
7690
+ let isDirectory = false;
7691
+ try {
7692
+ const st = statSync(resolve(repoRoot, t.file));
7693
+ isRegular = st.isFile();
7694
+ isDirectory = st.isDirectory();
7695
+ } catch { /* ENOENT / dangling symlink / permission — absence, either way */ }
7696
+ if (isRegular) { present.push(t.name !== undefined ? { file: t.file, name: t.name } : { file: t.file }); continue; }
7697
+ const row = t.name !== undefined ? { file: t.file, name: t.name, outcome: 'absent' as const } : { file: t.file, outcome: 'absent' as const };
7698
+ // Out-of-band detail channel: TEST_FILE_ABSENT is evidence-EXEMPT (its evidence is the stat
7699
+ // itself), and absent rows never consult the evidence gate — so this object cannot degrade the
7700
+ // row. It exists only so the finding can tell the operator WHY the path is not a test file.
7701
+ absent.push(isDirectory
7702
+ ? { ...row, evidence: { exitCode: null, runner: 'unrecognised', failureKind: 'unrecognised', testsExecuted: null, targetSeen: false, evidenceLine: 'not-a-regular-file' } }
7703
+ : row);
7704
+ }
7705
+
7706
+ const results: ClassifyResultRow[] = [...absent];
7707
+ let tipTree: { headSha: string; dirtyFiles: number } | null = null;
7708
+
7709
+ // Confirmation 12: with nothing present there is nothing to run — no worktree is built at all.
7710
+ if (present.length > 0) {
7711
+ const runner = runnerOpt !== undefined && plan.commands.some((c) => c.includes(runnerOpt)) ? runnerOpt : 'npx vitest run';
7712
+ // Execute the plan in a temp worktree WE own; substitute {{WORKTREE}} and always clean up.
7713
+ // `git worktree add` must CREATE the path, so compute a fresh non-existent one (do NOT mkdtemp it).
7714
+ const worktree = join(mkdtempSync(join(tmpdir(), 'dz-disc-')), 'wt');
7715
+ try {
7716
+ // 1) add the detached worktree at base (git creates `worktree`; its parent already exists).
7717
+ const addCmd = plan.commands[0]!.replace(/\{\{WORKTREE\}\}/g, worktree);
7718
+ execSync(addCmd, { cwd: repoRoot, stdio: 'pipe', encoding: 'utf-8' });
7719
+
7720
+ // 1b) a fresh worktree has NO node_modules — without this, every test fails to load (runner + deps
7721
+ // unresolvable) and the gate collapses to always-VIA_ERROR, blind to false greens. Absolute-path
7722
+ // symlinks point back at the main checkout's already-installed trees, robust across pnpm's layout.
7723
+ const linkNodeModules = (relDir: string): void => {
7724
+ const srcNm = join(repoRoot, relDir, 'node_modules');
7725
+ if (!existsSync(srcNm)) return;
7726
+ const dstNm = join(worktree, relDir, 'node_modules');
7727
+ if (existsSync(dstNm)) return;
7728
+ try { mkdirSync(dirname(dstNm), { recursive: true }); symlinkSync(srcNm, dstNm, 'dir'); } catch { /* best effort */ }
7729
+ };
7730
+ linkNodeModules('.'); // root (hoisted deps + .bin)
7731
+ const pkgDirs = new Set<string>();
7732
+ for (const t of present) {
7733
+ let d = dirname(t.file);
7734
+ while (d && d !== '.' && d !== sep) {
7735
+ if (existsSync(join(repoRoot, d, 'package.json'))) { pkgDirs.add(d); break; }
7736
+ d = dirname(d);
7737
+ }
7038
7738
  }
7039
- }
7040
- for (const d of pkgDirs) linkNodeModules(d);
7739
+ for (const d of pkgDirs) linkNodeModules(d);
7041
7740
 
7042
- // 2) copy each property test into the base worktree, then 3) run it and record pass/fail/error per target.
7043
- for (const t of plan.targets) {
7044
- try {
7045
- const src = resolve(repoRoot, t.file);
7046
- // containment guard (defense in depth beyond planDiscriminationCheck's path sanitation).
7047
- if (!resolve(src).startsWith(resolve(repoRoot) + sep)) { results.push(nameFor(t, 'error')); continue; }
7048
- const dst = join(worktree, t.file);
7049
- mkdirSync(dirname(dst), { recursive: true });
7050
- writeFileSync(dst, readFileSync(src));
7051
- } catch { results.push(nameFor(t, 'error')); continue; }
7052
-
7053
- const runner = (runnerOpt !== undefined && plan.commands.some((c) => c.includes(runnerOpt))) ? runnerOpt : 'npx vitest run';
7054
- // t.file + t.name already passed the engine's strict sanitation (no quotes/metacharacters/leading-dash);
7055
- // still quote + `--` so a path can never be read as a runner option or split a word.
7056
- const nameArg = t.name ? ` -t '${t.name}'` : '';
7057
- try {
7058
- execSync(`${runner}${nameArg} -- '${t.file}'`, { cwd: worktree, stdio: 'pipe', encoding: 'utf-8' });
7059
- results.push(nameFor(t, 'pass')); // exit 0 test PASSED at base false green
7060
- } catch (e) {
7061
- // vitest exits non-zero on failure AND on load/compile error. Distinguish: a load error usually names
7062
- // "Cannot find module"/"Failed to load"/"No test files"; otherwise treat as an assertion failure (red).
7063
- const out = String((e as { stdout?: string; stderr?: string }).stdout ?? '') + String((e as { stderr?: string }).stderr ?? '');
7064
- const isLoadError = /cannot find module|failed to load|no test (files )?found|error: cannot|transform failed|esbuild/i.test(out);
7065
- results.push(nameFor(t, isLoadError ? 'error' : 'fail'));
7741
+ // 2) copy each property test into the base worktree, then 3) run it and record the OBSERVATION.
7742
+ for (const t of present) {
7743
+ try {
7744
+ const src = resolve(repoRoot, t.file);
7745
+ // containment guard (defense in depth beyond planDiscriminationCheck's path sanitation).
7746
+ if (!resolve(src).startsWith(resolve(repoRoot) + sep)) { results.push(nameFor(t, 'error')); continue; }
7747
+ const dst = join(worktree, t.file);
7748
+ mkdirSync(dirname(dst), { recursive: true });
7749
+ writeFileSync(dst, readFileSync(src));
7750
+ } catch {
7751
+ // the file STAT-PASSED and the copy still failed: degrade LOUDLY as an error with NO
7752
+ // evidence (the gate reads it as CANNOT_ISOLATE), never as absence and never as a pass.
7753
+ results.push(nameFor(t, 'error'));
7754
+ continue;
7755
+ }
7756
+
7757
+ // t.file + t.name already passed the engine's strict sanitation (no quotes/metacharacters/leading-dash);
7758
+ // still quote + `--` so a path can never be read as a runner option or split a word.
7759
+ const nameArg = t.name ? ` -t '${t.name}'` : '';
7760
+ const cmd = `${runner}${nameArg} -- '${t.file}'`;
7761
+ const base = runCapturedTest(cmd, worktree, timeoutMs);
7762
+ const evidence = classifyExecutionEvidence(base.output, base.exitCode, t.file);
7763
+ const outcome = discriminationOutcomeOf(base.exitCode, evidence);
7764
+ const row: Record<string, unknown> = t.name !== undefined
7765
+ ? { file: t.file, name: t.name, outcome, evidence }
7766
+ : { file: t.file, outcome, evidence };
7767
+
7768
+ // 4) TIP CONTROL (FR-A2 + Confirmation 17). Run it for ALL non-assertion redness — file-load
7769
+ // redness (the matrix's EVIDENCED-error rows) AND unrecognised redness (so the invocation
7770
+ // ledger can prove the tip was REACHED). The CLASSIFIER still ignores the tip for unevidenced
7771
+ // base rows per the matrix; running it is cheap and only ever on an already-broken path.
7772
+ // Do NOT "simplify" this to evidenced-error-only — that silently breaks Confirmation 17.
7773
+ if (base.exitCode !== null && base.exitCode !== 0 && evidence.failureKind !== 'assertions') {
7774
+ const tip = runCapturedTest(cmd, repoRoot, timeoutMs);
7775
+ const tipEvidence = classifyExecutionEvidence(tip.output, tip.exitCode, t.file);
7776
+ row['tipOutcome'] = discriminationOutcomeOf(tip.exitCode, tipEvidence);
7777
+ row['tipEvidence'] = tipEvidence;
7778
+ // R15, named honestly: the base run is isolated in a worktree, but the tip runs in the LIVE
7779
+ // tree, where a concurrent writer can flip the observation mid-gate. No lock is taken
7780
+ // (deferred to backlog 9520e506); instead every tip-derived reading carries the tree
7781
+ // CONDITIONS it was taken under, so a surprising verdict can be re-read against them.
7782
+ if (tipTree === null) tipTree = readTipTreeConditions(repoRoot);
7783
+ }
7784
+ results.push(row as unknown as ClassifyResultRow);
7066
7785
  }
7786
+ } catch (e) {
7787
+ if (flags.has('json')) { write(JSON.stringify({ plan, error: 'worktree-setup-failed', detail: String((e as Error).message).slice(0, 300) }, null, 2)); }
7788
+ else write(`discrimination-check: could not create worktree at ${baseRef}: ${String((e as Error).message).slice(0, 200)}`);
7789
+ return 2;
7790
+ } finally {
7791
+ try { execSync(`git worktree remove --force ${worktree}`, { cwd: repoRoot, stdio: 'pipe' }); } catch { /* fall through to rm */ }
7792
+ // remove the whole mkdtemp parent (worktree is `<mkdtemp>/wt`), so nothing leaks under tmp even on error.
7793
+ try { rmSync(dirname(worktree), { recursive: true, force: true }); } catch { /* best effort */ }
7794
+ try { execSync('git worktree prune', { cwd: repoRoot, stdio: 'pipe' }); } catch { /* best effort */ }
7067
7795
  }
7068
- } catch (e) {
7069
- if (flags.has('json')) { write(JSON.stringify({ plan, error: 'worktree-setup-failed', detail: String((e as Error).message).slice(0, 300) }, null, 2)); }
7070
- else write(`discrimination-check: could not create worktree at ${baseRef}: ${String((e as Error).message).slice(0, 200)}`);
7071
- return 2;
7072
- } finally {
7073
- try { execSync(`git worktree remove --force ${worktree}`, { cwd: repoRoot, stdio: 'pipe' }); } catch { /* fall through to rm */ }
7074
- // remove the whole mkdtemp parent (worktree is `<mkdtemp>/wt`), so nothing leaks under tmp even on error.
7075
- try { rmSync(dirname(worktree), { recursive: true, force: true }); } catch { /* best effort */ }
7076
- try { execSync('git worktree prune', { cwd: repoRoot, stdio: 'pipe' }); } catch { /* best effort */ }
7077
7796
  }
7078
7797
 
7079
7798
  const result = classifyDiscrimination({ propertyTests, results });
7080
- if (flags.has('json')) { write(JSON.stringify({ plan, results, ...result }, null, 2)); return 0; }
7799
+ if (flags.has('json')) { write(JSON.stringify({ plan, results, tipTree, ...result }, null, 2)); return 0; }
7081
7800
 
7082
7801
  write(`discrimination-check @ ${baseRef} — verdict: ${result.aggregate}`);
7083
- for (const p of result.perTest) write(` ${p.verdict === 'NON_DISCRIMINATING' ? '✗' : '✓'} ${p.file}${p.name ? ` (${p.name})` : ''}: ${p.verdict}`);
7084
- if (result.finding) write(`\n [${result.finding.severity}] ${result.finding.title}\n ${result.finding.detail}`);
7802
+ for (const p of result.perTest) {
7803
+ // FR-A6: ✓ is reserved for the two ESTABLISHED trust verdicts. Every other value — including
7804
+ // every degraded reading — renders ✗, because a ✗ the operator investigates beats a ✓ that
7805
+ // silently meant "we could not tell".
7806
+ const mark = p.verdict === 'DISCRIMINATES' || p.verdict === 'DISCRIMINATES_VIA_ERROR' ? '✓' : '✗';
7807
+ write(` ${mark} ${p.file}${p.name ? ` (${p.name})` : ''}: ${p.verdict}${p.reason ? ` (reason: ${p.reason})` : ''}`);
7808
+ }
7809
+ write(` measurementValid: ${String(result.measurementValid)} · primaryAction: ${result.primaryAction}`);
7810
+ // ALL findings print, not just the worst: the scalar aggregate names one state, and a corpus with
7811
+ // a false green AND an absent file has two problems, each with its own operator action.
7812
+ for (const f of result.findings) write(`\n [${f.severity}] ${f.title}\n ${f.detail}`);
7085
7813
  return 0;
7086
7814
  }
7087
7815
 
7816
+ /**
7817
+ * Run one test command and CAPTURE the observation — output plus the exit code, including the
7818
+ * "no exit code at all" case. `execSync`'s timeout kills the child via signal and leaves
7819
+ * `status` null; a spawn failure does the same. That null is not an error to swallow, it is the
7820
+ * evidence (`CANNOT_ISOLATE` reason `'timeout'`), so it is returned as data.
7821
+ */
7822
+ function runCapturedTest(cmd: string, cwd: string, timeoutMs: number): { output: string; exitCode: number | null } {
7823
+ try {
7824
+ const stdout = execSync(cmd, { cwd, stdio: 'pipe', encoding: 'utf-8', timeout: timeoutMs });
7825
+ return { output: String(stdout ?? ''), exitCode: 0 };
7826
+ } catch (e) {
7827
+ const err = e as { stdout?: string; stderr?: string; status?: unknown };
7828
+ return {
7829
+ output: String(err.stdout ?? '') + String(err.stderr ?? ''),
7830
+ exitCode: typeof err.status === 'number' ? err.status : null,
7831
+ };
7832
+ }
7833
+ }
7834
+
7835
+ /**
7836
+ * The outcome VALUE for one captured run. The executor's whole remaining judgment, and it is
7837
+ * mechanical: exit 0 is a pass, no exit code is an error, and a non-zero exit is an error only when
7838
+ * the classifier RECOGNISED a file-load failure. An unrecognised red is deliberately recorded as a
7839
+ * `fail` VALUE whose evidence then degrades it — exactly acid A6's pinned shape, and the reason the
7840
+ * executor no longer owns a regex.
7841
+ */
7842
+ function discriminationOutcomeOf(exitCode: number | null, evidence: ExecutionEvidence): 'pass' | 'fail' | 'error' {
7843
+ if (exitCode === null) return 'error';
7844
+ if (exitCode === 0) return 'pass';
7845
+ return evidence.failureKind === 'file-load' ? 'error' : 'fail';
7846
+ }
7847
+
7848
+ /** The live tree's identity at tip-run time (R15). Best-effort: unknown conditions read as such. */
7849
+ function readTipTreeConditions(repoRoot: string): { headSha: string; dirtyFiles: number } {
7850
+ let headSha = 'unknown';
7851
+ let dirtyFiles = -1;
7852
+ try { headSha = execSync('git rev-parse HEAD', { cwd: repoRoot, stdio: 'pipe', encoding: 'utf-8' }).trim(); } catch { /* best effort */ }
7853
+ try {
7854
+ const porcelain = execSync('git status --porcelain', { cwd: repoRoot, stdio: 'pipe', encoding: 'utf-8' });
7855
+ dirtyFiles = String(porcelain).split('\n').filter((l) => l.trim() !== '').length;
7856
+ } catch { /* best effort */ }
7857
+ return { headSha, dirtyFiles };
7858
+ }
7859
+
7088
7860
  /** small helper: build a result row, omitting `name` when absent (exactOptionalPropertyTypes). */
7089
7861
  function nameFor(t: { file: string; name?: string }, outcome: 'pass' | 'fail' | 'error'): { file: string; name?: string; outcome: 'pass' | 'fail' | 'error' } {
7090
7862
  return t.name !== undefined ? { file: t.file, name: t.name, outcome } : { file: t.file, outcome };
@@ -7459,47 +8231,630 @@ function cmdMutationGate(options: Map<string, string>, flags: Set<string>, cwd:
7459
8231
  * debt); an oversized or non-regular due-file counts as MALFORMED, never a silent skip (QE #8);
7460
8232
  * a debt whose embedded slug differs from its directory is MALFORMED — identity is the directory,
7461
8233
  * the JSON only confirms it (QE #4: an embedded foreign slug must not redirect settlement). */
7462
- function scanReqeDebts(root: string): { debts: Array<{ debt: ReqeDebt; duePath: string; dir: string }>; malformed: number } {
7463
- const out: Array<{ debt: ReqeDebt; duePath: string; dir: string }> = [];
7464
- let malformed = 0;
7465
- const featuresDir = join(root, 'features');
7466
- let slugs: string[] = [];
8234
+ /* ── `dz workflow run` the impure half of the loop-plan executor (feature dz-workflow-run) ──────
8235
+ *
8236
+ * Everything DECIDABLE lives in harness-core's pure scheduler. This half owns exactly four things
8237
+ * core refuses to touch: the filesystem, the lock, the child processes, and the exit code. Keeping
8238
+ * that line sharp is what lets the whole feature be tested without a child process — so anything
8239
+ * added here that could have been a decision belongs upstream instead.
8240
+ */
8241
+
8242
+ /** The env TEST SEAM (the `DZ_QE_BRIDGE_CLAUDE_BIN` precedent: an env var, never a flag — a flag
8243
+ * invites production use). Recorded LOUDLY in run-state as `dispatcherOverride: true`, because a
8244
+ * test seam that leaves no trace in the artifact is indistinguishable from a real run. */
8245
+ const WF_RUN_DISPATCH_SCRIPT_ENV = 'DZ_WF_RUN_DISPATCH_SCRIPT';
8246
+ const WF_RUN_OWNER_FILE = 'run-owner.json';
8247
+ const WF_RUN_STATE_FILE = 'run-state.json';
8248
+
8249
+ /**
8250
+ * THE ONE PLACE anything in the loop runner is signalled (Step-8 re-QE NEW-C4).
8251
+ *
8252
+ * Round 1 guarded `process.kill(-pid, …)` — the process-GROUP path — and left `child.kill(sig)`
8253
+ * unguarded beside it. A fake child reporting `pid: 0` therefore still received the signal through
8254
+ * the object method, which is the same defect wearing a different call shape. `process.kill(-0, …)`
8255
+ * signals the CALLER'S OWN process group; round 0 of this exact class took down the vitest worker
8256
+ * pool. Two call shapes meant two chances to forget, so now there is one.
8257
+ *
8258
+ * The guard is on the PID, not on the shape: an unsignalable pid (not an integer, or <= 1) reaches
8259
+ * NOTHING — neither `process.kill` nor `child.kill`. Returns whether a signal was actually sent, so
8260
+ * a caller can never mistake "refused" for "delivered".
8261
+ */
8262
+ function signalChildSafely(child: { pid?: unknown; kill?: (signal: NodeJS.Signals) => unknown } | undefined, signal: NodeJS.Signals, detached: boolean): boolean {
8263
+ const raw = child?.pid;
8264
+ if (typeof raw !== 'number' || !Number.isInteger(raw) || raw <= 1) return false;
7467
8265
  try {
7468
- if (lstatSync(featuresDir).isSymbolicLink()) return { debts: [], malformed: 0 }; // r2 #4: features/ itself
7469
- slugs = readdirSync(featuresDir);
8266
+ if (detached) process.kill(-raw, signal);
8267
+ else child?.kill?.(signal);
8268
+ return true;
7470
8269
  } catch {
7471
- return { debts: [], malformed: 0 };
7472
- }
7473
- for (const slug of slugs.sort()) {
7474
- const dir = join(featuresDir, slug);
7475
- const stateDir = join(dir, '.fa-state');
7476
- const duePath = join(stateDir, 'reqe-due.json');
7477
- try {
7478
- if (lstatSync(dir).isSymbolicLink() || lstatSync(stateDir).isSymbolicLink()) continue;
7479
- } catch {
7480
- continue; // no feature dir / no state dir — nothing to scan
7481
- }
7482
- let st;
7483
- try {
7484
- st = lstatSync(duePath);
7485
- } catch {
7486
- continue; // no due-file — the common, silent case
7487
- }
7488
- if (!st.isFile() || st.size > 64 * 1024) {
7489
- malformed++; // exists but is not a plain small file — named, never silently dropped
7490
- continue;
7491
- }
7492
- try {
7493
- const debt = parseReqeDebt(readFileSync(duePath, 'utf-8'));
7494
- if (debt && debt.slug === slug) out.push({ debt, duePath, dir });
7495
- else malformed++;
7496
- } catch {
7497
- malformed++;
7498
- }
8270
+ return false; // already gone, or not ours — both mean nothing more to do
7499
8271
  }
8272
+ }
8273
+
8274
+ /** Test seam for the chokepoint: NEW-C4's proof needs to call it with a hostile pid. */
8275
+ export function __wfSignalChildTestSeam(child: unknown, signal: string, detached: boolean): boolean {
8276
+ return signalChildSafely(child as { pid?: unknown; kill?: (s: NodeJS.Signals) => unknown }, signal as NodeJS.Signals, detached);
8277
+ }
8278
+
8279
+ /** Live children, keyed by pid, for the kill-group handlers (AM-10). */
8280
+ const wfLiveChildren = new Map<number, ChildProcess>();
8281
+ let wfHandlersInstalled = false;
8282
+
8283
+ /** Kill the process GROUP of every live child. A detached child leads its own group, so killing the
8284
+ * leader alone would leave whatever it spawned running — that is the orphan class AM-10 closes.
8285
+ * NAMED RESIDUE: a SIGKILL of the runner itself runs no handler, so that case still orphans. */
8286
+ function wfKillLiveChildren(signal: NodeJS.Signals = 'SIGTERM'): number[] {
8287
+ const killed: number[] = [];
8288
+ for (const [pid, child] of [...wfLiveChildren.entries()]) {
8289
+ // ONE chokepoint: group first (a detached child leads its own), then the leader. Neither shape
8290
+ // is reachable without the pid guard.
8291
+ if (signalChildSafely(child, signal, true) || signalChildSafely(child, signal, false)) killed.push(pid);
8292
+ wfLiveChildren.delete(pid);
8293
+ }
8294
+ return killed;
8295
+ }
8296
+
8297
+ function wfInstallKillHandlers(): void {
8298
+ if (wfHandlersInstalled) return;
8299
+ wfHandlersInstalled = true;
8300
+ process.on('exit', () => { wfKillLiveChildren(); });
8301
+ process.on('SIGTERM', () => { wfKillLiveChildren(); process.exit(143); });
8302
+ process.on('SIGINT', () => { wfKillLiveChildren(); process.exit(130); });
8303
+ }
8304
+
8305
+ /** Exposed for the unit test: the kill set must NAME every live child's pid. */
8306
+ export function __wfKillGroupTestSeam(): { register: (pid: number, child: ChildProcess) => void; killAll: () => number[]; size: () => number } {
8307
+ return {
8308
+ register: (pid, child) => { wfLiveChildren.set(pid, child); },
8309
+ killAll: () => wfKillLiveChildren(),
8310
+ size: () => wfLiveChildren.size,
8311
+ };
8312
+ }
8313
+
8314
+ /** A `ChildRunner` over the generalized wrapper, registering every live child for the kill set. */
8315
+ /** A `ChildRunner` bound to ONE family, so its child can only ever receive that family's
8316
+ * credentials (re-QE H9). Two runners, two credential sets, one wrapper. */
8317
+ const wfChildRunnerFor = (family: BridgeFamily): ChildRunner => async (bin, argv, opts) =>
8318
+ runChildBridge(bin, argv, {
8319
+ ...opts,
8320
+ // a dispatched model gets a NAMED minimal environment, never the runner's whole one (HIGH-9)
8321
+ envMode: 'allowlist',
8322
+ envExtra: CHILD_ENV_BY_FAMILY[family],
8323
+ onSpawn: (child) => {
8324
+ if (typeof child.pid !== 'number') return;
8325
+ const pid = child.pid;
8326
+ wfLiveChildren.set(pid, child);
8327
+ child.on('close', () => { wfLiveChildren.delete(pid); });
8328
+ },
8329
+ });
8330
+
8331
+ /** Build the SCRIPTED dispatcher from the env seam's JSON file (test-only). */
8332
+ function wfScriptedDispatcher(scriptPath: string, family: BridgeFamily): Dispatcher {
8333
+ const raw = JSON.parse(readFileSync(scriptPath, 'utf8')) as Record<string, unknown>;
8334
+ const script = (raw['steps'] ?? raw) as Record<string, unknown>;
8335
+ const probeId = typeof raw['probeId'] === 'string' ? (raw['probeId'] as string) : `${family}-scripted`;
8336
+ const consumed = new Map<string, number>();
8337
+ return {
8338
+ probe: async (candidates) => ({ id: raw['probeFails'] === true ? null : probeId, wallMs: 1, detail: `scripted probe (${candidates.join(',') || 'defaults'})` }),
8339
+ dispatch: async (req) => {
8340
+ const key = req.itemKey === null ? req.stepId : `${req.stepId}:${req.itemKey}`;
8341
+ const entry = script[key] ?? script[req.stepId];
8342
+ const n = consumed.get(key) ?? 0;
8343
+ consumed.set(key, n + 1);
8344
+ const picked = Array.isArray(entry) ? (entry[Math.min(n, entry.length - 1)] as Record<string, unknown>) : (entry as Record<string, unknown> | undefined);
8345
+ const base: DispatchResult = {
8346
+ outcome: 'ok',
8347
+ text: `scripted:${key}`,
8348
+ family,
8349
+ modelUsed: req.resolvedModelId,
8350
+ wallMs: 1,
8351
+ tokensIn: null,
8352
+ tokensOut: null,
8353
+ tokensSource: null,
8354
+ };
8355
+ if (picked === undefined || picked === null) return base;
8356
+ // a scripted step may ask the runner to CREATE its declared writes (the landed-barrier leg)
8357
+ if (picked['writes'] === true) {
8358
+ for (const rel of req.expectedWrites) {
8359
+ // the seam re-checks containment too — a test double that could write outside the root
8360
+ // would be a hole in exactly the guard the real path is being tested for (CRITICAL-4)
8361
+ const abs = wfContainedPath(req.cwd, rel);
8362
+ if (abs === null) continue;
8363
+ mkdirSync(dirname(abs), { recursive: true });
8364
+ writeFileSync(abs, `scripted write for ${req.stepId} attempt ${req.attempt}\n`);
8365
+ }
8366
+ }
8367
+ return { ...base, ...(picked as Partial<DispatchResult>) };
8368
+ },
8369
+ };
8370
+ }
8371
+
8372
+ /** Read a small JSON file, or null. */
8373
+ function wfReadJson(path: string): unknown {
8374
+ try {
8375
+ return JSON.parse(readFileSync(path, 'utf8'));
8376
+ } catch {
8377
+ return null;
8378
+ }
8379
+ }
8380
+
8381
+ /** Is a recorded pid still alive? `kill(pid, 0)` is the portable liveness probe. */
8382
+ function wfPidAlive(pid: number): boolean {
8383
+ if (!Number.isInteger(pid) || pid <= 0) return false;
8384
+ try {
8385
+ process.kill(pid, 0);
8386
+ return true;
8387
+ } catch (e) {
8388
+ return (e as NodeJS.ErrnoException).code === 'EPERM'; // alive, just not ours
8389
+ }
8390
+ }
8391
+
8392
+ /** The fs `RunStore`. Every write that must be atomic is temp+rename; every file that must be NEW
8393
+ * is `wx`. Nothing here decides anything. */
8394
+ /**
8395
+ * Containment, re-checked at the LAST possible moment (Step-8 CRITICAL-4: "repeat containment
8396
+ * immediately before filesystem access").
8397
+ *
8398
+ * Preflight validated these paths minutes earlier, against a filesystem that has since been written
8399
+ * to — by the very models this run dispatched. A symlink planted between preflight and the probe is
8400
+ * not a hypothetical here; creating files is what the file-deliverable steps DO. Returns the
8401
+ * absolute path, or null when the path no longer resolves inside the root.
8402
+ */
8403
+ function wfContainedPath(targetCwd: string, rel: string): string | null {
8404
+ const check = containedUnderRoot(targetCwd, rel);
8405
+ return check.ok ? check.path : null;
8406
+ }
8407
+
8408
+ function wfMakeStore(runDir: string, repoRoot: string, targetCwd: string): RunStore {
8409
+ const statePath = join(runDir, WF_RUN_STATE_FILE);
8410
+ const tracePath = join(runDir, 'trace.jsonl');
8411
+ const stateDir = join(runDir, '.fa-state');
8412
+ const ckptPath = join(stateDir, 'checkpoints.jsonl');
8413
+ const budgetPath = join(runDir, 'budget.jsonl');
8414
+ const duePath = join(stateDir, 'reqe-due.json');
8415
+ const ledgerPath = join(repoRoot, '.dz', 'feature-adr', 'run-cost-ledger.jsonl');
8416
+ const hashOf = (abs: string): string | null => {
8417
+ try {
8418
+ return createHash('sha256').update(readFileSync(abs)).digest('hex');
8419
+ } catch {
8420
+ return null;
8421
+ }
8422
+ };
8423
+ return {
8424
+ runDirExists: () => existsSync(runDir),
8425
+ hasTrace: () => existsSync(tracePath),
8426
+ readTraceText: () => (existsSync(tracePath) ? readFileSync(tracePath, 'utf8') : null),
8427
+ readRunState: () => wfReadJson(statePath) as WfRunState | null,
8428
+ writeRunState: (s) => {
8429
+ mkdirSync(runDir, { recursive: true });
8430
+ const tmp = statePath + '.tmp';
8431
+ writeFileSync(tmp, JSON.stringify(s, null, 2) + '\n');
8432
+ renameSync(tmp, statePath); // atomic: a half-written state is a foreign run forever
8433
+ },
8434
+ appendTraceLines: (lines) => {
8435
+ if (lines.length === 0) return;
8436
+ mkdirSync(runDir, { recursive: true });
8437
+ appendFileSync(tracePath, lines.join('\n') + '\n');
8438
+ },
8439
+ readCheckpointsText: () => (existsSync(ckptPath) ? readFileSync(ckptPath, 'utf8') : null),
8440
+ appendCheckpointLine: (line) => {
8441
+ mkdirSync(stateDir, { recursive: true });
8442
+ appendFileSync(ckptPath, line + '\n');
8443
+ },
8444
+ appendBudgetRow: (row) => {
8445
+ mkdirSync(runDir, { recursive: true });
8446
+ appendFileSync(budgetPath, JSON.stringify(row) + '\n');
8447
+ },
8448
+ appendLedgerLine: (line) => {
8449
+ try {
8450
+ mkdirSync(dirname(ledgerPath), { recursive: true });
8451
+ appendFileSync(ledgerPath, line + '\n');
8452
+ } catch {
8453
+ /* telemetry is SECONDARY: a ledger failure never fails a run */
8454
+ }
8455
+ },
8456
+ probeArtifact: (rel) => {
8457
+ const abs = wfContainedPath(targetCwd, rel);
8458
+ // a path that no longer resolves inside the root is NOT LANDED, whatever is at the other end
8459
+ return abs !== null && existsSync(abs);
8460
+ },
8461
+ // re-QE R3-A: the same realpath + symlinked-ancestor discipline, for reads AND writes, at the
8462
+ // moment before the dispatch grants filesystem access
8463
+ pathContainmentOk: (rel) => wfContainedPath(targetCwd, rel) !== null,
8464
+ snapshotWrites: (rels) => {
8465
+ const out: Record<string, string | null> = {};
8466
+ for (const rel of rels) {
8467
+ const abs = wfContainedPath(targetCwd, rel);
8468
+ out[rel] = abs === null ? null : hashOf(abs);
8469
+ }
8470
+ return out;
8471
+ },
8472
+ writeReqeDebt: (record) => {
8473
+ mkdirSync(stateDir, { recursive: true });
8474
+ writeFileSync(duePath, JSON.stringify(record, null, 2) + '\n');
8475
+ },
8476
+ };
8477
+ }
8478
+
8479
+ /**
8480
+ * `dz workflow run <plan.json>` — INTERPRET the plan (ADR-001). Registered inside the existing
8481
+ * `case 'workflow':` branch when `_positional_0 === 'run'`, BEFORE the sync `cmdWorkflow`.
8482
+ *
8483
+ * Exit codes (AM-11): `0` completed · `1` failed (named) · `2` usage / invalid plan ·
8484
+ * `75` typed pause (sysexits EX_TEMPFAIL). NOT `3`: that collides with workflow-lint's
8485
+ * inconclusive and reads ignorable, while a pause strands resumable progress.
8486
+ */
8487
+ async function cmdWorkflowRun(
8488
+ options: Map<string, string>,
8489
+ optionLists: Map<string, string[]>,
8490
+ flags: Set<string>,
8491
+ cwd: string,
8492
+ write: Write,
8493
+ ): Promise<number> {
8494
+ const json = flags.has('json');
8495
+ const usage = 'dz workflow run <plan.json> [--run-id <id>] [--resume <runId>] [--arg k=v]… '
8496
+ + '[--coder-family codex|claude] [--default-family codex|claude] [--budget <n>] [--max-wall-clock <s>] '
8497
+ + '[--stage-timeout <s>] [--budget-extra <n>] [--wall-clock-extra <s>] [--run-dir <dir>] '
8498
+ + '[--allow-same-family-qe] [--json]';
8499
+ const usageError = (message: string): number => {
8500
+ write(json ? JSON.stringify({ ok: false, reason: 'plan-invalid', error: message, exitCode: 2 }) : `dz workflow run: ${message}\n${usage}`);
8501
+ return 2;
8502
+ };
8503
+
8504
+ if (flags.has('help')) {
8505
+ write(usage);
8506
+ write('');
8507
+ write('EXIT CODES — `dz workflow run` and `dz workflow-lint` have DIFFERENT tables (AM-11):');
8508
+ write(' run 0 completed · 1 failed (named reason) · 2 usage/invalid plan · 75 typed pause (EX_TEMPFAIL)');
8509
+ write(' lint 0 clean · 1 findings · 3 inconclusive');
8510
+ write(' 75 is NOT 3: 3 reads ignorable and collides with lint, while a pause strands resumable work.');
8511
+ write('On a pause the LAST stdout line is a `wf-pause-envelope/1` JSON object; a FAILURE emits none,');
8512
+ write('so a wrapper can tell the two apart from stdout + exit code alone, without parsing prose.');
8513
+ return 0;
8514
+ }
8515
+
8516
+ // ── closed allowlists (the cmdQeBridge discipline: an unknown flag is a usage error, never a
8517
+ // silently-ignored intention) ──
8518
+ const OPTS = new Set(['run-id', 'resume', 'arg', 'coder-family', 'default-family', 'budget', 'max-wall-clock', 'stage-timeout', 'budget-extra', 'wall-clock-extra', 'run-dir', 'project', '_positional_0', '_positional_1']);
8519
+ const FLAGS = new Set(['allow-same-family-qe', 'json', 'help']);
8520
+ for (const k of options.keys()) if (!OPTS.has(k)) return usageError(`unknown option --${k}`);
8521
+ for (const f of flags) if (!FLAGS.has(f)) return usageError(`unknown flag --${f}`);
8522
+
8523
+ // ── SINGLETONS (Step-8 HIGH-8 — the recurring class) ──
8524
+ //
8525
+ // `parseArgs` keeps every occurrence in `optionLists` but the main map is LAST-WINS, so
8526
+ // `--coder-family codex --coder-family claude` was accepted and only `claude` reached preflight.
8527
+ // For a SAFETY option that is a bypass: the same-family guard compares the coder family against a
8528
+ // qe step's family, and whoever supplies the last occurrence chooses the answer. Every option here
8529
+ // is a singleton BY MEANING — a run has one coder family, one budget, one run directory — so a
8530
+ // second occurrence is not a preference, it is an ambiguity, and the only honest answer is to
8531
+ // refuse. `--arg` is deliberately absent: it is the one genuinely repeatable option.
8532
+ const SINGLETON_OPTS = ['run-id', 'resume', 'coder-family', 'default-family', 'budget', 'max-wall-clock', 'stage-timeout', 'budget-extra', 'wall-clock-extra', 'run-dir', 'project'];
8533
+ for (const key of SINGLETON_OPTS) {
8534
+ const occurrences = optionLists.get(key) ?? [];
8535
+ if (occurrences.length > 1) {
8536
+ return usageError(
8537
+ `--${key} was given ${occurrences.length} times (${occurrences.map((v) => JSON.stringify(v)).join(', ')}) — it is a singleton, and a second occurrence is an ambiguity, not a preference. `
8538
+ + 'Stacking a safety option would let the LAST value decide what the first one refused.',
8539
+ );
8540
+ }
8541
+ }
8542
+
8543
+ const planPath = options.get('_positional_1') ?? '';
8544
+ if (planPath === '') return usageError('a plan.json positional is required');
8545
+ const root = resolve(cwd, options.get('project') ?? '.');
8546
+ const absPlan = resolve(cwd, planPath);
8547
+ if (!existsSync(absPlan)) return usageError(`no such plan file: ${absPlan}`);
8548
+
8549
+ let rawPlan: unknown;
8550
+ try {
8551
+ rawPlan = JSON.parse(readFileSync(absPlan, 'utf8'));
8552
+ } catch (e) {
8553
+ return usageError(`unparseable plan JSON — ${e instanceof Error ? e.message : String(e)}`);
8554
+ }
8555
+ const parsed = parsePlan(rawPlan);
8556
+ if (isParseErrors(parsed)) {
8557
+ if (json) write(JSON.stringify({ ok: false, reason: 'plan-invalid', parseErrors: parsed, exitCode: 2 }));
8558
+ else for (const e of parsed) write(`PARSE ${e.path}: ${e.message}`);
8559
+ return 2;
8560
+ }
8561
+ const diags = validatePlan(parsed);
8562
+ if (diags.length > 0) {
8563
+ if (json) write(JSON.stringify({ ok: false, reason: 'plan-invalid', diagnostics: diags, exitCode: 2 }));
8564
+ else for (const d of diags) write(`${d.invariant} ${d.path}: ${d.message}`);
8565
+ return 2;
8566
+ }
8567
+
8568
+ // ── numeric options ride the Number.isFinite clamp (every numeric config clamp needs it) ──
8569
+ const num = (key: string, scale = 1): { ok: true; value: number | null } | { ok: false; why: string } => {
8570
+ const raw = options.get(key);
8571
+ if (raw === undefined) return { ok: true, value: null };
8572
+ const n = Number(raw);
8573
+ if (!Number.isFinite(n) || n < 0) return { ok: false, why: `--${key} must be a finite non-negative number (got ${JSON.stringify(raw)})` };
8574
+ return { ok: true, value: Math.floor(n * scale) };
8575
+ };
8576
+ const nums: Record<string, number | null> = {};
8577
+ for (const [key, scale] of [['budget', 1], ['max-wall-clock', 1000], ['stage-timeout', 1000], ['budget-extra', 1], ['wall-clock-extra', 1000]] as const) {
8578
+ const r = num(key, scale);
8579
+ if (!r.ok) return usageError(r.why);
8580
+ nums[key] = r.value;
8581
+ }
8582
+
8583
+ const familyOpt = (key: string): { ok: true; value: BridgeFamily | null } | { ok: false; why: string } => {
8584
+ const raw = options.get(key);
8585
+ if (raw === undefined) return { ok: true, value: null };
8586
+ if (raw !== 'codex' && raw !== 'openai' && raw !== 'claude') return { ok: false, why: `--${key} must be codex or claude (got ${JSON.stringify(raw)})` };
8587
+ return { ok: true, value: modelFamily(raw) };
8588
+ };
8589
+ const coder = familyOpt('coder-family');
8590
+ if (!coder.ok) return usageError(coder.why);
8591
+ const dflt = familyOpt('default-family');
8592
+ if (!dflt.ok) return usageError(dflt.why);
8593
+
8594
+ const resumeArgs: Record<string, string> = {};
8595
+ for (const kv of optionLists.get('arg') ?? []) {
8596
+ const eq = kv.indexOf('=');
8597
+ if (eq <= 0) return usageError(`--arg must be k=v (got ${JSON.stringify(kv)})`);
8598
+ resumeArgs[kv.slice(0, eq)] = kv.slice(eq + 1);
8599
+ }
8600
+
8601
+ const resumeId = options.get('resume') ?? null;
8602
+ const runId = options.get('run-id') ?? resumeId ?? `${parsed.name}-${randomBytes(2).toString('hex')}`;
8603
+ if (!TRACE_RUNID_RE.test(runId)) return usageError(`runId ${JSON.stringify(runId)} fails ${String(TRACE_RUNID_RE)}`);
8604
+ if (resumeId !== null && options.get('run-id') !== undefined && options.get('run-id') !== resumeId) {
8605
+ return usageError('--run-id and --resume name different runs — a resume continues the run it names');
8606
+ }
8607
+
8608
+ const runDirOpt = options.get('run-dir');
8609
+ let runDir: string;
8610
+ if (runDirOpt !== undefined) {
8611
+ const contained = containedUnderRoot(root, runDirOpt);
8612
+ if (!contained.ok) return usageError(`--run-dir ${contained.why}`);
8613
+ runDir = contained.path;
8614
+ } else {
8615
+ runDir = join(root, '.dz', 'loop-trace', runId); // the addressing `dz workflow-trace --run <id>` already uses
8616
+ }
8617
+
8618
+ // The scripted-seam marker is established BEFORE the first refusal can emit (re-QE MINOR): an
8619
+ // EARLY refusal is still a run that would have dispatched to no real model, and a reader of that
8620
+ // envelope has the same right to know as a reader of a completed one.
8621
+ const seamScriptPath = process.env[WF_RUN_DISPATCH_SCRIPT_ENV];
8622
+ const dispatcherOverride = typeof seamScriptPath === 'string' && seamScriptPath !== '';
8623
+ const emit = (payload: object): void => {
8624
+ write(JSON.stringify(dispatcherOverride ? { ...payload, dispatcherOverride: true } : payload));
8625
+ };
8626
+
8627
+ // ── AM-7 ownership, ATOMICALLY (Step-8 HIGH-6) ──
8628
+ //
8629
+ // The previous shape read the owner marker, decided, and wrote it later — a window in which two
8630
+ // processes both saw "no live owner" and both proceeded. And the write itself was wrapped in a
8631
+ // swallowing try, so a run could execute while its durable claim silently did not exist.
8632
+ //
8633
+ // Now: check and claim happen INSIDE the named lock, the claim is `wx` (create-or-fail, so the
8634
+ // filesystem itself arbitrates), a STALE marker is only replaced under that same lock, and a
8635
+ // failure to claim FAILS THE RUN. One writer per run is not a convention here; it is an atomic
8636
+ // filesystem operation.
8637
+ const ownerPath = join(runDir, WF_RUN_OWNER_FILE);
8638
+ const startedMarker = new Date().toISOString();
8639
+ const RUN_ARTIFACTS = [WF_RUN_STATE_FILE, 'trace.jsonl', 'budget.jsonl', join('.fa-state', 'checkpoints.jsonl')];
8640
+ type Claim = { ok: true } | { ok: false; reason: 'run-exists' | 'run-locked'; detail: string };
8641
+ const claim: Claim = withNamedLockSync(root, `wf-run-${runId}`, (): Claim => {
8642
+ mkdirSync(runDir, { recursive: true });
8643
+ // ORDER MATTERS. A LIVE owner is `run-locked` whichever kind of invocation this is — that is
8644
+ // the precise fact, and it outranks "the directory has files in it". Only then does a FRESH run
8645
+ // refuse a directory that already holds a run's artifacts.
8646
+ const existingOwner = wfReadJson(ownerPath) as { pid?: number; startedMarker?: string } | null;
8647
+ if (existingOwner !== null && typeof existingOwner.pid === 'number' && wfPidAlive(existingOwner.pid)) {
8648
+ return { ok: false, reason: 'run-locked', detail: `another dz workflow run (pid ${existingOwner.pid}, started ${existingOwner.startedMarker ?? 'unknown'}) owns ${runDir} — ONE writer per run, always` };
8649
+ }
8650
+ if (resumeId === null) {
8651
+ // a FRESH run may not write into a directory that already holds ANY artifact of a run — not
8652
+ // merely one with a readable state file (a HALF-written run is exactly the dangerous case).
8653
+ // The owner marker is excluded: a dead one is stale residue, handled by the claim below.
8654
+ const found = RUN_ARTIFACTS.filter((rel) => existsSync(join(runDir, rel)));
8655
+ if (found.length > 0) {
8656
+ return {
8657
+ ok: false,
8658
+ reason: 'run-exists',
8659
+ detail: `run directory ${runDir} already holds ${found.join(', ')} — pass --resume ${runId} to continue it, or choose another --run-id. A fresh run never writes into an existing run's artifacts`,
8660
+ };
8661
+ }
8662
+ }
8663
+ for (let attempt = 0; attempt < 2; attempt++) {
8664
+ try {
8665
+ writeFileSync(ownerPath, JSON.stringify({ host: WF_RUN_OWNER_HOST, pid: process.pid, runnerVersion: dzOwnVersion(), startedMarker }, null, 2) + '\n', { flag: 'wx' });
8666
+ return { ok: true };
8667
+ } catch (e) {
8668
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') {
8669
+ return { ok: false, reason: 'run-locked', detail: `cannot claim ${ownerPath}: ${e instanceof Error ? e.message : String(e)} — refusing to run without a durable owner record` };
8670
+ }
8671
+ const held = wfReadJson(ownerPath) as { pid?: number; startedMarker?: string } | null;
8672
+ if (held !== null && typeof held.pid === 'number' && wfPidAlive(held.pid)) {
8673
+ return { ok: false, reason: 'run-locked', detail: `another dz workflow run (pid ${held.pid}, started ${held.startedMarker ?? 'unknown'}) owns ${runDir} — ONE writer per run, always` };
8674
+ }
8675
+ // STALE: the recorded owner is gone. Replacing it is safe HERE and only here, because this
8676
+ // whole block holds the named lock, so no concurrent claimant can be mid-decision.
8677
+ try {
8678
+ unlinkSync(ownerPath);
8679
+ } catch {
8680
+ /* someone else just cleared it; the retry's `wx` decides */
8681
+ }
8682
+ }
8683
+ }
8684
+ return { ok: false, reason: 'run-locked', detail: `could not claim ${ownerPath} after replacing a stale marker — another writer is racing for this run` };
8685
+ });
8686
+ if (!claim.ok) {
8687
+ if (json) emit({ schema: 'wf-run-result/1', runId, status: 'failed', reason: claim.reason, exitCode: 1 });
8688
+ else write(`dz workflow run: ${claim.reason} — ${claim.detail}`);
8689
+ return 1;
8690
+ }
8691
+
8692
+ // ── NEW-H (re-QE): from HERE to the end, every exit path — return, throw, or completion — runs
8693
+ // the cleanup. Round 1 opened the try only around `runWorkflow`, so a `usageError` return or a
8694
+ // throw while CONSTRUCTING the dispatchers (a malformed seam file is enough) left `run-owner.json`
8695
+ // behind: a durable claim held by a process that had already exited.
8696
+ try {
8697
+ const targetCwd = root;
8698
+ const inputs: RunnerInputs = {
8699
+ plan: parsed,
8700
+ runId,
8701
+ coderFamily: coder.value ?? 'claude',
8702
+ allowSameFamilyQe: flags.has('allow-same-family-qe'),
8703
+ defaultFamily: dflt.value,
8704
+ budgetOverride: nums['budget'] ?? null,
8705
+ maxWallClockMsOverride: nums['max-wall-clock'] ?? null,
8706
+ stageTimeoutMsOverride: nums['stage-timeout'] ?? null,
8707
+ resume: resumeId,
8708
+ resumeArgs,
8709
+ budgetExtra: nums['budget-extra'] ?? null,
8710
+ wallClockExtraMs: nums['wall-clock-extra'] ?? null,
8711
+ runnerVersion: dzOwnVersion(),
8712
+ cwdRoot: targetCwd,
8713
+ };
8714
+
8715
+ const pre = preflight(inputs, {
8716
+ realpath: (p) => { try { return realpathSync(p); } catch { return null; } },
8717
+ exists: (p) => existsSync(p),
8718
+ });
8719
+ if (!pre.ok) {
8720
+ if (json) emit({ schema: 'wf-run-result/1', runId, status: 'failed', reason: pre.reason, exitCode: 1 });
8721
+ else write(`dz workflow run: ${pre.reason} — ${pre.detail}`);
8722
+ return 1;
8723
+ }
8724
+
8725
+ // ── dispatchers: the real adapters, or the scripted env TEST SEAM ──
8726
+ const scriptPath = seamScriptPath;
8727
+ let dispatchers: Record<BridgeFamily, Dispatcher>;
8728
+ if (dispatcherOverride) {
8729
+ if (!existsSync(scriptPath as string)) return usageError(`${WF_RUN_DISPATCH_SCRIPT_ENV}=${String(scriptPath)} does not exist`);
8730
+ dispatchers = { claude: wfScriptedDispatcher(scriptPath as string, 'claude'), openai: wfScriptedDispatcher(scriptPath as string, 'openai') };
8731
+ } else {
8732
+ wfInstallKillHandlers();
8733
+ const isolated = mkdtempSync(join(tmpdir(), 'dz-wf-run-'));
8734
+ const monotonicMs = (): number => Number(process.hrtime.bigint() / 1000000n);
8735
+ dispatchers = {
8736
+ claude: makeClaudePDispatcher(wfChildRunnerFor('claude'), { isolatedCwd: () => isolated, monotonicMs }),
8737
+ openai: makeCodexExecDispatcher(wfChildRunnerFor('openai'), { isolatedCwd: () => isolated, monotonicMs }),
8738
+ };
8739
+ }
8740
+
8741
+ const store = wfMakeStore(runDir, root, targetCwd);
8742
+ const deps: SchedulerDeps = {
8743
+ store,
8744
+ dispatchers,
8745
+ lock: (fn) => withNamedLockSync(root, `wf-run-${runId}`, fn),
8746
+ now: () => new Date().toISOString(),
8747
+ monotonicMs: () => Number(process.hrtime.bigint() / 1000000n),
8748
+ dispatcherOverride,
8749
+ planPath: relative(root, absPlan) || planPath,
8750
+ slug: parsed.name,
8751
+ // the envelope must point at THIS run's state file and reproduce THIS run's flags (HIGH-7)
8752
+ runStatePath: relative(root, join(runDir, WF_RUN_STATE_FILE)) || join(runDir, WF_RUN_STATE_FILE),
8753
+ runDirArg: runDirOpt ?? null,
8754
+ // the run-state owner records the process that actually holds the claim (HIGH-6) — `pid: 0`
8755
+ // was a durable record of a process that never existed
8756
+ ownerPid: process.pid,
8757
+ ownerStartedMarker: startedMarker,
8758
+ };
8759
+
8760
+ const outcome = await runWorkflow(inputs, pre, deps);
8761
+
8762
+ // A run that dispatched to NO REAL MODEL says so on every channel (Step-8 MEDIUM-11): the
8763
+ // result/pause envelope carries `dispatcherOverride`, and the human line says it in words. A seam
8764
+ // visible only inside a state file is a seam a reader of the output cannot know about.
8765
+ const seamNote = dispatcherOverride ? ' [SCRIPTED DISPATCHER — no real model ran]' : '';
8766
+ if (outcome.kind === 'paused') {
8767
+ if (!json) write(`dz workflow run: PAUSED (${outcome.envelope.pauseState})${seamNote} — resume with: ${outcome.envelope.resumeCmd}`);
8768
+ // the envelope is the LAST stdout line, ALWAYS (AM-16)
8769
+ emit({ ...outcome.envelope, ...(dispatcherOverride ? { dispatcherOverride: true } : {}) });
8770
+ return 75;
8771
+ }
8772
+ if (outcome.kind === 'failed') {
8773
+ if (!json) write(`dz workflow run: ${outcome.reason}${seamNote} — ${outcome.detail}`);
8774
+ emit(outcome.result); // a wf-run-result/1 line — and NEVER a pause envelope
8775
+ return 1;
8776
+ }
8777
+ if (!json) {
8778
+ const terminal = outcome.result.terminalRoute === undefined ? '' : ` via the plan's terminal route ${outcome.result.terminalRoute}`;
8779
+ write(`dz workflow run: completed (${runId})${terminal}${seamNote} — trace at ${join(relative(root, runDir) || '.', 'trace.jsonl')}`);
8780
+ }
8781
+ emit(outcome.result);
8782
+ return 0;
8783
+ } finally {
8784
+ // the claim is released exactly once, on EVERY path out of the claimed region
8785
+ try { unlinkSync(ownerPath); } catch { /* already gone */ }
8786
+ wfKillLiveChildren();
8787
+ }
8788
+ }
8789
+
8790
+ function scanReqeDebts(root: string): { debts: Array<{ debt: ReqeDebt; duePath: string; dir: string }>; malformed: number } {
8791
+ const out: Array<{ debt: ReqeDebt; duePath: string; dir: string }> = [];
8792
+ let malformed = 0;
8793
+ /**
8794
+ * TWO scan roots (K1 — feature dz-workflow-run):
8795
+ * `features/<slug>/.fa-state/` — the feature-adr home, the original root;
8796
+ * `.dz/loop-trace/<runId>/.fa-state/` — the DEFAULT home of a `dz workflow run` (ADR-003).
8797
+ * Without the second root the ADR-002 waiver promise ("a waived run's debt is surfaced by
8798
+ * `dz reqe`") is FALSE for every default-homed loop run — the record would be written to a
8799
+ * directory nothing ever reads. The scan's own rules are unchanged: symlinked containers are
8800
+ * skipped, an oversize or non-plain file is NAMED as malformed rather than silently dropped, and
8801
+ * a debt whose `slug` disagrees with its directory is malformed too.
8802
+ */
8803
+ const scanRoots: { base: string; keyMatchesDir: boolean }[] = [
8804
+ { base: join(root, 'features'), keyMatchesDir: true },
8805
+ // a loop run's directory is its runId; the debt's `slug` is the PLAN's name, so the two need
8806
+ // not agree — the identity check that applies under features/ does not apply here
8807
+ { base: join(root, '.dz', 'loop-trace'), keyMatchesDir: false },
8808
+ ];
8809
+ for (const scanRoot of scanRoots) scanOneReqeRoot(scanRoot.base, scanRoot.keyMatchesDir, out, (n) => { malformed += n; });
7500
8810
  return { debts: out, malformed };
7501
8811
  }
7502
8812
 
8813
+ /** One scan root's walk — extracted verbatim from the original single-root body (K1). */
8814
+ function scanOneReqeRoot(
8815
+ featuresDir: string,
8816
+ keyMatchesDir: boolean,
8817
+ out: Array<{ debt: ReqeDebt; duePath: string; dir: string }>,
8818
+ addMalformed: (n: number) => void,
8819
+ ): void {
8820
+ let malformed = 0;
8821
+ let slugs: string[] = [];
8822
+ try {
8823
+ if (lstatSync(featuresDir).isSymbolicLink()) return; // r2 #4: the container itself
8824
+ slugs = readdirSync(featuresDir);
8825
+ } catch {
8826
+ return;
8827
+ }
8828
+ for (const slug of slugs.sort()) {
8829
+ const dir = join(featuresDir, slug);
8830
+ const stateDir = join(dir, '.fa-state');
8831
+ const duePath = join(stateDir, 'reqe-due.json');
8832
+ try {
8833
+ if (lstatSync(dir).isSymbolicLink() || lstatSync(stateDir).isSymbolicLink()) continue;
8834
+ } catch {
8835
+ continue; // no feature dir / no state dir — nothing to scan
8836
+ }
8837
+ let st;
8838
+ try {
8839
+ st = lstatSync(duePath);
8840
+ } catch {
8841
+ continue; // no due-file — the common, silent case
8842
+ }
8843
+ if (!st.isFile() || st.size > 64 * 1024) {
8844
+ malformed++; // exists but is not a plain small file — named, never silently dropped
8845
+ continue;
8846
+ }
8847
+ try {
8848
+ const debt = parseReqeDebt(readFileSync(duePath, 'utf-8'));
8849
+ if (debt && (!keyMatchesDir || debt.slug === slug)) out.push({ debt, duePath, dir });
8850
+ else malformed++;
8851
+ } catch {
8852
+ malformed++;
8853
+ }
8854
+ }
8855
+ addMalformed(malformed);
8856
+ }
8857
+
7503
8858
  /**
7504
8859
  * `dz reqe` — the re-QE debt ledger (backlog 6b40e667): list usage-switched same-family QE debts,
7505
8860
  * print the cross-family review brief, settle FAIL-CLOSED against a graded report.
@@ -7642,6 +8997,770 @@ function cmdReqe(options: Map<string, string>, flags: Set<string>, cwd: string,
7642
8997
  return 0;
7643
8998
  }
7644
8999
 
9000
+ /* -------------------------------------------------------------------------- */
9001
+ /* `dz qe-bridge` — the reverse QE bridge (feature qe-bridge-claude, ADR-001) */
9002
+ /* -------------------------------------------------------------------------- */
9003
+
9004
+ /** Review timeout default: an adversarial QE pass legitimately takes minutes (NFR-3). */
9005
+ const QE_BRIDGE_DEFAULT_TIMEOUT_S = 600;
9006
+ const QE_BRIDGE_MIN_TIMEOUT_S = 30;
9007
+ const QE_BRIDGE_MAX_TIMEOUT_S = 3600;
9008
+ /** Probe timeout — the mirror of `codexProbeCommand`'s `timeout 60`. */
9009
+ const QE_BRIDGE_PROBE_TIMEOUT_MS = 60_000;
9010
+
9011
+ export interface ClaudeBridgeRun {
9012
+ stdout: string;
9013
+ stderr: string;
9014
+ exitCode: number | null;
9015
+ timedOut: boolean;
9016
+ spawnError: string | null;
9017
+ }
9018
+
9019
+ /**
9020
+ * Run one `claude` call with the prompt on STDIN. Spawn-injectable, and NEVER throws: a missing
9021
+ * binary, a crash and a hang all come back as DATA, because the taxonomy above them can only name
9022
+ * a failure it is handed. (The first draft of this function let the ENOENT escape as an uncaught
9023
+ * exception and the command never settled — the acid A1 red, quoted in red-green.md.)
9024
+ *
9025
+ * Mirrors `probeContent`'s settled-flag + SIGTERM deadline shape (`cli.ts` probes) and scrubs
9026
+ * `PROBE_SCRUB_ENV`, so a bridge launched from inside a nested Claude session cannot inherit the
9027
+ * parent's session identity (SEC-4).
9028
+ */
9029
+ export async function runClaudeBridge(
9030
+ bin: string,
9031
+ argv: string[],
9032
+ promptStdin: string,
9033
+ timeoutMs: number,
9034
+ cwd: string = process.cwd(),
9035
+ spawnImpl: typeof spawn = spawn,
9036
+ ): Promise<ClaudeBridgeRun> {
9037
+ // A THIN WRAPPER over runChildBridge since the loop runner needed the same machinery with two
9038
+ // extra knobs. This signature is consumed by the qe-bridge suites and MUST NOT change.
9039
+ return runChildBridge(bin, argv, { stdinText: promptStdin, timeoutMs, cwd, detached: false, spawnImpl });
9040
+ }
9041
+
9042
+ /** How long a child's process group gets to honour SIGTERM before SIGKILL (Step-8 MEDIUM-14). */
9043
+ const CHILD_SIGKILL_GRACE_MS = 2000;
9044
+
9045
+ /**
9046
+ * The MINIMAL environment a dispatched child gets (Step-8 HIGH-9).
9047
+ *
9048
+ * A deny-list removes what somebody remembered; an allow-list carries what the child needs and
9049
+ * nothing else. The named set is deliberately boring — enough for a binary to find itself, resolve
9050
+ * a home directory, write a temp file and talk to a proxy — plus each runtime's own credential
9051
+ * variables, which are listed because they are REQUIRED, not because they happened to be present.
9052
+ * Anything a future adapter needs is added HERE, visibly, with a reason.
9053
+ */
9054
+ const CHILD_ENV_BASE: readonly string[] = [
9055
+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'LC_ALL', 'TZ',
9056
+ 'TMPDIR', 'TEMP', 'TMP',
9057
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy',
9058
+ // node itself, for a child that IS node
9059
+ 'NODE_EXTRA_CA_CERTS',
9060
+ ];
9061
+
9062
+ /**
9063
+ * CREDENTIALS ARE PER FAMILY (Step-8 re-QE H9 — the round-1 allowlist shipped BOTH sets to BOTH
9064
+ * runtimes, which is a shorter list of the same mistake).
9065
+ *
9066
+ * A codex dispatch has no business holding an Anthropic key, and vice versa. The two runtimes are
9067
+ * separate blast radii precisely because the cross-model rule makes them review each other: if one
9068
+ * is compromised or simply misbehaves, it must not be carrying the other's credentials. The base
9069
+ * above is boring on purpose — enough to find a binary, a home directory and a proxy — and nothing
9070
+ * in it authenticates anything.
9071
+ */
9072
+ const CHILD_ENV_BY_FAMILY: Readonly<Record<BridgeFamily, readonly string[]>> = {
9073
+ claude: ['ANTHROPIC_API_KEY', 'CLAUDE_CONFIG_DIR'],
9074
+ openai: ['OPENAI_API_KEY', 'CODEX_HOME'],
9075
+ };
9076
+
9077
+ function buildAllowlistEnv(extra: readonly string[], parent: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
9078
+ const out: NodeJS.ProcessEnv = {};
9079
+ for (const key of [...CHILD_ENV_BASE, ...extra]) {
9080
+ const v = parent[key];
9081
+ if (typeof v === 'string') out[key] = v;
9082
+ }
9083
+ return out;
9084
+ }
9085
+
9086
+ /** Test seam for H9: the exact environment ONE family's child would receive. */
9087
+ export function __wfChildEnvTestSeam(family: BridgeFamily, parent: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
9088
+ return buildAllowlistEnv(CHILD_ENV_BY_FAMILY[family], parent);
9089
+ }
9090
+
9091
+ /**
9092
+ * THE child-process wrapper both the qe-bridge and the loop runner ride (ADR-002 O1: ONE impure
9093
+ * wrapper, not two). Generalized from `runClaudeBridge` with the same guarantees — a settled flag so
9094
+ * no path resolves twice, a deadline timer that SIGTERMs, the `PROBE_SCRUB_ENV` scrub so a bridge
9095
+ * launched from inside a nested Claude session cannot inherit it, and an injectable `spawnImpl` —
9096
+ * plus the two knobs the generalization adds:
9097
+ *
9098
+ * • `stdinText: null` ⇒ `stdio[0] = 'ignore'`. MEASURED: codex-cli 0.148.0 prints
9099
+ * `Reading additional input from stdin...` and WAITS when stdin is left open. Passing an empty
9100
+ * string is not the same thing as closing it.
9101
+ * • `detached: true` ⇒ the child leads its OWN process group, so the runner can kill the whole
9102
+ * group (AM-10). `onSpawn` hands the live child to the caller's registry at the only moment the
9103
+ * pid is knowable.
9104
+ *
9105
+ * Never throws: a spawn failure resolves with `spawnError` set, exactly like the original.
9106
+ */
9107
+ export async function runChildBridge(
9108
+ bin: string,
9109
+ argv: string[],
9110
+ opts: {
9111
+ stdinText: string | null;
9112
+ timeoutMs: number;
9113
+ cwd: string;
9114
+ detached: boolean;
9115
+ spawnImpl?: typeof spawn;
9116
+ onSpawn?: (child: ChildProcess) => void;
9117
+ /**
9118
+ * `'scrub'` (default) — inherit the parent environment minus `PROBE_SCRUB_ENV`. The historical
9119
+ * qe-bridge posture; unchanged so its suites keep their meaning.
9120
+ * `'allowlist'` — build the child's environment from a NAMED list and nothing else
9121
+ * (Step-8 HIGH-9). A deny-list can only remove what somebody thought of; every cloud token,
9122
+ * registry credential and unrelated secret in the parent survived it. The loop runner uses this.
9123
+ */
9124
+ envMode?: 'scrub' | 'allowlist';
9125
+ /** Extra variable names the allowlist should carry (a family's own auth, named by the caller). */
9126
+ envExtra?: readonly string[];
9127
+ },
9128
+ ): Promise<ClaudeBridgeRun> {
9129
+ const spawnImpl = opts.spawnImpl ?? spawn;
9130
+ return new Promise<ClaudeBridgeRun>((resolveRun) => {
9131
+ const env: NodeJS.ProcessEnv = opts.envMode === 'allowlist'
9132
+ ? buildAllowlistEnv(opts.envExtra ?? [])
9133
+ : { ...process.env };
9134
+ if (opts.envMode !== 'allowlist') for (const key of PROBE_SCRUB_ENV) delete env[key];
9135
+ let out = '';
9136
+ let err = '';
9137
+ let settled = false;
9138
+ let timedOut = false;
9139
+ let child: ReturnType<typeof spawn> | undefined;
9140
+ const finish = (spawnError: string | null, exitCode: number | null): void => {
9141
+ if (settled) return;
9142
+ settled = true;
9143
+ clearTimeout(timer);
9144
+ // A DETACHED child leads its own group, so kill the GROUP — killing the leader alone leaves
9145
+ // whatever it spawned running (the orphan class AM-10 exists to close). SIGTERM is a REQUEST;
9146
+ // a group that ignores it would outlive the runner, so a bounded grace period later the same
9147
+ // group gets SIGKILL, which is not a request (Step-8 MEDIUM-14).
9148
+ // EVERY termination goes through the one guarded chokepoint (re-QE NEW-C4) — there is no
9149
+ // second call shape here to forget to guard.
9150
+ const sent = signalChildSafely(child, 'SIGTERM', opts.detached);
9151
+ if (sent) {
9152
+ const escalation = setTimeout(() => {
9153
+ signalChildSafely(child, 'SIGKILL', opts.detached);
9154
+ }, CHILD_SIGKILL_GRACE_MS);
9155
+ escalation.unref?.(); // the grace timer must never hold the runner's event loop open
9156
+ }
9157
+ resolveRun({ stdout: out, stderr: err, exitCode, timedOut, spawnError });
9158
+ };
9159
+ const timer = setTimeout(() => {
9160
+ timedOut = true;
9161
+ finish(null, null);
9162
+ }, opts.timeoutMs);
9163
+ try {
9164
+ child = spawnImpl(bin, argv, {
9165
+ cwd: opts.cwd,
9166
+ env,
9167
+ detached: opts.detached,
9168
+ stdio: [opts.stdinText === null ? 'ignore' : 'pipe', 'pipe', 'pipe'],
9169
+ });
9170
+ } catch (error) {
9171
+ finish(`cannot run \`${bin}\`: ${error instanceof Error ? error.message : String(error)}`, null);
9172
+ return;
9173
+ }
9174
+ opts.onSpawn?.(child as ChildProcess);
9175
+ child.on('error', (error: Error) => finish(`cannot run \`${bin}\`: ${error.message}`, null));
9176
+ child.stdout?.on('data', (c: Buffer) => { out += c.toString(); });
9177
+ child.stderr?.on('data', (c: Buffer) => { err += c.toString(); });
9178
+ child.on('close', (code) => finish(null, code));
9179
+ // EPIPE when the child died before reading: already reported through 'error'/'close'.
9180
+ child.stdin?.on('error', () => { /* ignored on purpose */ });
9181
+ if (opts.stdinText !== null) {
9182
+ try {
9183
+ child.stdin?.write(opts.stdinText);
9184
+ child.stdin?.end();
9185
+ } catch {
9186
+ /* the close/error handlers decide the outcome */
9187
+ }
9188
+ }
9189
+ });
9190
+ }
9191
+
9192
+ /** stderr wording that PROVES a login problem. Anything else stays unclassified: a guessed reason
9193
+ * is a small lie, and the failure record carries the raw evidence instead (ADR-001 D3-A). */
9194
+ function classifyClaudeStderr(stderr: string): 'claude-not-logged-in' | 'exit-nonzero' {
9195
+ return /invalid api key|not logged in|please run \/login|unauthorized|authentication (failed|error)|oauth token (has )?expired/i.test(stderr)
9196
+ ? 'claude-not-logged-in'
9197
+ : 'exit-nonzero';
9198
+ }
9199
+
9200
+ /** Test seam AND escape hatch for a non-standard install: the executable the bridge spawns.
9201
+ * Deliberately an ENV VAR and not a flag — a reviewer's identity should not be something a caller
9202
+ * can redirect with a casual command-line switch, and every record says loudly when it was used
9203
+ * (round-2 M3). */
9204
+ const QE_BRIDGE_CLAUDE_BIN_ENV = 'DZ_QE_BRIDGE_CLAUDE_BIN';
9205
+
9206
+ /**
9207
+ * CRASH FAILPOINT (round-4 R4-1) — test-only, and the ONLY thing it can do is stop. Set
9208
+ * `DZ_QE_BRIDGE_FAILPOINT=hang-before-rename` and the process blocks after the temp record is
9209
+ * written and before the rename, so a test can SIGKILL it exactly inside the window the atomic
9210
+ * update exists to close. Unset (the normal case) it is one string comparison and no behaviour.
9211
+ * A crash-window property that no test can enter is a claim, not a guarantee.
9212
+ */
9213
+ const QE_BRIDGE_FAILPOINT_ENV = 'DZ_QE_BRIDGE_FAILPOINT';
9214
+
9215
+ /** Files under `.fa-state/qe-bridge/` may quote reviewed source and reviewer prose: owner-only. */
9216
+ const RECORD_FILE_MODE = 0o600;
9217
+ const RECORD_DIR_MODE = 0o700;
9218
+
9219
+ /**
9220
+ * Write a NEW file, never through a symlink, never over an existing one, and never world-readable.
9221
+ * `wx` gives O_EXCL (no overwrite, no symlink follow at the final component); the explicit chmods
9222
+ * defeat the process umask, which `mode:` alone does not (MEASURED: under umask 022 the round-1
9223
+ * writes landed 0644/0755 — round-2 MAJOR M6).
9224
+ */
9225
+ function writeNewFileOrThrow(path: string, content: string, mode: number = RECORD_FILE_MODE): void {
9226
+ const dir = dirname(path);
9227
+ mkdirSync(dir, { recursive: true, mode: RECORD_DIR_MODE });
9228
+ try {
9229
+ chmodSync(dir, RECORD_DIR_MODE);
9230
+ } catch { /* not ours to tighten (a pre-existing shared dir) — the file mode below still applies */ }
9231
+ writeFileSync(path, content, { flag: 'wx', mode });
9232
+ chmodSync(path, mode);
9233
+ }
9234
+
9235
+ /**
9236
+ * Path containment that survives a symlinked PARENT (round-2 M6). Lexical `startsWith` is not
9237
+ * containment: `features/x/` can be a symlink to `/etc`, and `wx` only refuses a symlink at the
9238
+ * FINAL component. So: walk from the deepest EXISTING ancestor, realpath it, and require the result
9239
+ * to stay under the realpath of the root — and refuse outright if any existing component on the way
9240
+ * is a symlink.
9241
+ */
9242
+ function containedUnderRoot(root: string, target: string): { ok: true; path: string } | { ok: false; why: string } {
9243
+ let realRoot: string;
9244
+ try {
9245
+ realRoot = realpathSync(root);
9246
+ } catch {
9247
+ return { ok: false, why: `the project root ${root} does not resolve` };
9248
+ }
9249
+ const abs = resolve(root, target);
9250
+ const rel = relative(realRoot, abs);
9251
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return { ok: false, why: `${target} resolves outside the project root` };
9252
+
9253
+ // deepest existing ancestor, with every existing component checked for a symlink
9254
+ const parts = rel.split(sep).filter((p) => p !== '');
9255
+ let walked = realRoot;
9256
+ for (const part of parts) {
9257
+ const next = join(walked, part);
9258
+ let st;
9259
+ try {
9260
+ st = lstatSync(next);
9261
+ } catch {
9262
+ break; // this component does not exist yet: nothing below it can be a symlink either
9263
+ }
9264
+ if (st.isSymbolicLink()) return { ok: false, why: `${target} passes through the symlink ${relative(realRoot, next)} — refusing (a symlinked parent can redirect a new file out of the repository)` };
9265
+ walked = next;
9266
+ }
9267
+ let realWalked: string;
9268
+ try {
9269
+ realWalked = realpathSync(walked);
9270
+ } catch {
9271
+ return { ok: false, why: `${target} has an unresolvable parent` };
9272
+ }
9273
+ const realRel = relative(realRoot, realWalked);
9274
+ if (realRel.startsWith('..') || isAbsolute(realRel)) return { ok: false, why: `${target} escapes the project root through its parent directories` };
9275
+ return { ok: true, path: abs };
9276
+ }
9277
+
9278
+ /**
9279
+ * `dz qe-bridge --family claude` — run a Claude reviewer over Step-8-scoped inputs and land a
9280
+ * PARSED signoff (feature qe-bridge-claude, ADR-001).
9281
+ *
9282
+ * The point of the command: when CODEX hosts the run there is no Claude agent plane to dispatch
9283
+ * from, so the cross-family QE rule has no vehicle — `buildReqeBrief` hands the human a `null`
9284
+ * command template for exactly this case. This is that vehicle, callable from a plain shell.
9285
+ *
9286
+ * ISOLATION (round-2 CRITICAL C1): both calls run from an EMPTY temporary directory with the
9287
+ * runtime's own `--safe-mode --strict-mcp-config --tools '' --no-session-persistence`, and the
9288
+ * verdict is read out of the `--output-format json` result envelope. Without that, the reviewer is a
9289
+ * fully customized session running INSIDE the repository under review, and hooks/plugins can print a
9290
+ * complete signoff onto the same stdout the parser reads (MEASURED — see red-green.md).
9291
+ *
9292
+ * Exit codes: 0 = a signoff was PARSED (any grade — the bridge reports, `dz reqe` gates),
9293
+ * 1 = a NAMED failure (record in `.fa-state/qe-bridge/failed-*.json`, raw output beside it,
9294
+ * never at `--out`), 2 = a usage error (nothing spawned, nothing written).
9295
+ */
9296
+ async function cmdQeBridge(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): Promise<number> {
9297
+ const json = flags.has('json');
9298
+ const usage = 'dz qe-bridge --family claude --slug <feature> [--coder-family codex|claude] [--model <id>] [--files a,b] [--out <file>] [--timeout <s>] [--allow-same-family] [--project <dir>] [--json]';
9299
+
9300
+ const usageError = (message: string): number => {
9301
+ write(json ? JSON.stringify({ ok: false, error: message, exitCode: 2 }) : `dz qe-bridge: ${message}\n${usage}`);
9302
+ return 2;
9303
+ };
9304
+
9305
+ if (flags.has('help')) {
9306
+ if (json) {
9307
+ write(JSON.stringify({ help: usage, exitCode: 0 }));
9308
+ return 0;
9309
+ }
9310
+ write(usage);
9311
+ write(' Runs a CLAUDE reviewer over a feature’s Step-8 artifacts from ANY host (a Codex session included)');
9312
+ write(' and writes a parsed SIGNOFF. Exit 0 = a signoff was parsed (ANY grade — the bridge reports, it does');
9313
+ write(' not gate); 1 = a named failure (see features/<slug>/.fa-state/qe-bridge/failed-*.json); 2 = usage.');
9314
+ write(' --family codex is reserved: the forward bridge is `codex exec` (see .claude/rules/feature-adr-conventions.md).');
9315
+ write(' Default report: features/<slug>/08b_reqe_report.md — settle it with');
9316
+ write(' dz reqe --slug <feature> --done --report features/<feature>/08b_reqe_report.md');
9317
+ write(' DISCLOSURE: the bridge sends the extracts you scope (--files, plus the feature’s manifest/ADR/QE report)');
9318
+ write(' to the Claude runtime. It cannot classify secrets — scoping the content you scope is YOUR decision (SEC-5).');
9319
+ return 0;
9320
+ }
9321
+
9322
+ const ALLOWED_FLAGS = new Set(['json', 'help', 'allow-same-family']);
9323
+ for (const flag of flags) {
9324
+ if (!ALLOWED_FLAGS.has(flag)) {
9325
+ return usageError(`unknown option --${flag}` + (['model', 'slug', 'family', 'out', 'files', 'timeout', 'coder-family', 'project'].includes(flag) ? ` (it takes a value: --${flag} <value>)` : ''));
9326
+ }
9327
+ }
9328
+ const ALLOWED_OPTIONS = new Set(['family', 'slug', 'coder-family', 'model', 'files', 'out', 'timeout', 'project']);
9329
+ for (const key of options.keys()) {
9330
+ if (key.startsWith('_positional_')) return usageError(`unexpected argument "${options.get(key)}"`);
9331
+ if (key === 'claude-bin') return usageError(`--claude-bin was removed in favour of the ${QE_BRIDGE_CLAUDE_BIN_ENV} environment variable — a TEST SEAM, recorded loudly in every signoff (binOverride:true). Who reviews is not a casual command-line switch.`);
9332
+ if (!ALLOWED_OPTIONS.has(key)) return usageError(`unknown option --${key}`);
9333
+ }
9334
+
9335
+ // ── family (the reserved codex direction errors with a pointer, never a silent alias) ──
9336
+ const family = options.get('family');
9337
+ if (family === undefined) return usageError('--family claude is required');
9338
+ if (family === 'codex' || family === 'openai') {
9339
+ return usageError('--family codex is reserved — the FORWARD bridge already exists: dispatch `codex exec -m <probed-id> --sandbox read-only "<brief>" < /dev/null` (one bridge per direction; see .claude/rules/feature-adr-conventions.md)');
9340
+ }
9341
+ if (family !== 'claude') return usageError(`unsupported --family ${family} (this leg ships "claude" only)`);
9342
+
9343
+ const slug = options.get('slug') ?? '';
9344
+ if (!isSafeSlug(slug)) return usageError('a kebab-case --slug <feature> is required (no path separators, max 40 chars)');
9345
+
9346
+ const root = resolve(cwd, options.get('project') ?? '.');
9347
+ const featureDir = join(root, 'features', slug);
9348
+ if (!existsSync(featureDir)) return usageError(`no feature directory at features/${slug} — the bridge reviews an existing feature’s artifacts`);
9349
+
9350
+ // ── coder family: the RECORDED DEBT is the authority; the flag may only fill a gap ──
9351
+ //
9352
+ // Round-2 MAJOR M3: round 1 let `--coder-family codex` override a debt that said `claude`, which
9353
+ // turns the loud `--allow-same-family` escape into an optional formality — a Claude-coded feature
9354
+ // could be Claude-reviewed by mis-declaring one flag. The debt is written by the pipeline; the
9355
+ // flag is written by whoever is running the command.
9356
+ let coderFamily: BridgeFamily | null = null;
9357
+ let coderFamilySource = 'flag';
9358
+ let recordedDebtFamily: BridgeFamily | null = null;
9359
+ const duePath = join(featureDir, '.fa-state', 'reqe-due.json');
9360
+ if (existsSync(duePath)) {
9361
+ try {
9362
+ const debt = parseReqeDebt(readFileSync(duePath, 'utf-8'));
9363
+ if (debt) recordedDebtFamily = debt.coderFamily;
9364
+ } catch { /* unreadable debt: treated as absent, and the flag must then be given */ }
9365
+ }
9366
+ const coderOpt = options.get('coder-family');
9367
+ if (coderOpt !== undefined) {
9368
+ // The FLAG surface stays a closed allowlist (the cmdQeBridge discipline — a flag is not a
9369
+ // place to accept whatever parses); the FAMILY behind it comes from the ONE mapper the loop
9370
+ // runner also uses for its same-family comparison (ADR-002 W20/AM-17). A second normalization
9371
+ // here is how a codex-coded run comes to be reviewed by codex under a claude label — the
9372
+ // agreement between the two call sites is pinned by a test, not by care.
9373
+ const asked = coderOpt === 'codex' || coderOpt === 'openai' || coderOpt === 'claude' ? modelFamily(coderOpt) : null;
9374
+ if (asked === null) return usageError(`--coder-family must be codex or claude (got "${coderOpt}")`);
9375
+ if (recordedDebtFamily !== null && recordedDebtFamily !== asked) {
9376
+ return usageError(
9377
+ `--coder-family ${coderOpt} contradicts the recorded debt at features/${slug}/.fa-state/reqe-due.json, which says the coder family was ${recordedDebtFamily}. ` +
9378
+ 'The debt is the authority: it was written by the run being reviewed, the flag by whoever is invoking this command. ' +
9379
+ 'Refusing rather than letting a flag re-label who wrote the code — that label is what decides whether this review is cross-family. ' +
9380
+ 'Fix the flag, or correct the debt file if IT is wrong.',
9381
+ );
9382
+ }
9383
+ coderFamily = asked;
9384
+ } else if (recordedDebtFamily !== null) {
9385
+ coderFamily = recordedDebtFamily;
9386
+ coderFamilySource = 'reqe-due.json';
9387
+ }
9388
+ if (coderFamily === null) {
9389
+ return usageError(`--coder-family codex|claude is required (no readable re-QE debt at features/${slug}/.fa-state/reqe-due.json to read it from) — who WROTE the code decides whether this review is cross-family`);
9390
+ }
9391
+
9392
+ // ── --out: under the repo, no traversal, no control characters, no symlinked parents ──
9393
+ const outOpt = options.get('out') ?? join('features', slug, '08b_reqe_report.md');
9394
+ if (hasUnsafePathChars(outOpt) || hasDotDotSegment(outOpt)) return usageError('--out must not contain control characters or ".." segments');
9395
+ const outCheck = containedUnderRoot(root, outOpt);
9396
+ if (!outCheck.ok) return usageError(`--out ${outCheck.why}`);
9397
+ const outPath = outCheck.path;
9398
+
9399
+ // ── timeouts: Number.isFinite-safe clamp (the numeric-clamp lesson) ──
9400
+ let timeoutS = QE_BRIDGE_DEFAULT_TIMEOUT_S;
9401
+ const timeoutRaw = options.get('timeout');
9402
+ if (timeoutRaw !== undefined) {
9403
+ const n = Number(timeoutRaw);
9404
+ if (!Number.isFinite(n)) return usageError(`--timeout must be a number of seconds (got "${timeoutRaw}")`);
9405
+ timeoutS = Math.min(QE_BRIDGE_MAX_TIMEOUT_S, Math.max(QE_BRIDGE_MIN_TIMEOUT_S, Math.floor(n)));
9406
+ }
9407
+
9408
+ // ── model candidates: an allowlist says a name is spellable, only the probe says it answers ──
9409
+ const modelOpt = options.get('model');
9410
+ if (modelOpt !== undefined && !isSafeClaudeId(modelOpt)) {
9411
+ return usageError(`unsafe --model id "${modelOpt}" — ids must match /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/ (a leading "-" would become an option)`);
9412
+ }
9413
+ const candidates = modelOpt !== undefined ? [modelOpt] : Object.keys(KNOWN_CLAUDE);
9414
+
9415
+ const binRaw = process.env[QE_BRIDGE_CLAUDE_BIN_ENV];
9416
+ const binOverride = typeof binRaw === 'string' && binRaw.trim() !== '';
9417
+ const binOpt = binOverride ? binRaw.trim() : 'claude';
9418
+ if (hasUnsafePathChars(binOpt)) return usageError(`${QE_BRIDGE_CLAUDE_BIN_ENV} must not contain control characters`);
9419
+ let resolvedBin = binOpt;
9420
+ if (binOverride) {
9421
+ try {
9422
+ resolvedBin = realpathSync(binOpt);
9423
+ } catch {
9424
+ resolvedBin = binOpt; // unresolvable: recorded as given, and the spawn will name the failure
9425
+ }
9426
+ }
9427
+
9428
+ // ── extracts: SCOPED, never a repo dump ──
9429
+ const extracts: NamedExtract[] = [];
9430
+ const pushIfPresent = (rel: string, label: string): void => {
9431
+ const p = join(root, rel);
9432
+ try {
9433
+ if (!lstatSync(p).isFile()) return;
9434
+ extracts.push({ label, text: readFileSync(p, 'utf-8') });
9435
+ } catch { /* absent: the brief says so by omission */ }
9436
+ };
9437
+ pushIfPresent(join('features', slug, '07_code_changes', 'change_manifest.md'), `features/${slug}/07_code_changes/change_manifest.md`);
9438
+ const adrDir = join(featureDir, '03_adr');
9439
+ if (existsSync(adrDir)) {
9440
+ for (const f of readdirSync(adrDir).filter((n) => n.endsWith('.md')).sort()) {
9441
+ pushIfPresent(join('features', slug, '03_adr', f), `features/${slug}/03_adr/${f}`);
9442
+ }
9443
+ }
9444
+ pushIfPresent(join('features', slug, '08_qe_report.md'), `features/${slug}/08_qe_report.md (the review ON RECORD — judge it, do not inherit it)`);
9445
+
9446
+ const filesOpt = options.get('files');
9447
+ for (const rel of (filesOpt ?? '').split(',').map((s) => s.trim()).filter((s) => s !== '')) {
9448
+ if (hasUnsafePathChars(rel) || hasDotDotSegment(rel) || isAbsolute(rel)) {
9449
+ return usageError(`--files entry "${rel}" must be a repo-relative path with no ".." segments and no control characters`);
9450
+ }
9451
+ const check = containedUnderRoot(root, rel);
9452
+ if (!check.ok) return usageError(`--files entry "${check.why}"`);
9453
+ let st;
9454
+ try {
9455
+ st = lstatSync(check.path);
9456
+ } catch {
9457
+ return usageError(`--files entry "${rel}" does not exist`);
9458
+ }
9459
+ if (!st.isFile()) return usageError(`--files entry "${rel}" is not a regular file (symlinks are refused)`);
9460
+ extracts.push({ label: rel, text: readFileSync(check.path, 'utf-8') });
9461
+ }
9462
+ if (extracts.length === 0) {
9463
+ return usageError(`nothing to review: features/${slug} has no change manifest, ADR or QE report, and no --files were given`);
9464
+ }
9465
+
9466
+ // ── run identity + the audit bundle (round-2 M7) ──
9467
+ //
9468
+ // R3-2: the state directory is checked with the SAME containment walk as `--out`, BEFORE anything
9469
+ // is created in it. Round 2 contained the record PATHS but not the directory they live in, so a
9470
+ // symlinked `.fa-state/qe-bridge` (or `.fa-state`) silently redirected every write — and every
9471
+ // chmod — outside the repository. A guard that covers the leaves but not the branch is not a guard.
9472
+ const stateDirRel = join('features', slug, '.fa-state', 'qe-bridge');
9473
+ const stateCheck = containedUnderRoot(root, stateDirRel);
9474
+ if (!stateCheck.ok) return usageError(`the audit state directory ${stateCheck.why}`);
9475
+ const stateDir = stateCheck.path;
9476
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
9477
+ const runId = `${stamp}-${randomBytes(4).toString('hex')}`;
9478
+ const requestedOut = relative(root, outPath);
9479
+ const uniquePath = (base: string, ext: string): string => {
9480
+ let candidate = `${base}${ext}`;
9481
+ for (let n = 2; existsSync(candidate); n += 1) candidate = `${base}-${n}${ext}`;
9482
+ return candidate;
9483
+ };
9484
+ /** Retain the raw reviewer stdout. THROWS on failure (R3-3): round 2 swallowed the error and
9485
+ * recorded `rawStdoutFile: null`, which turns "we could not keep the evidence" into a field nobody
9486
+ * reads. On the success path an unretainable stdout fails the run; on a failure path the forensics
9487
+ * are best-effort, because the run is already failing for a named reason. */
9488
+ const retainRaw = (stdout: string, kind: 'signoff' | 'failed'): string | null => {
9489
+ if (stdout === '') return null;
9490
+ const p = uniquePath(join(stateDir, `${kind}-${runId}`), '.stdout.txt');
9491
+ writeNewFileOrThrow(p, stdout);
9492
+ return relative(root, p);
9493
+ };
9494
+ const retainRawBestEffort = (stdout: string, kind: 'signoff' | 'failed'): string | null => {
9495
+ try {
9496
+ return retainRaw(stdout, kind);
9497
+ } catch {
9498
+ return null;
9499
+ }
9500
+ };
9501
+
9502
+ let promptSha256: string | null = null;
9503
+
9504
+ const failRun = (
9505
+ reason: BridgeFailureReason,
9506
+ detail: string,
9507
+ model: string | null,
9508
+ forensics?: { stdout: string; stderr: string },
9509
+ ): number => {
9510
+ const emittedAt = new Date().toISOString();
9511
+ const rawStdoutFile = forensics === undefined ? null : retainRawBestEffort(forensics.stdout, 'failed');
9512
+ const record = buildBridgeFailureRecord(reason, detail, {
9513
+ slug,
9514
+ model,
9515
+ emittedAt,
9516
+ runId,
9517
+ claudeBin: resolvedBin,
9518
+ binOverride,
9519
+ requestedOut,
9520
+ reportWritten: false,
9521
+ rawStdoutFile,
9522
+ promptSha256,
9523
+ });
9524
+ let recordPath = '';
9525
+ try {
9526
+ recordPath = uniquePath(join(stateDir, `failed-${runId}`), '.json');
9527
+ writeNewFileOrThrow(recordPath, `${JSON.stringify(record, null, 2)}\n`);
9528
+ if (forensics && forensics.stderr.trim() !== '') writeNewFileOrThrow(uniquePath(join(stateDir, `failed-${runId}`), '.stderr.txt'), forensics.stderr);
9529
+ } catch (primaryError) {
9530
+ // R3-1: the one condition that breaks the record medium ITSELF (`audit-write-failed`) must
9531
+ // still leave a named record behind, or the closed taxonomy has a member nothing can evidence.
9532
+ // Fall back ONE level up, inside the same per-feature state plane — not to an invented path.
9533
+ try {
9534
+ recordPath = uniquePath(join(featureDir, '.fa-state', `qe-bridge-fallback-${runId}`), '.json');
9535
+ writeNewFileOrThrow(recordPath, `${JSON.stringify({ ...record, fallbackFrom: relative(root, stateDir), fallbackReason: String(primaryError) }, null, 2)}\n`);
9536
+ } catch (fallbackError) {
9537
+ write(json ? JSON.stringify({ ok: false, reason, detail, recordError: String(fallbackError), exitCode: 1 }) : `dz qe-bridge: ${reason} — ${detail}\n (the failure record could NOT be written: ${String(fallbackError)})`);
9538
+ return 1;
9539
+ }
9540
+ }
9541
+ if (json) write(JSON.stringify({ ok: false, reason, detail, record: relative(root, recordPath), runId, reportWritten: false, requestedOut, exitCode: 1 }));
9542
+ else {
9543
+ write(`dz qe-bridge: FAILED — ${reason}`);
9544
+ write(` ${detail}`);
9545
+ write(` record: ${relative(root, recordPath)}`);
9546
+ write(` no report was written at ${requestedOut} — an unparseable or absent review is never a passing one.`);
9547
+ }
9548
+ return 1;
9549
+ };
9550
+
9551
+ // ── the prompt (built BEFORE any model call: a same-family refusal must cost nothing) ──
9552
+ const built = buildBridgePrompt({ slug, coderFamily, allowSameFamily: flags.has('allow-same-family'), extracts });
9553
+ if (!built.ok) return failRun(built.reason, built.detail, null);
9554
+ const prompt = built.prompt;
9555
+ promptSha256 = createHash('sha256').update(prompt).digest('hex');
9556
+
9557
+ // ── the isolated working directory: an EMPTY dir, so project-scoped discovery finds nothing ──
9558
+ let isolatedCwd: string;
9559
+ try {
9560
+ isolatedCwd = mkdtempSync(join(tmpdir(), 'dz-qe-bridge-iso-'));
9561
+ } catch (error) {
9562
+ return failRun('probe-failed', `could not create an isolated working directory for the reviewer: ${String(error)}`, null);
9563
+ }
9564
+ const cleanupIsolated = (): void => {
9565
+ try {
9566
+ rmSync(isolatedCwd, { recursive: true, force: true });
9567
+ } catch { /* a leftover empty temp dir is not worth failing a review over */ }
9568
+ };
9569
+
9570
+ try {
9571
+ // ── probe: the allowlist is a search order, the probe is the answer ──
9572
+ let probed: string | null = null;
9573
+ const probeNotes: string[] = [];
9574
+ for (const id of candidates) {
9575
+ const probeArgs = claudeProbeArgs(id);
9576
+ if (probeArgs === null) {
9577
+ probeNotes.push(`${id}: unsafe id, never spawned`);
9578
+ continue;
9579
+ }
9580
+ const run = await runClaudeBridge(binOpt, probeArgs, '', QE_BRIDGE_PROBE_TIMEOUT_MS, isolatedCwd);
9581
+ if (run.spawnError !== null) {
9582
+ const enoent = /ENOENT|not found|no such file/i.test(run.spawnError);
9583
+ return failRun(
9584
+ enoent ? 'claude-not-found' : 'probe-failed',
9585
+ enoent
9586
+ ? `\`${binOpt}\` is not runnable (${run.spawnError}) — install/authenticate the Claude CLI, or point ${QE_BRIDGE_CLAUDE_BIN_ENV} at it`
9587
+ : run.spawnError,
9588
+ null,
9589
+ );
9590
+ }
9591
+ if (run.timedOut) {
9592
+ probeNotes.push(`${id}: probe timed out after ${QE_BRIDGE_PROBE_TIMEOUT_MS / 1000}s`);
9593
+ continue;
9594
+ }
9595
+ if (interpretClaudeProbe({ stdout: run.stdout, exitCode: run.exitCode ?? 1 })) {
9596
+ probed = id;
9597
+ break;
9598
+ }
9599
+ const loginish = classifyClaudeStderr(run.stderr) === 'claude-not-logged-in';
9600
+ if (loginish) {
9601
+ return failRun('claude-not-logged-in', `the liveness probe for ${id} failed with a login error: ${run.stderr.trim().split('\n')[0]}`, null, { stdout: run.stdout, stderr: run.stderr });
9602
+ }
9603
+ probeNotes.push(`${id}: exit ${String(run.exitCode)}, no model-authored \`OK\` in the result envelope (${run.stdout.length} chars of stdout)${run.stderr.trim() === '' ? '' : ` (stderr: ${run.stderr.trim().split('\n')[0]})`}`);
9604
+ }
9605
+ if (probed === null) {
9606
+ return failRun('probe-failed', `no candidate model answered the liveness probe — ${probeNotes.join('; ')}`, null);
9607
+ }
9608
+
9609
+ // ── the review call ──
9610
+ const reviewArgs = claudeReviewArgs(probed);
9611
+ if (reviewArgs === null) return failRun('probe-failed', `the probed id ${probed} failed id validation on the review path`, probed);
9612
+ const started = Date.now();
9613
+ const review = await runClaudeBridge(binOpt, reviewArgs, prompt, timeoutS * 1000, isolatedCwd);
9614
+ const elapsedMs = Date.now() - started;
9615
+
9616
+ if (review.spawnError !== null) {
9617
+ const enoent = /ENOENT|not found|no such file/i.test(review.spawnError);
9618
+ return failRun(enoent ? 'claude-not-found' : 'exit-nonzero', review.spawnError, probed, { stdout: review.stdout, stderr: review.stderr });
9619
+ }
9620
+ if (review.timedOut) {
9621
+ return failRun('timeout', `the review call exceeded --timeout ${timeoutS}s and the child was killed (timeout-${timeoutS}s)`, probed, { stdout: review.stdout, stderr: review.stderr });
9622
+ }
9623
+ if (review.exitCode !== 0) {
9624
+ const reason = classifyClaudeStderr(review.stderr);
9625
+ return failRun(
9626
+ reason,
9627
+ `\`${binOpt}\` exited ${String(review.exitCode)}${review.stderr.trim() === '' ? ' with no stderr' : `: ${review.stderr.trim().split('\n')[0]}`}` +
9628
+ (reason === 'exit-nonzero' ? ' — the cause is NOT classified: from outside the process a limit-exhaustion death and a crash look alike, so the raw evidence is saved instead of a guess.' : ''),
9629
+ probed,
9630
+ { stdout: review.stdout, stderr: review.stderr },
9631
+ );
9632
+ }
9633
+ if (review.stdout.trim() === '') {
9634
+ return failRun('empty-output', `the review call exited 0 with no output (${review.stdout.length} chars) — silence is not a clean review`, probed, { stdout: review.stdout, stderr: review.stderr });
9635
+ }
9636
+
9637
+ // ── PARSE, never synthesize ──
9638
+ const emittedAt = new Date().toISOString();
9639
+ const parsed = parseBridgeOutput(review.stdout, { slug, coderFamily, model: probed, elapsedMs, promptSha256, emittedAt });
9640
+ if (!parsed.ok) {
9641
+ // No `?? <some named reason>` fallback: a state the parser did not name is its OWN failure
9642
+ // (round-2 MAJOR M5 — laundering an unknown state into `no-grade-marker` reads like a verdict
9643
+ // about the reviewer's text when it is really a verdict about our own code).
9644
+ const reason: BridgeFailureReason = parsed.reason;
9645
+ return failRun(reason, parsed.detail, probed, { stdout: review.stdout, stderr: review.stderr });
9646
+ }
9647
+ const signoff = parsed.signoff;
9648
+
9649
+ // ── landing (R3-3 ordering): AUDIT FIRST, then the report, then the truth about the report ──
9650
+ //
9651
+ // Round 2 wrote the report BEFORE the record, so a crash between the two left a report on disk
9652
+ // and a record that said `reportWritten:false` — metadata that lies in the direction of "no
9653
+ // review happened" while a review report sits next to it. The order below can only ever
9654
+ // understate: the record exists first saying false, the report lands, then the record is
9655
+ // corrected. A crash at any point leaves a record that is true or pessimistic, never optimistic.
9656
+ let rawStdoutFile: string | null;
9657
+ try {
9658
+ rawStdoutFile = retainRaw(review.stdout, 'signoff');
9659
+ } catch (error) {
9660
+ return failRun(
9661
+ 'audit-write-failed',
9662
+ `the review was PARSED (grade ${signoff.grade}) but its raw stdout could not be retained: ${String(error)} — an unauditable success is not a success, so the run FAILS rather than shipping a verdict nobody can re-derive`,
9663
+ probed,
9664
+ { stdout: review.stdout, stderr: review.stderr },
9665
+ );
9666
+ }
9667
+
9668
+ const recordText = (reportWritten: boolean): string => `${JSON.stringify(buildBridgeSignoffRecord(signoff, {
9669
+ runId,
9670
+ claudeBin: resolvedBin,
9671
+ binOverride,
9672
+ requestedOut,
9673
+ reportWritten,
9674
+ rawStdoutFile,
9675
+ promptSha256,
9676
+ ...(parsed.channels === undefined ? {} : { channels: parsed.channels }),
9677
+ }), null, 2)}\n`;
9678
+
9679
+ let signoffPath: string;
9680
+ try {
9681
+ signoffPath = uniquePath(join(stateDir, `signoff-${runId}`), '.json');
9682
+ writeNewFileOrThrow(signoffPath, recordText(false));
9683
+ } catch (error) {
9684
+ return failRun(
9685
+ 'audit-write-failed',
9686
+ `the review was PARSED (grade ${signoff.grade}) but the signoff record could not be written: ${String(error)} — the verdict exists and cannot be persisted, so the run FAILS rather than reporting an unrecorded success`,
9687
+ probed,
9688
+ { stdout: review.stdout, stderr: review.stderr },
9689
+ );
9690
+ }
9691
+
9692
+ let reportError: unknown = null;
9693
+ try {
9694
+ writeNewFileOrThrow(outPath, renderBridgeReport(signoff), 0o600);
9695
+ } catch (error) {
9696
+ reportError = error;
9697
+ }
9698
+
9699
+ if (reportError === null) {
9700
+ // the ONLY moment `reportWritten:true` may appear: after the report is on disk
9701
+ try {
9702
+ // ATOMIC (R4-1): write a sibling temp file, then rename() over the original. On the same
9703
+ // filesystem rename is atomic, so a reader — or a crash — sees the OLD complete record or
9704
+ // the NEW complete record, never a truncated one. Round 3 truncated and rewrote in place,
9705
+ // which made the "a crash leaves a record that is true or pessimistic" claim untrue in the
9706
+ // one case it was about.
9707
+ const tmpPath = `${signoffPath}.tmp.${process.pid}`;
9708
+ writeNewFileOrThrow(tmpPath, recordText(true));
9709
+ if (process.env[QE_BRIDGE_FAILPOINT_ENV] === 'hang-before-rename') {
9710
+ // test-only: stop dead INSIDE the window, so a SIGKILL can prove the property
9711
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 600_000);
9712
+ }
9713
+ renameSync(tmpPath, signoffPath);
9714
+ chmodSync(signoffPath, RECORD_FILE_MODE);
9715
+ } catch (error) {
9716
+ return failRun(
9717
+ 'audit-write-failed',
9718
+ `the report landed at ${requestedOut} but the signoff record could not be updated to say so: ${String(error)} — the record on disk understates (reportWritten:false); re-run rather than trusting a record that disagrees with the tree`,
9719
+ probed,
9720
+ { stdout: review.stdout, stderr: review.stderr },
9721
+ );
9722
+ }
9723
+ } else {
9724
+ const detail = `the review was PARSED (grade ${signoff.grade}) but ${requestedOut} could not be written: ${String(reportError)} — prior evidence is never overwritten and a symlinked target is never followed; the verdict is preserved at ${relative(root, signoffPath)} with reportWritten:false`;
9725
+ return failRun('report-write-failed', detail, probed, { stdout: '', stderr: '' });
9726
+ }
9727
+
9728
+ if (json) {
9729
+ write(JSON.stringify({
9730
+ ok: true,
9731
+ grade: signoff.grade,
9732
+ gradedBy: signoff.gradedBy,
9733
+ coderFamily: signoff.coderFamily,
9734
+ coderFamilySource,
9735
+ findings: signoff.findings.length,
9736
+ report: requestedOut,
9737
+ reportWritten: true,
9738
+ signoff: relative(root, signoffPath),
9739
+ rawStdout: rawStdoutFile,
9740
+ runId,
9741
+ binOverride,
9742
+ claudeBin: resolvedBin,
9743
+ elapsedMs,
9744
+ promptChars: prompt.length,
9745
+ promptSha256,
9746
+ channels: parsed.channels,
9747
+ exitCode: 0,
9748
+ }));
9749
+ } else {
9750
+ write(`dz qe-bridge: GRADE ${signoff.grade} from claude/${signoff.gradedBy.model} — ${signoff.findings.length} finding(s) in ${Math.round(elapsedMs / 1000)}s`);
9751
+ if (binOverride) write(` ⚠ reviewer executable OVERRIDDEN via ${QE_BRIDGE_CLAUDE_BIN_ENV}: ${resolvedBin} (recorded as binOverride:true — this signoff does not prove Anthropic's runtime answered)`);
9752
+ write(` report: ${requestedOut}`);
9753
+ write(` signoff: ${relative(root, signoffPath)}`);
9754
+ write(` settle: dz reqe --slug ${slug} --done --report ${requestedOut}`);
9755
+ write(' the bridge REPORTS (any grade exits 0); gating stays with dz reqe and the host pipeline.');
9756
+ }
9757
+ return 0;
9758
+ } finally {
9759
+ cleanupIsolated();
9760
+ }
9761
+ }
9762
+
9763
+
7645
9764
  function cmdScore(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
7646
9765
  const json = flags.has('json');
7647
9766
  if (flags.has('help')) {
@@ -9334,6 +11453,8 @@ async function cmdImportEcc(options: Map<string, string>, flags: Set<string>, cw
9334
11453
  export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9335
11454
  const cwd = io.cwd ?? process.cwd();
9336
11455
  const write: Write = io.write ?? ((line) => { console.log(line); });
11456
+ // Diagnostics go to stderr so `dz <cmd> > out.txt` yields clean data (feature dz-cli-defects).
11457
+ const writeErr: WriteErr = io.writeErr ?? ((line) => { console.error(line); });
9337
11458
  // Lazy STDIN reader — only `dz brain ground` reads it, and only when no positional prompt is
9338
11459
  // given. Never blocks: injected `io.stdin` wins; else read fd 0 synchronously, but bail to '' on
9339
11460
  // a TTY (nothing piped) or any read error. Grounding must never hang waiting on an empty pipe.
@@ -9376,14 +11497,14 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9376
11497
  try {
9377
11498
  switch (command) {
9378
11499
  case 'init':
9379
- return await cmdInit(options, flags, cwd, write);
11500
+ return await cmdInit(options, flags, cwd, write, writeErr);
9380
11501
  case 'verify':
9381
- return await cmdVerify(options, cwd, write);
11502
+ return await cmdVerify(options, cwd, write, writeErr);
9382
11503
  case 'sync':
9383
11504
  case 'update':
9384
- return await cmdSync(options, flags, cwd, write);
11505
+ return await cmdSync(options, flags, cwd, write, writeErr);
9385
11506
  case 'list':
9386
- return cmdList(options, cwd, write);
11507
+ return cmdList(options, cwd, write, writeErr);
9387
11508
  case 'create-skill':
9388
11509
  return cmdCreateSkill(options, flags, cwd, write);
9389
11510
  case 'info':
@@ -9391,6 +11512,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9391
11512
  case 'scout':
9392
11513
  return await cmdScout(options, flags, cwd, write);
9393
11514
  case 'workflow':
11515
+ // `run` is ASYNC (it drives child processes); every other subcommand stays sync.
11516
+ if ((options.get('_positional_0') ?? '') === 'run') return await cmdWorkflowRun(options, optionLists, flags, cwd, write);
9394
11517
  return cmdWorkflow(options, flags, cwd, write);
9395
11518
  case 'workflow-lint':
9396
11519
  return cmdWorkflowLint(options, flags, cwd, write);
@@ -9401,7 +11524,7 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9401
11524
  case 'doctor':
9402
11525
  return await cmdDoctor(options, flags, cwd, write);
9403
11526
  case 'install':
9404
- return await cmdInstall(options, flags, cwd, write, io.installRunner);
11527
+ return await cmdInstall(options, flags, cwd, write, writeErr, io.installRunner);
9405
11528
  case 'bundle':
9406
11529
  return cmdBundle(options, flags, cwd, write);
9407
11530
  case 'teach':
@@ -9429,17 +11552,17 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9429
11552
  case 'verify-pack':
9430
11553
  return cmdVerifyPack(options, flags, cwd, write);
9431
11554
  case 'setup':
9432
- return await cmdSetup(options, flags, cwd, write);
11555
+ return await cmdSetup(options, flags, cwd, write, writeErr);
9433
11556
  case 'pretrain':
9434
11557
  return cmdPretrain(options, cwd, write);
9435
11558
  case 'compose':
9436
- return cmdCompose(options, cwd, write);
11559
+ return cmdCompose(options, cwd, write, writeErr);
9437
11560
  case 'diff':
9438
11561
  return cmdDiff(options, cwd, write);
9439
11562
  case 'recommend':
9440
11563
  return cmdRecommend(options, cwd, write);
9441
11564
  case 'upgrade':
9442
- return cmdUpgrade(options, flags, cwd, write);
11565
+ return cmdUpgrade(options, flags, cwd, write, writeErr);
9443
11566
  case 'auto-canonicalize':
9444
11567
  return await cmdAutoCanonicalize(options, cwd, write);
9445
11568
  case 'publish':
@@ -9447,7 +11570,7 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9447
11570
  case 'release':
9448
11571
  return cmdRelease(options, flags, cwd, write, io.releaseRunner);
9449
11572
  case 'parity':
9450
- return cmdParity(options, flags, write);
11573
+ return cmdParity(options, flags, write, writeErr);
9451
11574
  case 'registry':
9452
11575
  return cmdRegistry(options, cwd, write);
9453
11576
  case 'benchmark':
@@ -9458,6 +11581,10 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9458
11581
  return await cmdSyncUpstream(options, flags, cwd, write);
9459
11582
  case 'drift-check':
9460
11583
  return cmdDriftCheck(options, flags, cwd, write);
11584
+ case 'hooks-sync':
11585
+ return cmdHooksSync(options, flags, cwd, write, writeErr);
11586
+ case 'agents-sync':
11587
+ return cmdAgentsSync(options, flags, cwd, write, writeErr);
9461
11588
  case 'sync-canonical':
9462
11589
  return cmdSyncCanonical(options, flags, cwd, write);
9463
11590
  case 'plugin':
@@ -9475,7 +11602,7 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9475
11602
  case 'retro':
9476
11603
  return await cmdRetro(options, flags, cwd, write);
9477
11604
  case 'feature-adr-setup':
9478
- return cmdFeatureAdrSetup(options, flags, cwd, write);
11605
+ return cmdFeatureAdrSetup(options, flags, cwd, write, writeErr);
9479
11606
  case 'challenge':
9480
11607
  return cmdChallenge(options, flags, cwd, write);
9481
11608
  case 'discrimination-check':
@@ -9494,6 +11621,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9494
11621
  return cmdScore(options, flags, cwd, write);
9495
11622
  case 'reqe':
9496
11623
  return cmdReqe(options, flags, cwd, write);
11624
+ case 'qe-bridge':
11625
+ return await cmdQeBridge(options, flags, cwd, write);
9497
11626
  case 'backlog':
9498
11627
  return await cmdBacklog(options, flags, cwd, write);
9499
11628
  case 'routing':
@@ -9512,7 +11641,9 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9512
11641
  return 1;
9513
11642
  }
9514
11643
  } catch (error) {
9515
- write(`dz: ${error instanceof Error ? error.message : String(error)}`);
11644
+ // stderr, not stdout: an uncaught failure is a diagnostic, and routing it through
11645
+ // `write` is what made `dz list > skills.txt` write the error into the data file.
11646
+ writeErr(`dz: ${error instanceof Error ? error.message : String(error)}`);
9516
11647
  return 1;
9517
11648
  }
9518
11649
  }