@dzhechkov/harness-cli 0.5.0 → 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,8 +7,8 @@
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
 
@@ -56,11 +56,36 @@ import {
56
56
  runInitGeminiMd,
57
57
  runSyncAgentsPolicy,
58
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,
59
82
  POLICY_SOURCES,
60
83
  detectPolicyDrift,
61
84
  hasPolicyFence,
62
85
  TARGET_NAMES,
63
86
  buildParityMatrix,
87
+ downgradeForStaleEvidence,
88
+ findStaleTranscriptEvidence,
64
89
  TARGET_CAPABILITIES,
65
90
  TARGET_SHORT_LABELS,
66
91
  WORKFLOW_TEMPLATES_RETIRED_MESSAGE,
@@ -331,6 +356,24 @@ import {
331
356
  renderDomainBoostNote,
332
357
  renderDomainCutNote,
333
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,
334
377
  buildReqeBrief,
335
378
  settleReqeDebt,
336
379
  renderReqeList,
@@ -368,7 +411,7 @@ import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, S
368
411
  const USAGE = `dz - DZ cross-platform harness CLI
369
412
 
370
413
  Usage:
371
- 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)
372
415
  dz verify [--skills-dir <dir>] [--target <name>]
373
416
  dz sync [--canonical <dir>] [--project <dir>] [--dry-run] [--force]
374
417
  dz update (alias of sync)
@@ -403,6 +446,7 @@ Usage:
403
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)
404
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)
405
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)
406
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)
407
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)
408
452
  dz backlog list [--status <s>] [--goal <id>] [--project <dir>] [--json] (list captured ideas, filterable by status/goal)
@@ -417,7 +461,7 @@ Usage:
417
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)
418
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)
419
463
  dz backlog harmonize [--apply] [--threshold <0-1>] [--project <dir>] [--json] (batch semantic dedup of the backlog ideas; --dry-run default, --apply snapshots first)
420
- 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)
421
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)
422
466
  dz teach --from-json <file> [--project <dir>] [--no-mirror] (bulk-import a 'dz recall --all --json' export — share a learned store across machines)
423
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)
@@ -467,6 +511,18 @@ Usage:
467
511
 
468
512
  Global: --version | -v [--json] (prints this CLI's own semver on one line, exit 0; "unknown" + exit 1 when unresolvable)
469
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
+
470
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)
471
527
 
472
528
  Targets: ${TARGET_NAMES.join(', ')}
@@ -730,6 +786,19 @@ async function cmdInit(options: Map<string, string>, flags: Set<string>, cwd: st
730
786
  write(` (searched ${r.dirsSearched} skill directories)`);
731
787
  }
732
788
  writeMissingSkillsHint(write, r.missing, presetName);
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
+ }
733
802
  // Skip-and-collect must not become skip-and-SILENCE: a skill that failed to load is
734
803
  // named on stderr and the command exits 1 (it exited 1 before too — by throwing).
735
804
  if (r.failures.length > 0 || r.applyFailures.length > 0) {
@@ -748,7 +817,7 @@ async function cmdInit(options: Map<string, string>, flags: Set<string>, cwd: st
748
817
  for (const line of formatSkillApplyFailures(r.applyFailures)) writeErr(line);
749
818
  return 1;
750
819
  }
751
- return 0;
820
+ return codexHooksOk ? 0 : 1;
752
821
  }
753
822
 
754
823
  async function cmdVerify(options: Map<string, string>, cwd: string, write: Write, writeErr: WriteErr): Promise<number> {
@@ -4087,6 +4156,17 @@ async function cmdSetup(options: Map<string, string>, flags: Set<string>, cwd: s
4087
4156
  write(`║ (no skills resolved) ║`);
4088
4157
  }
4089
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
+
4090
4170
  write(`╠══════════════════════════════════════════════════════╣`);
4091
4171
  write(`║ Setup: ${String(setupResult.completed).padStart(2)} done, ${String(setupResult.skipped).padStart(2)} skipped ║`);
4092
4172
  // Honest label derived from the ACTUAL wiring (runSetup's 'agentdb wiring' invariant check),
@@ -4106,7 +4186,9 @@ async function cmdSetup(options: Map<string, string>, flags: Set<string>, cwd: s
4106
4186
  + (install.dirsSearched > 1 ? ` (searched ${install.dirsSearched} skill dirs)` : ''));
4107
4187
  writeMissingSkillsHint(write, install.missing, selectArg !== undefined ? undefined : preset);
4108
4188
  }
4109
- 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;
4110
4192
  }
4111
4193
 
4112
4194
  function cmdPretrain(options: Map<string, string>, cwd: string, write: Write): number {
@@ -4841,6 +4923,20 @@ function cmdParity(options: Map<string, string>, flags: Set<string>, write: Writ
4841
4923
  }
4842
4924
 
4843
4925
  const matrix = buildParityMatrix();
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 ?? ''})`);
4844
4940
  // Site 8 of the D3 rewiring, closed in fix round 1 (QE F1). It shipped spelling its
4845
4941
  // own bare guard `TARGET_NAMES.includes(...)` and was therefore invisible to the AM-2
4846
4942
  // grep-guard, which searched for the token `isTargetName(` — a PRESENCE check on one
@@ -4866,14 +4962,22 @@ function cmdParity(options: Map<string, string>, flags: Set<string>, write: Writ
4866
4962
  }
4867
4963
 
4868
4964
  if (json) {
4869
- const rows = matrix.map((r) => ({
4870
- id: r.feature.id,
4871
- title: r.feature.title,
4872
- cells: target !== undefined ? { [target]: r.cells[target] } : r.cells,
4873
- }));
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
+ });
4874
4971
  // A filtered response stays internally consistent: capabilities are filtered too (Codex QE gap 9).
4875
4972
  const caps = target !== undefined ? { [target]: TARGET_CAPABILITIES[target] } : TARGET_CAPABILITIES;
4876
- write(JSON.stringify({ targets: target !== undefined ? [target] : TARGET_NAMES, capabilities: caps, features: rows }, null, 2));
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));
4877
4981
  return 0;
4878
4982
  }
4879
4983
 
@@ -4881,11 +4985,17 @@ function cmdParity(options: Map<string, string>, flags: Set<string>, write: Writ
4881
4985
  const t = target;
4882
4986
  write(`\ndz parity — ${t} (capabilities: ${TARGET_CAPABILITIES[t].join(', ')})\n`);
4883
4987
  for (const r of matrix) {
4884
- const c = r.cells[t];
4885
- const icon = c.level === 'full' ? '✓' : c.level === 'manual' ? '◐' : '—';
4886
- write(` ${icon} ${r.feature.title.padEnd(58)} ${c.level === 'none' ? 'not available on this target' : `via ${c.via ?? ''}`}`);
4887
- }
4888
- 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);
4889
4999
  return 0;
4890
5000
  }
4891
5001
 
@@ -4896,8 +5006,8 @@ function cmdParity(options: Map<string, string>, flags: Set<string>, write: Writ
4896
5006
  write(` ${'feature'.padEnd(52)} ${TARGET_NAMES.map((t) => (short[t] ?? t).padStart(4)).join('')}`);
4897
5007
  for (const r of matrix) {
4898
5008
  const cells = TARGET_NAMES.map((t) => {
4899
- const c = r.cells[t];
4900
- 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);
4901
5011
  }).join('');
4902
5012
  write(` ${r.feature.title.slice(0, 52).padEnd(52)} ${cells}`);
4903
5013
  }
@@ -5911,11 +6021,18 @@ function cmdHooksSync(
5911
6021
  }
5912
6022
 
5913
6023
  const codexHome = options.get('codex-home');
5914
- const report = runSyncCodexHooks({
5915
- ...(codexHome !== undefined ? { codexHome } : {}),
5916
- check: flags.has('check'),
5917
- remove: flags.has('remove'),
5918
- });
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
+ );
5919
6036
 
5920
6037
  if (json) {
5921
6038
  write(JSON.stringify({ ...report, exitCode: report.exitCode }));
@@ -5934,18 +6051,193 @@ function cmdHooksSync(
5934
6051
  return report.exitCode;
5935
6052
  }
5936
6053
 
5937
- // AM-17 / G-G: the success word is reachable ONLY from armed AND trusted. The trust clause is
5938
- // asserted HERE as well as in the exit map — a read-only `--check` that could not establish trust
5939
- // once returned exit 0 with `trust: 'unknown'`, and this line printed "ready" for it.
5940
- if (report.exitCode === 0 && report.trust === 'trusted' && report.installed) {
5941
- write(`dz hooks-sync: codex hooks installed and ARMED (trust: ${report.trust}) — ready`);
5942
- } else if (report.installed) {
5943
- writeErr(`dz hooks-sync: installed, NOT verified — ARMED = NO (trust: ${report.trust}, executable: ${report.executable})`);
5944
- writeErr('→ open an interactive Codex session in this directory and approve the two dz hooks, then re-run with --verify');
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`');
5945
6124
  } else {
5946
- writeErr('dz hooks-sync: ARMED = NO — the managed entries are not present in the registry');
6125
+ stderr.push(`${label}: ARMED = NO — the managed entries are not present in the registry`);
5947
6126
  }
5948
- return report.exitCode;
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 };
5949
6241
  }
5950
6242
 
5951
6243
  function cmdAgentsSync(
@@ -7939,16 +8231,599 @@ function cmdMutationGate(options: Map<string, string>, flags: Set<string>, cwd:
7939
8231
  * debt); an oversized or non-regular due-file counts as MALFORMED, never a silent skip (QE #8);
7940
8232
  * a debt whose embedded slug differs from its directory is MALFORMED — identity is the directory,
7941
8233
  * the JSON only confirms it (QE #4: an embedded foreign slug must not redirect settlement). */
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;
8265
+ try {
8266
+ if (detached) process.kill(-raw, signal);
8267
+ else child?.kill?.(signal);
8268
+ return true;
8269
+ } catch {
8270
+ return false; // already gone, or not ours — both mean nothing more to do
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
+
7942
8790
  function scanReqeDebts(root: string): { debts: Array<{ debt: ReqeDebt; duePath: string; dir: string }>; malformed: number } {
7943
8791
  const out: Array<{ debt: ReqeDebt; duePath: string; dir: string }> = [];
7944
8792
  let malformed = 0;
7945
- const featuresDir = join(root, 'features');
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; });
8810
+ return { debts: out, malformed };
8811
+ }
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;
7946
8821
  let slugs: string[] = [];
7947
8822
  try {
7948
- if (lstatSync(featuresDir).isSymbolicLink()) return { debts: [], malformed: 0 }; // r2 #4: features/ itself
8823
+ if (lstatSync(featuresDir).isSymbolicLink()) return; // r2 #4: the container itself
7949
8824
  slugs = readdirSync(featuresDir);
7950
8825
  } catch {
7951
- return { debts: [], malformed: 0 };
8826
+ return;
7952
8827
  }
7953
8828
  for (const slug of slugs.sort()) {
7954
8829
  const dir = join(featuresDir, slug);
@@ -7971,13 +8846,13 @@ function scanReqeDebts(root: string): { debts: Array<{ debt: ReqeDebt; duePath:
7971
8846
  }
7972
8847
  try {
7973
8848
  const debt = parseReqeDebt(readFileSync(duePath, 'utf-8'));
7974
- if (debt && debt.slug === slug) out.push({ debt, duePath, dir });
8849
+ if (debt && (!keyMatchesDir || debt.slug === slug)) out.push({ debt, duePath, dir });
7975
8850
  else malformed++;
7976
8851
  } catch {
7977
8852
  malformed++;
7978
8853
  }
7979
8854
  }
7980
- return { debts: out, malformed };
8855
+ addMalformed(malformed);
7981
8856
  }
7982
8857
 
7983
8858
  /**
@@ -8122,6 +8997,770 @@ function cmdReqe(options: Map<string, string>, flags: Set<string>, cwd: string,
8122
8997
  return 0;
8123
8998
  }
8124
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
+
8125
9764
  function cmdScore(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
8126
9765
  const json = flags.has('json');
8127
9766
  if (flags.has('help')) {
@@ -9873,6 +11512,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9873
11512
  case 'scout':
9874
11513
  return await cmdScout(options, flags, cwd, write);
9875
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);
9876
11517
  return cmdWorkflow(options, flags, cwd, write);
9877
11518
  case 'workflow-lint':
9878
11519
  return cmdWorkflowLint(options, flags, cwd, write);
@@ -9980,6 +11621,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
9980
11621
  return cmdScore(options, flags, cwd, write);
9981
11622
  case 'reqe':
9982
11623
  return cmdReqe(options, flags, cwd, write);
11624
+ case 'qe-bridge':
11625
+ return await cmdQeBridge(options, flags, cwd, write);
9983
11626
  case 'backlog':
9984
11627
  return await cmdBacklog(options, flags, cwd, write);
9985
11628
  case 'routing':