@dzhechkov/harness-cli 0.3.253 → 0.3.256

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,7 +7,7 @@
7
7
  import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
8
8
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
- import { execSync, spawn } from 'node:child_process';
10
+ import { execFileSync, execSync, spawn } from 'node:child_process';
11
11
  import { homedir, tmpdir } from 'node:os';
12
12
  import { createRequire } from 'node:module';
13
13
 
@@ -118,6 +118,21 @@ import {
118
118
  guardExitCode,
119
119
  DEFAULT_RULES,
120
120
  parsePnpmLockImporters,
121
+ // guard-promotion (feature guard-promotion, scout idea #1)
122
+ assembleCandidates,
123
+ renderPromotionReport,
124
+ renderPromotionAdr,
125
+ normalizePromotionState,
126
+ nextPromotionState,
127
+ globMatch,
128
+ promotionAdrRelPath,
129
+ DEFAULT_WINDOW_DAYS,
130
+ DEFAULT_PERIODS,
131
+ MAX_CONTENT_FETCHES,
132
+ BUILTIN_COVERAGE,
133
+ type ChangeSet,
134
+ type ExistingRuleView,
135
+ type PromotionReport,
121
136
  decideProvenance,
122
137
  isInsideTree,
123
138
  signManifest,
@@ -201,6 +216,24 @@ import {
201
216
  renderContentProbe,
202
217
  findNonRegistrableSkillDirs,
203
218
  assembleCompoundingReport,
219
+ // Cold-vs-warm EPOCH RUNNER (feature epoch-replay) — orchestrates + scores, never calls a model.
220
+ replayableInstances,
221
+ buildWorkOrder,
222
+ buildJudgePrompts,
223
+ unblindJudgments,
224
+ verifyWorkOrder,
225
+ isValidMargin,
226
+ DIGEST_HONEST_SCOPE,
227
+ scoreEpochReplay,
228
+ generateMockOutcomes,
229
+ renderEpochReplayResult,
230
+ renderWorkOrderSummary,
231
+ renderJudgePromptsSummary,
232
+ WORK_ORDER_KIND,
233
+ DEFAULT_MOCK_N,
234
+ DEFAULT_MOCK_SEED,
235
+ type WorkOrder,
236
+ type EpochOutcome,
204
237
  scoreRun,
205
238
  renderScorecard,
206
239
  renderCompoundingReport,
@@ -265,6 +298,10 @@ Usage:
265
298
  dz delivery-check --slug <slug> [--context-only] [--findings <f.json>] [--strict] [--author <model>] [--json] (portable Step-10 Delivery Gate: prints the 4-plane review brief + artifact probes; --findings classifies a fed-back review into a fail-closed ready|blocked hand-off and writes features/<slug>/10_delivery_review.md; --strict exits 1 on blocked)
266
299
  dz skills-verify [--dir <project>] [--expect a,b] [--static] [--strict] [--json] (does .claude/skills/ actually REGISTER? --static = instant layout scan for CI; default reads the authoritative system/init listing from a real session. exit 0 pass / 1 fail / 2 inconclusive — never a false pass)
267
300
  dz compounding [--project <dir>] [--json] (honest learning-loop payoff report: pool write-only ratio, guard repeat-violation trajectory, cold-vs-warm replay readiness, instrumentation health — a gate without enough data says INSUFFICIENT_DATA, never a fake verdict)
301
+ dz epoch-replay --mock [--n <N>] [--effect <-1..1>] [--tie-rate <0..1>] [--seed <N>] [--slice <name>] [--json] ($0 synthetic run — exercises the verdict math, NOT evidence)
302
+ dz epoch-replay --emit [--project <dir>] [--limit <N>] [--seed <N>] [--out <file>] (cold-vs-warm work order: instances + PRE-REGISTERED blind A/B assignment; the runner never calls a model)
303
+ dz epoch-replay --judge <filled-work-order.json> [--out <file>] (blind judge prompts from the filled plans)
304
+ 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)
268
305
  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)
269
306
  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)
270
307
  dz backlog list [--status <s>] [--goal <id>] [--project <dir>] [--json] (list captured ideas, filterable by status/goal)
@@ -4942,6 +4979,42 @@ function gatherGuardFacts(op: string, root: string, text: string | undefined, st
4942
4979
  facts['lockfile'] = { parsed: true, importers: rows };
4943
4980
  }
4944
4981
  } catch { facts['lockfile'] = { parsed: false }; /* no lockfile (not a pnpm workspace) — rule stays silent */ }
4982
+
4983
+ // change: the working-tree diff, for PROMOTED (template) rules. Without this fact a rule written
4984
+ // by `dz guard promote --apply` would be INERT — present in the config and enforcing nothing.
4985
+ // Contents are read only for the globs an active `format-match` rule actually asks about.
4986
+ try {
4987
+ const status = execSync('git status --porcelain', { cwd: root, encoding: 'utf-8' });
4988
+ const files = status
4989
+ .split('\n')
4990
+ .map((l) => l.slice(3).trim())
4991
+ .map((p) => (p.includes(' -> ') ? p.split(' -> ')[1]!.trim() : p)) // renames: the destination is the changed path
4992
+ .filter((p) => p !== '');
4993
+ const formatGlobs = (Array.isArray(loadGuardConfig(root).rules) ? (loadGuardConfig(root).rules as { template?: unknown; params?: { file?: unknown } }[]) : [])
4994
+ .filter((r) => r?.template === 'format-match' && typeof r?.params?.file === 'string')
4995
+ .map((r) => r.params!.file as string);
4996
+ const contents: Record<string, string> = {};
4997
+ if (formatGlobs.length > 0) {
4998
+ for (const f of files) {
4999
+ if (!formatGlobs.some((g) => globMatch(g, f))) continue;
5000
+ const abs = resolve(root, f);
5001
+ // Containment: a `git status` path is repo-relative, but `..` in one must never let the
5002
+ // LIVE reader step outside the repo the HISTORICAL reader is confined to.
5003
+ if (abs !== root && !abs.startsWith(root + sep)) continue;
5004
+ try {
5005
+ // lstat, NOT stat (Codex QE MED-3). `git show <sha>:<path>` yields the SYMLINK TARGET
5006
+ // TEXT, never the file it points at, so a live reader that follows links answers a
5007
+ // different question than the replay — and `/dev/zero` behind a symlink hangs the read.
5008
+ // Skipping non-regular files restores replay/live equivalence and closes the DoS.
5009
+ const st = lstatSync(abs);
5010
+ if (!st.isFile()) continue;
5011
+ if (st.size > MAX_CONTENT_BYTES) continue; // too large to be a spec file — undecidable, never guessed
5012
+ contents[f] = readFileSync(abs, 'utf8');
5013
+ } catch { /* deleted — leave it undecidable, never guess */ }
5014
+ }
5015
+ }
5016
+ facts['change'] = { files, ...(Object.keys(contents).length > 0 ? { contents } : {}) };
5017
+ } catch { /* not a git repo — every template rule stays silent (fail-open) */ }
4945
5018
  }
4946
5019
  if (op === 'consolidate') {
4947
5020
  try { facts['drift'] = sweepSkillDrift(root, { scope: 'packages', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name); } catch { /* skip */ }
@@ -4977,6 +5050,341 @@ function runGuardEvaluation(root: string, op: string, text: string | undefined,
4977
5050
  return result;
4978
5051
  }
4979
5052
 
5053
+ // ── `dz guard promote` (feature guard-promotion, scout idea #1) ─────────────────────────────────
5054
+
5055
+ const PROMOTIONS_DIR = join('features', 'guard-promotion', 'promotions');
5056
+ const PROMOTION_STATE_FILE = join('.dz', 'promotion-state.json');
5057
+ /**
5058
+ * Ceiling on a single file read, applied IDENTICALLY to the historical (`git show`) and live
5059
+ * (working-tree) readers. A `format-match` target is a spec/manifest file; anything larger is not
5060
+ * one, and an unbounded read of a symlinked `/dev/zero` is a hang, not a measurement.
5061
+ */
5062
+ const MAX_CONTENT_BYTES = 1024 * 1024;
5063
+
5064
+ const GUARD_PROMOTE_USAGE = [
5065
+ 'dz guard promote [--project <dir>] [--json] [--dry-run | --apply]',
5066
+ ' [--window-days <N>] [--periods <N>] [--limit <N>]',
5067
+ ].join('\n ');
5068
+
5069
+ /**
5070
+ * Read real commit history as {@link ChangeSet}s — the shadow-replay corpus. `--name-only` gives the
5071
+ * change shape every v1 template consumes. Merges are excluded (their file list is a union of the
5072
+ * branches, not a decision anyone made).
5073
+ *
5074
+ * A missing/failing `git` yields `[]`, which makes every candidate `insufficient-data` — the command
5075
+ * still exits 0 and says why. No history is not a promotion.
5076
+ */
5077
+ function readGitChanges(root: string, sinceIso: string): ChangeSet[] {
5078
+ let out = '';
5079
+ try {
5080
+ // execFileSync (argv form), NOT a shell string: `--name-only` paths come straight from the repo,
5081
+ // and a filename containing `$(…)` or a backtick would EXPAND inside a double-quoted shell
5082
+ // argument. `-z` is not used because the pretty header needs line framing; the argv form removes
5083
+ // the shell entirely instead.
5084
+ out = execFileSync('git', ['log', `--since=${sinceIso}`, '--no-merges', '--name-only', '--pretty=format:%x01%H%x09%cI'], {
5085
+ cwd: root,
5086
+ encoding: 'utf-8',
5087
+ maxBuffer: 64 * 1024 * 1024,
5088
+ });
5089
+ } catch {
5090
+ return [];
5091
+ }
5092
+ const changes: ChangeSet[] = [];
5093
+ let current: { id: string; ts: string; files: string[] } | null = null;
5094
+ for (const raw of out.split('\n')) {
5095
+ if (raw.startsWith('\x01')) {
5096
+ if (current) changes.push(current);
5097
+ const [id, ts] = raw.slice(1).split('\t');
5098
+ current = { id: (id ?? '').slice(0, 12), ts: ts ?? '', files: [] };
5099
+ continue;
5100
+ }
5101
+ const line = raw.trim();
5102
+ if (line === '' || current === null) continue;
5103
+ current.files.push(line);
5104
+ }
5105
+ if (current) changes.push(current);
5106
+ return changes;
5107
+ }
5108
+
5109
+ /**
5110
+ * Attach file text at each historical commit for the `format-match` candidates that need it.
5111
+ *
5112
+ * HARD CAP (`MAX_CONTENT_FETCHES`): over it we STOP fetching, which leaves those changes without
5113
+ * contents, which makes `templateFires` return `undecidable`, which makes the candidate
5114
+ * `insufficient-data`. What we deliberately do NOT do is fall back to the file's CURRENT content —
5115
+ * evaluating a historical commit against today's file is exactly the fabricated-win shape ADR-002
5116
+ * refused for `presence-check`.
5117
+ */
5118
+ function attachChangeContents(root: string, changes: readonly ChangeSet[], globs: readonly string[]): ChangeSet[] {
5119
+ if (globs.length === 0) return [...changes];
5120
+ let budget = MAX_CONTENT_FETCHES;
5121
+ return changes.map((c) => {
5122
+ const wanted = c.files.filter((f) => globs.some((g) => globMatch(g, f)));
5123
+ if (wanted.length === 0) return c;
5124
+ const contents: Record<string, string> = {};
5125
+ for (const f of wanted) {
5126
+ if (budget <= 0) return c; // over cap ⇒ leave this change undecidable, never guess
5127
+ budget -= 1;
5128
+ try {
5129
+ // argv form, NOT a shell string: a repo path is untrusted input and `$(…)`/backticks would
5130
+ // expand inside a quoted shell argument. No `--` terminator — `git show -- <rev>:<path>`
5131
+ // exits 0 with EMPTY output (the terminator turns the rev-with-path into a pathspec). The
5132
+ // option-smuggling risk it would have covered is absent anyway: the argument always begins
5133
+ // with a 12-hex sha.
5134
+ const text = execFileSync('git', ['show', `${c.id}:${f}`], { cwd: root, encoding: 'utf-8', maxBuffer: MAX_CONTENT_BYTES });
5135
+ // Same size ceiling as the live reader, so replay and live agree on what is too big to judge.
5136
+ if (text.length > MAX_CONTENT_BYTES) return c;
5137
+ // EMPTY OUTPUT IS NOT CONTENT. git reported this path as changed in this commit, so an
5138
+ // empty body is far more likely a failed lookup than a genuinely empty file — and treating
5139
+ // it as content is the worst possible failure: `''.includes(x)` is false, so the rule would
5140
+ // FIRE on every single file and fabricate a clean sweep of wins. Undecidable instead.
5141
+ if (text === '') return c;
5142
+ contents[f] = text;
5143
+ } catch {
5144
+ return c; // deleted/renamed at that commit — undecidable, not clean
5145
+ }
5146
+ }
5147
+ return { ...c, contents };
5148
+ });
5149
+ }
5150
+
5151
+ /** Every rule the engine would run: the built-ins plus any template rules already in `.dz/guard.json`. */
5152
+ function existingRuleViews(root: string): ExistingRuleView[] {
5153
+ const cfg = loadGuardConfig(root);
5154
+ const configRules = Array.isArray(cfg.rules) ? (cfg.rules as { id?: unknown; template?: unknown; params?: unknown; enabled?: unknown }[]) : [];
5155
+ const disabled = new Set(configRules.filter((r) => r?.enabled === false && typeof r.id === 'string').map((r) => r.id as string));
5156
+ // A built-in the operator has DISABLED does not cover anything — otherwise the promoter would
5157
+ // refuse a candidate as a duplicate of a rule that is not running, and the gap would stay open.
5158
+ const views: ExistingRuleView[] = DEFAULT_RULES.filter((r) => !disabled.has(r.id)).map((r) => ({ id: r.id }));
5159
+ for (const o of configRules) {
5160
+ if (typeof o?.id !== 'string' || o.enabled === false) continue;
5161
+ // A rule op-scoped AWAY from publish covers nothing a change-shaped promotion targets — letting
5162
+ // it suppress a candidate as a "duplicate" keeps the gap open (Codex re-QE MED, mirror of the
5163
+ // disabled-builtin rationale above).
5164
+ const ops = (o as { ops?: unknown }).ops;
5165
+ if (Array.isArray(ops) && !(ops as unknown[]).includes('publish')) continue;
5166
+ if (views.some((v) => v.id === o.id)) continue;
5167
+ views.push({ id: o.id, ...(typeof o.template === 'string' ? { template: o.template as never } : {}), ...(o.params && typeof o.params === 'object' ? { params: o.params as never } : {}) });
5168
+ }
5169
+ return views;
5170
+ }
5171
+
5172
+ /** Atomic JSON write — tmp + rename, so a crash mid-write never leaves a half-parsed state file. */
5173
+ function writeJsonAtomic(path: string, value: unknown): void {
5174
+ mkdirSync(dirname(path), { recursive: true });
5175
+ const tmp = `${path}.tmp.${process.pid}`;
5176
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf-8');
5177
+ renameSync(tmp, path);
5178
+ }
5179
+
5180
+ /** The rolled-up refusal record (ADR-004): one file, regenerated in place, one row per lesson. */
5181
+ function renderNotPromotableRollup(report: PromotionReport, nowTs: string): string {
5182
+ const refused = report.candidates.filter((c) => c.verdict === 'not-promotable');
5183
+ const out: string[] = [];
5184
+ out.push('# 000 — Not promotable (rolled-up refusal record)');
5185
+ out.push('');
5186
+ out.push(`**Decision:** REFUSED · **Date:** ${nowTs} · **Count:** ${refused.length} of ${report.totalLessons} lesson(s)`);
5187
+ out.push('');
5188
+ out.push('These lessons do not reduce to a v1 `dz guard promote` rule template. Rule code is NEVER');
5189
+ out.push('synthesised from lesson text (ADR-002), so a lesson that fits no template is refused aloud');
5190
+ out.push('rather than force-fitted. This file is regenerated in place on every run.');
5191
+ out.push('');
5192
+ out.push('| lesson | reason | first 90 chars |');
5193
+ out.push('|---|---|---|');
5194
+ for (const c of refused) {
5195
+ const t = c.lessonText.replace(/\|/g, '\\|').replace(/\n/g, ' ').slice(0, 90);
5196
+ out.push(`| \`${c.lessonId}\` | ${c.reason.replace(/\|/g, '\\|')} | ${t} |`);
5197
+ }
5198
+ return out.join('\n') + '\n';
5199
+ }
5200
+
5201
+ /**
5202
+ * `dz guard promote` — lesson → guard-rule promotion with a "win twice to promote" gate.
5203
+ *
5204
+ * Thin by design: gather (lessons, existing rules, real commit history, state) → the PURE
5205
+ * `assembleCandidates` → render → write. Default PROPOSES (documents + journal only); `--dry-run`
5206
+ * writes nothing at all; `--apply` is the only path that touches `.dz/guard.json`, always SOFT.
5207
+ */
5208
+ function cmdGuardPromote(options: Map<string, string>, flags: Set<string>, root: string, write: Write): number {
5209
+ const json = flags.has('json');
5210
+ const fail = (msg: string): number => {
5211
+ write(json ? JSON.stringify({ error: msg, exitCode: 1 }) : `dz guard promote: ${msg}\n usage: ${GUARD_PROMOTE_USAGE}`);
5212
+ return 1;
5213
+ };
5214
+ for (const f of flags) if (!['json', 'dry-run', 'apply', 'help'].includes(f)) return fail(`unknown option --${f}`);
5215
+ for (const k of options.keys()) {
5216
+ if (k === '_positional_0') continue; // the `promote` subcommand token itself
5217
+ if (k.startsWith('_positional_')) return fail(`unexpected argument "${options.get(k)}"`);
5218
+ if (!['project', 'window-days', 'periods', 'limit'].includes(k)) return fail(`unknown option --${k}`);
5219
+ }
5220
+ if (flags.has('help')) {
5221
+ write(`dz guard promote — promote a learned lesson to a deterministic guard rule\n usage: ${GUARD_PROMOTE_USAGE}`);
5222
+ write(' A candidate must SHADOW-WIN twice consecutively over real commit history before it is proposed.');
5223
+ write(' Default: writes proposal/refusal documents only. --dry-run: writes nothing. --apply: writes the SOFT rule into .dz/guard.json.');
5224
+ return 0;
5225
+ }
5226
+ const dryRun = flags.has('dry-run');
5227
+ const apply = flags.has('apply');
5228
+ // NOT a silent precedence: two contradictory intents is an error, not a coin flip.
5229
+ if (dryRun && apply) return fail('--dry-run and --apply are mutually exclusive');
5230
+
5231
+ const num = (key: string, dflt: number, lo: number, hi: number): number | null => {
5232
+ const raw = options.get(key);
5233
+ if (raw === undefined) return dflt;
5234
+ const n = Number(raw);
5235
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < lo || n > hi) return null;
5236
+ return n;
5237
+ };
5238
+ const windowDays = num('window-days', DEFAULT_WINDOW_DAYS, 1, 365);
5239
+ if (windowDays === null) return fail('--window-days expects an integer in [1, 365]');
5240
+ const periods = num('periods', DEFAULT_PERIODS, 2, 52);
5241
+ if (periods === null) return fail('--periods expects an integer in [2, 52]');
5242
+ const limit = num('limit', 15, 1, 1000);
5243
+ if (limit === null) return fail('--limit expects an integer in [1, 1000]');
5244
+
5245
+ const nowTs = new Date().toISOString();
5246
+ const sinceIso = new Date(Date.now() - windowDays * periods * 86_400_000).toISOString();
5247
+
5248
+ // lessons — the SAME readers `dz compounding` uses; no second store.
5249
+ const lessons = loadStoreRecords(root).map((r) => ({
5250
+ dzId: r.id,
5251
+ text: typeof r.text === 'string' ? r.text : '',
5252
+ quarantined: readQuarantineState(r).quarantined,
5253
+ uses: readReinforcementState(r).uses,
5254
+ }));
5255
+ const existingRules = existingRuleViews(root);
5256
+ const changes = readGitChanges(root, sinceIso);
5257
+
5258
+ // State is read on EVERY run, including --dry-run, because it carries the LOCAL-clock `firstSeen`
5259
+ // the elapsed gate reads (MED-7). --dry-run still writes nothing — which is exactly why a
5260
+ // dry-run-only workflow never starts that clock, and the wait reason says so.
5261
+ const state = normalizePromotionState(((): unknown => {
5262
+ try { return JSON.parse(readFileSync(join(root, PROMOTION_STATE_FILE), 'utf-8')); } catch { return null; }
5263
+ })());
5264
+ const firstSeen: Record<string, string> = {};
5265
+ for (const [id, e] of Object.entries(state.entries)) if (e.firstSeenTs !== '') firstSeen[id] = e.firstSeenTs;
5266
+
5267
+ // Pass 1 discovers which `format-match` candidates exist, so contents are fetched only for the
5268
+ // globs that actually need them (and only up to the cap).
5269
+ const pass1 = assembleCandidates({ lessons, existingRules, changes, nowTs, windowDays, periods, firstSeen });
5270
+ const formatGlobs = [...new Set(pass1.candidates.filter((c) => c.template === 'format-match' && typeof c.params?.file === 'string').map((c) => c.params!.file!))];
5271
+ const report = formatGlobs.length === 0
5272
+ ? pass1
5273
+ : assembleCandidates({ lessons, existingRules, changes: attachChangeContents(root, changes, formatGlobs), nowTs, windowDays, periods, firstSeen });
5274
+
5275
+ // ── write side ────────────────────────────────────────────────────────────────────────────────
5276
+ const written: string[] = [];
5277
+ const applied: string[] = [];
5278
+ const conflicts: string[] = [];
5279
+ if (!dryRun) {
5280
+ const adrSeqs: Record<string, number> = {};
5281
+ let seq = state.nextAdrSeq;
5282
+ let allocated = 0;
5283
+ for (const c of report.candidates) {
5284
+ if (c.verdict !== 'promote' && c.verdict !== 'duplicate') continue;
5285
+ const key = c.ruleId!;
5286
+ // ONE document per CANDIDATE, not per run — but the reused thing is the integer SEQUENCE, never
5287
+ // a path. State is attacker-shaped input (a JSON file anyone can corrupt), and a path taken
5288
+ // from it and handed to writeFileSync overwrites whatever it names — with no `--apply`, no
5289
+ // promotion, and no way to notice. The path is DERIVED from the validated id + that integer.
5290
+ const existingSeq = state.entries[key]?.adrSeq;
5291
+ const useSeq = existingSeq ?? seq;
5292
+ const rel = promotionAdrRelPath(key, useSeq);
5293
+ if (rel === null) continue; // an id or sequence that fails validation writes NOTHING
5294
+ if (existingSeq === undefined) { seq += 1; allocated += 1; }
5295
+ // Belt to the derivation's braces: resolve and assert containment before writing. A derivation
5296
+ // that is correct today is not a substitute for checking the thing you are about to write.
5297
+ const abs = resolve(root, rel);
5298
+ const dir = resolve(root, PROMOTIONS_DIR);
5299
+ if (abs !== dir && !abs.startsWith(dir + sep)) continue;
5300
+ try {
5301
+ mkdirSync(dirname(abs), { recursive: true });
5302
+ // Lexical containment is not PHYSICAL containment (Codex re-QE HIGH): a symlinked
5303
+ // promotions/ directory (or a symlink planted at the ADR leaf) redirects the write outside
5304
+ // the repo while every string check passes. realpath the directory that actually exists on
5305
+ // disk and require it to be the real promotions dir under the real root; refuse a leaf that
5306
+ // is a symlink.
5307
+ const realDir = realpathSync(dirname(abs));
5308
+ const expectedReal = join(realpathSync(root), PROMOTIONS_DIR.split('/').join(sep));
5309
+ if (realDir !== expectedReal) continue;
5310
+ if (existsSync(abs) && lstatSync(abs).isSymbolicLink()) continue;
5311
+ writeFileSync(abs, renderPromotionAdr(c, useSeq, nowTs), 'utf-8');
5312
+ adrSeqs[key] = useSeq;
5313
+ written.push(rel);
5314
+ } catch { /* a document we cannot write must not lose the verdict */ }
5315
+ }
5316
+ if (report.candidates.some((c) => c.verdict === 'not-promotable')) {
5317
+ const rel = join(PROMOTIONS_DIR, '000-not-promotable.md');
5318
+ try {
5319
+ mkdirSync(join(root, PROMOTIONS_DIR), { recursive: true });
5320
+ writeFileSync(join(root, rel), renderNotPromotableRollup(report, nowTs), 'utf-8');
5321
+ written.push(rel);
5322
+ } catch { /* best-effort */ }
5323
+ }
5324
+
5325
+ if (apply) {
5326
+ const cfg = loadGuardConfig(root);
5327
+ const rules = Array.isArray(cfg.rules) ? [...(cfg.rules as unknown[])] : [];
5328
+ for (const c of report.candidates) {
5329
+ if (c.verdict !== 'promote' || c.proposedRule === null) continue;
5330
+ const want = c.proposedRule;
5331
+ const clash = rules.find((r) => (r as { id?: unknown })?.id === want.id) as { template?: unknown; params?: unknown } | undefined;
5332
+ if (clash !== undefined) {
5333
+ // ID EQUALITY IS NOT IDEMPOTENCE (Codex QE MED-5). A rule that merely SHARES the id — a
5334
+ // hand-written bare entry, or a same-id rule with different params — is not the rule we
5335
+ // are promoting. Skipping it silently reports "applied" while installing nothing (the bare
5336
+ // entry does not even enforce, since resolveRules drops an unknown id with no template).
5337
+ // Same id + same BODY is genuine idempotence; same id + different body is a conflict, and a
5338
+ // conflict is refused out loud rather than resolved by guessing which side to keep.
5339
+ const sameBody = clash.template === want.template && JSON.stringify(clash.params ?? null) === JSON.stringify(want.params);
5340
+ // Same body but DISABLED (or op-scoped away from publish) is NOT idempotence: the rule
5341
+ // exists on paper and enforces nothing — "already installed" would be a false success
5342
+ // (Codex re-QE MED). Refuse loudly so the operator re-enables or removes it.
5343
+ const clashEnabled = (clash as { enabled?: unknown }).enabled !== false;
5344
+ const clashOps = (clash as { ops?: unknown }).ops;
5345
+ const clashCoversPublish = !Array.isArray(clashOps) || (clashOps as unknown[]).includes('publish');
5346
+ if (sameBody && clashEnabled && clashCoversPublish) continue; // already installed AND active — genuine idempotence
5347
+ if (sameBody) {
5348
+ conflicts.push(`${want.id}: an identical rule exists in .dz/guard.json but is ${clashEnabled ? 'op-scoped away from publish' : 'DISABLED'} — it enforces nothing; re-enable it (or remove it and re-run --apply) instead of trusting a rule that is not running`);
5349
+ continue;
5350
+ }
5351
+ conflicts.push(`${want.id}: an existing .dz/guard.json rule shares this id but has a different body (existing template=${JSON.stringify(clash.template ?? null)} params=${JSON.stringify(clash.params ?? null)}; promoted template=${JSON.stringify(want.template)} params=${JSON.stringify(want.params)}) — refusing to overwrite or to claim success; rename or remove the existing rule`);
5352
+ continue;
5353
+ }
5354
+ rules.push(want);
5355
+ applied.push(want.id);
5356
+ }
5357
+ if (applied.length > 0) writeJsonAtomic(join(root, '.dz', 'guard.json'), { ...cfg, rules });
5358
+ }
5359
+
5360
+ const next = nextPromotionState(state, report, nowTs, adrSeqs, allocated);
5361
+ const withApplied = applied.length === 0 ? next : {
5362
+ ...next,
5363
+ entries: Object.fromEntries(Object.entries(next.entries).map(([k, v]) => (applied.includes(k) ? [k, { ...v, appliedTs: nowTs }] : [k, v]))),
5364
+ };
5365
+ try { writeJsonAtomic(join(root, PROMOTION_STATE_FILE), withApplied); } catch { /* best-effort */ }
5366
+ }
5367
+
5368
+ // A refused conflict means the requested apply did NOT fully happen — exit non-zero rather than
5369
+ // let a zero exit report success for work that was deliberately not done.
5370
+ const exitCode = conflicts.length > 0 ? 1 : 0;
5371
+
5372
+ if (json) {
5373
+ write(JSON.stringify({ ...report, mode: dryRun ? 'dry-run' : apply ? 'apply' : 'propose', written, applied, conflicts, exitCode }, null, 2));
5374
+ return exitCode;
5375
+ }
5376
+ write(renderPromotionReport(report, limit));
5377
+ write('');
5378
+ if (dryRun) write(' MODE: --dry-run — nothing was written (not even .dz/promotion-state.json)');
5379
+ else {
5380
+ write(` WROTE: ${written.length === 0 ? '(no decisions to record)' : written.join(', ')}`);
5381
+ if (apply) write(` APPLIED to .dz/guard.json: ${applied.length === 0 ? '(none)' : applied.join(', ')} — SOFT severity, always`);
5382
+ else write(' Nothing was written to .dz/guard.json — re-run with --apply to install the promoted rule(s).');
5383
+ }
5384
+ for (const c of conflicts) write(` ✗ CONFLICT — ${c}`);
5385
+ return exitCode;
5386
+ }
5387
+
4980
5388
  /**
4981
5389
  * `dz guard` — the declarative constraint layer that refuses a self-mutating op when a HARD invariant is
4982
5390
  * violated. Simple outside: `dz guard check --op publish` works with zero config (built-in defaults).
@@ -5018,8 +5426,13 @@ function cmdGuard(options: Map<string, string>, flags: Set<string>, cwd: string,
5018
5426
  return 0;
5019
5427
  }
5020
5428
 
5429
+ // `promote` — lesson → guard-rule promotion. It lives HERE, not as a top-level `dz promote`,
5430
+ // because its object IS a guard rule: its evidence is .dz/guard-audit.jsonl + real commit history
5431
+ // and its write target is .dz/guard.json (ADR-001).
5432
+ if (sub === 'promote') return cmdGuardPromote(options, flags, options.get('project') !== undefined ? resolve(cwd, options.get('project')!) : root, write);
5433
+
5021
5434
  if (sub !== 'check') {
5022
- write(`dz guard: unknown subcommand '${sub}' — use: check --op <op> | --init | log`);
5435
+ write(`dz guard: unknown subcommand '${sub}' — use: check --op <op> | promote | --init | log`);
5023
5436
  return 1;
5024
5437
  }
5025
5438
 
@@ -5773,6 +6186,46 @@ function cmdScore(options: Map<string, string>, flags: Set<string>, cwd: string,
5773
6186
  return 0;
5774
6187
  }
5775
6188
 
6189
+ /**
6190
+ * Read the apply-leg usage log into the shape `compounding.ts` / `epoch-replay.ts` expect.
6191
+ *
6192
+ * ONE reader, because there were two and they disagreed: the `dz compounding` fact-gatherer used
6193
+ * to drop `eventId` and `queryTruncated`, so the readiness gate counted 48 "replayable pairs" over
6194
+ * a log whose honest count is 25 (MEASURED on this repo, 2026-07-29). Both defences documented in
6195
+ * `assembleCompoundingReport` — "one prompt = one pair" (Codex #1) and "a truncated query is a
6196
+ * prefix, not the prompt" (Codex #3) — were correct in the pure function and DEAD at its only
6197
+ * caller, because the caller never passed the fields they read.
6198
+ */
6199
+ function readRecallUsageEvents(
6200
+ root: string,
6201
+ ): { dzId: string; ts: string; query?: string; runId?: string; eventId?: string; queryTruncated?: boolean }[] {
6202
+ const usage: { dzId: string; ts: string; query?: string; runId?: string; eventId?: string; queryTruncated?: boolean }[] = [];
6203
+ try {
6204
+ const text = readFileSync(join(root, '.dz', 'recall-usage.jsonl'), 'utf-8');
6205
+ for (const line of text.split('\n')) {
6206
+ if (line.trim() === '') continue;
6207
+ try {
6208
+ const o = JSON.parse(line) as Record<string, unknown>;
6209
+ if (typeof o.dzId === 'string' && typeof o.ts === 'string' && o.kind !== 'aggregate') {
6210
+ usage.push({
6211
+ dzId: o.dzId,
6212
+ ts: o.ts,
6213
+ ...(typeof o.query === 'string' ? { query: o.query } : {}),
6214
+ ...(typeof o.runId === 'string' ? { runId: o.runId } : {}),
6215
+ ...(typeof o.eventId === 'string' ? { eventId: o.eventId } : {}),
6216
+ ...(o.queryTruncated === true ? { queryTruncated: true } : {}),
6217
+ });
6218
+ }
6219
+ } catch {
6220
+ /* one bad line must not kill the read */
6221
+ }
6222
+ }
6223
+ } catch {
6224
+ /* no log yet — callers report the absence */
6225
+ }
6226
+ return usage;
6227
+ }
6228
+
5776
6229
  /**
5777
6230
  * `dz compounding` — does the learning loop actually PAY? (feature compounding, scout C2.)
5778
6231
  * Gathers the facts (store rows, apply-leg usage log, guard audit) and hands them to the PURE
@@ -5812,28 +6265,7 @@ function cmdCompounding(options: Map<string, string>, flags: Set<string>, cwd: s
5812
6265
  }));
5813
6266
 
5814
6267
  // apply-leg usage events (read records only; aggregate rows carry no query by construction)
5815
- const usage: { dzId: string; ts: string; query?: string; runId?: string }[] = [];
5816
- try {
5817
- const text = readFileSync(join(root, '.dz', 'recall-usage.jsonl'), 'utf-8');
5818
- for (const line of text.split('\n')) {
5819
- if (line.trim() === '') continue;
5820
- try {
5821
- const o = JSON.parse(line) as Record<string, unknown>;
5822
- if (typeof o.dzId === 'string' && typeof o.ts === 'string' && o.kind !== 'aggregate') {
5823
- usage.push({
5824
- dzId: o.dzId,
5825
- ts: o.ts,
5826
- ...(typeof o.query === 'string' ? { query: o.query } : {}),
5827
- ...(typeof o.runId === 'string' ? { runId: o.runId } : {}),
5828
- });
5829
- }
5830
- } catch {
5831
- /* one bad line must not kill the report */
5832
- }
5833
- }
5834
- } catch {
5835
- /* no log yet — the report says so */
5836
- }
6268
+ const usage = readRecallUsageEvents(root);
5837
6269
 
5838
6270
  // guard audit events
5839
6271
  const guard: { ts: string; verdict: string; rules: string[] }[] = [];
@@ -5864,6 +6296,295 @@ function cmdCompounding(options: Map<string, string>, flags: Set<string>, cwd: s
5864
6296
  return 0;
5865
6297
  }
5866
6298
 
6299
+ // ── `dz epoch-replay` (feature epoch-replay) ────────────────────────────────────────────────────
6300
+
6301
+ const EPOCH_REPLAY_DIR = join('.dz', 'epoch-replay');
6302
+
6303
+ const EPOCH_REPLAY_USAGE = [
6304
+ 'dz epoch-replay --mock [--n <N>] [--effect <-1..1>] [--tie-rate <0..1>] [--seed <N>] [--slice <name>] [--margin <0..1>] [--json]',
6305
+ 'dz epoch-replay --emit [--project <dir>] [--limit <N>] [--seed <N>] [--margin <0..0.5>] [--out <file>] [--json]',
6306
+ 'dz epoch-replay --judge <filled-work-order.json> [--out <file>] [--json]',
6307
+ 'dz epoch-replay --score <judgments.json> --work-order <file> [--slice <name>] [--json] (margin comes from the work order)',
6308
+ ].join('\n ');
6309
+
6310
+ /** Read a JSON file into an object, or return a parse/IO error string. */
6311
+ function readJsonFile(path: string): { value: unknown } | { error: string } {
6312
+ try {
6313
+ return { value: JSON.parse(readFileSync(path, 'utf-8')) as unknown };
6314
+ } catch (e) {
6315
+ return { error: `cannot read ${path}: ${e instanceof Error ? e.message : String(e)}` };
6316
+ }
6317
+ }
6318
+
6319
+ /**
6320
+ * Integrity-check a parsed work order. Checking `kind` + `Array.isArray(items)` was VACUOUS: a
6321
+ * hand-written file with those two fields and a fabricated `warmIsA` bought whatever verdict its
6322
+ * author wanted (Codex QE HIGH-2). `verifyWorkOrder` recomputes the digest AND re-derives every
6323
+ * assignment from the stated seed.
6324
+ */
6325
+ function asVerifiedWorkOrder(value: unknown): { order: WorkOrder } | { problems: readonly string[] } {
6326
+ const v = verifyWorkOrder(value);
6327
+ if (!v.ok) return { problems: v.problems };
6328
+ return { order: value as WorkOrder };
6329
+ }
6330
+
6331
+ function writeJsonOut(path: string, value: unknown): void {
6332
+ mkdirSync(dirname(path), { recursive: true });
6333
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, 'utf-8');
6334
+ }
6335
+
6336
+ /** Numeric option parsing that never silently accepts garbage. */
6337
+ function numOpt(options: Map<string, string>, key: string): { value: number } | { error: string } | null {
6338
+ const raw = options.get(key);
6339
+ if (raw === undefined) return null;
6340
+ const n = Number(raw);
6341
+ if (!Number.isFinite(n)) return { error: `--${key} expects a finite number, got ${JSON.stringify(raw)}` };
6342
+ return { value: n };
6343
+ }
6344
+
6345
+ /**
6346
+ * `dz epoch-replay` — the executable cold-vs-warm epoch runner (feature epoch-replay, scout #4).
6347
+ *
6348
+ * `dz compounding` says whether a replay CAN be run; this says what it FOUND. The runner never
6349
+ * calls a model: real mode emits a work order, renders blind judge prompts, and scores filled
6350
+ * judgments; `--mock` exercises the same verdict math on seeded synthetic outcomes at $0.
6351
+ */
6352
+ function cmdEpochReplay(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
6353
+ const json = flags.has('json');
6354
+ const fail = (msg: string): number => {
6355
+ write(json ? JSON.stringify({ error: msg, exitCode: 1 }) : `dz epoch-replay: ${msg}\n usage:\n ${EPOCH_REPLAY_USAGE}`);
6356
+ return 1;
6357
+ };
6358
+ if (flags.has('help')) {
6359
+ write(`dz epoch-replay — cold (epoch 0) vs warm (epoch 1), Wilson-CI three-valued verdict\n ${EPOCH_REPLAY_USAGE}`);
6360
+ write('');
6361
+ write(' ONE binomial over DECISIVE pairs (ties carry no direction and are excluded from the test).');
6362
+ write(' SUPPORTED only when the paired lift interval lies ENTIRELY above zero.');
6363
+ write(' FALSIFIED only on HARM (entirely below zero), or on a passed NON-SUPERIORITY test (the');
6364
+ write(' lift upper bound below the PRE-REGISTERED margin, default 0.05). Otherwise INCONCLUSIVE —');
6365
+ write(' a first-class honest outcome; a tie is UNDER-POWERED, never "refuted".');
6366
+ write(' The margin is pre-registered at --emit and stored in the work order; --score reads it there.');
6367
+ write(' This runner ORCHESTRATES and SCORES; it never calls a model. The judge-facing file holds');
6368
+ write(' {id, prompt} and nothing else; --score refuses any work order whose digest or seed-derived');
6369
+ write(' assignment does not check out, and refuses duplicate judgement ids.');
6370
+ return 0;
6371
+ }
6372
+
6373
+ const allowedFlags = new Set(['mock', 'emit', 'json', 'help']);
6374
+ for (const flag of flags) {
6375
+ if (!allowedFlags.has(flag)) return fail(`unknown option --${flag}`);
6376
+ }
6377
+ const allowedOptions = new Set(['judge', 'score', 'work-order', 'project', 'out', 'n', 'effect', 'tie-rate', 'seed', 'slice', 'limit', 'margin']);
6378
+ for (const key of options.keys()) {
6379
+ if (key.startsWith('_positional_')) return fail(`unexpected argument "${options.get(key)}"`);
6380
+ if (!allowedOptions.has(key)) return fail(`unknown option --${key}`);
6381
+ }
6382
+
6383
+ // Exactly ONE mode. A command whose default mode is a report can silently swallow a typo'd mode
6384
+ // flag and print something that reads like a result — so there is NO default mode here.
6385
+ const modes = [
6386
+ flags.has('mock') ? 'mock' : null,
6387
+ flags.has('emit') ? 'emit' : null,
6388
+ options.has('judge') ? 'judge' : null,
6389
+ options.has('score') ? 'score' : null,
6390
+ ].filter((m): m is string => m !== null);
6391
+ if (modes.length === 0) return fail('pick exactly one mode: --mock | --emit | --judge <file> | --score <file>');
6392
+ if (modes.length > 1) return fail(`modes are exclusive, got: ${modes.join(', ')}`);
6393
+ const mode = modes[0]!;
6394
+
6395
+ const num = (key: string): number | undefined | { error: string } => {
6396
+ const r = numOpt(options, key);
6397
+ if (r === null) return undefined;
6398
+ if ('error' in r) return r;
6399
+ return r.value;
6400
+ };
6401
+
6402
+ // ── --mock: seeded synthetic outcomes, $0, exercises the real verdict math ──
6403
+ if (mode === 'mock') {
6404
+ for (const key of ['judge', 'score', 'work-order', 'project', 'out', 'limit']) {
6405
+ if (options.has(key)) return fail(`--${key} is not valid with --mock`);
6406
+ }
6407
+ const parsed: Record<string, number | undefined> = {};
6408
+ for (const key of ['n', 'effect', 'tie-rate', 'seed'] as const) {
6409
+ const v = num(key);
6410
+ if (typeof v === 'object' && v !== null) return fail(v.error);
6411
+ parsed[key] = v;
6412
+ }
6413
+ const outcomes = generateMockOutcomes({
6414
+ n: parsed.n ?? DEFAULT_MOCK_N,
6415
+ effect: parsed.effect ?? 0,
6416
+ tieRate: parsed['tie-rate'] ?? 0,
6417
+ seed: parsed.seed ?? DEFAULT_MOCK_SEED,
6418
+ });
6419
+ const marginOpt = numOpt(options, 'margin');
6420
+ if (marginOpt !== null && 'error' in marginOpt) return fail(marginOpt.error);
6421
+ const result = scoreEpochReplay(outcomes, {
6422
+ slice: options.get('slice') ?? 'all',
6423
+ ...(marginOpt !== null ? { margin: marginOpt.value } : {}),
6424
+ });
6425
+ if (result.refusal !== null) return fail(result.refusal);
6426
+ if (json) {
6427
+ write(JSON.stringify({ mode: 'mock', synthetic: true, ...result, exitCode: 0 }, null, 2));
6428
+ } else {
6429
+ write(renderEpochReplayResult(result));
6430
+ write('');
6431
+ write(
6432
+ ` SYNTHETIC (--mock): outcomes generated with seed ${parsed.seed ?? DEFAULT_MOCK_SEED} at a TRUE effect of ${parsed.effect ?? 0}. ` +
6433
+ 'This exercises the protocol, it is NOT evidence about the learning loop.',
6434
+ );
6435
+ }
6436
+ return 0;
6437
+ }
6438
+
6439
+ // ── --emit: the generation work order (real mode, stage 1) ──
6440
+ if (mode === 'emit') {
6441
+ for (const key of ['judge', 'score', 'work-order', 'n', 'effect', 'tie-rate', 'slice']) {
6442
+ if (options.has(key)) return fail(`--${key} is not valid with --emit`);
6443
+ }
6444
+ const root = resolve(cwd, options.get('project') ?? '.');
6445
+ const seed = num('seed');
6446
+ if (typeof seed === 'object' && seed !== null) return fail(seed.error);
6447
+ const limit = num('limit');
6448
+ if (typeof limit === 'object' && limit !== null) return fail(limit.error);
6449
+ // HIGH-B: the non-superiority margin is PRE-REGISTERED here, digest-covered, and read back by
6450
+ // --score. Out of range is refused, never clamped — `--margin 99` must not buy FALSIFIED.
6451
+ const emitMargin = num('margin');
6452
+ if (typeof emitMargin === 'object' && emitMargin !== null) return fail(emitMargin.error);
6453
+ if (typeof emitMargin === 'number' && !isValidMargin(emitMargin)) {
6454
+ return fail(`--margin ${emitMargin} must be in (0, 0.5] — refused, not clamped: an oversized margin buys FALSIFIED`);
6455
+ }
6456
+
6457
+ const lessonText = new Map<string, string>();
6458
+ for (const r of loadStoreRecords(root)) {
6459
+ if (typeof r.text === 'string' && r.text.trim() !== '') lessonText.set(r.id, r.text);
6460
+ }
6461
+ // The SAME reader `dz compounding` uses — readiness and the runner must see one corpus.
6462
+ const instances = replayableInstances(readRecallUsageEvents(root), lessonText);
6463
+ const order = buildWorkOrder(instances, {
6464
+ ...(typeof seed === 'number' ? { seed } : {}),
6465
+ ...(typeof limit === 'number' ? { limit } : {}),
6466
+ ...(typeof emitMargin === 'number' ? { margin: emitMargin } : {}),
6467
+ });
6468
+ const outPath = resolve(cwd, options.get('out') ?? join(root, EPOCH_REPLAY_DIR, 'work-order.json'));
6469
+ try {
6470
+ writeJsonOut(outPath, order);
6471
+ } catch (e) {
6472
+ return fail(`cannot write ${outPath}: ${e instanceof Error ? e.message : String(e)}`);
6473
+ }
6474
+ if (json) {
6475
+ write(JSON.stringify({ mode: 'emit', out: outPath, instances: order.items.length, seed: order.seed, margin: order.margin, digest: order.digest, corpusFingerprint: order.corpusFingerprint, emittedAt: order.emittedAt, exitCode: 0 }, null, 2));
6476
+ }
6477
+ else write(renderWorkOrderSummary(order, outPath));
6478
+ return 0;
6479
+ }
6480
+
6481
+ // ── --judge: blind judge prompts from a FILLED work order (real mode, stage 2) ──
6482
+ if (mode === 'judge') {
6483
+ for (const key of ['score', 'work-order', 'n', 'effect', 'tie-rate', 'slice', 'limit', 'seed', 'margin']) {
6484
+ if (options.has(key)) return fail(`--${key} is not valid with --judge`);
6485
+ }
6486
+ const inPath = resolve(cwd, options.get('judge')!);
6487
+ const read = readJsonFile(inPath);
6488
+ if ('error' in read) return fail(read.error);
6489
+ const verified = asVerifiedWorkOrder(read.value);
6490
+ if ('problems' in verified) {
6491
+ return fail(`${inPath} is not a verifiable ${WORK_ORDER_KIND}: ${verified.problems.join('; ')} (emit one with \`dz epoch-replay --emit\`)`);
6492
+ }
6493
+ const result = buildJudgePrompts(verified.order);
6494
+ const outPath = resolve(cwd, options.get('out') ?? join(dirname(inPath), 'judge-prompts.json'));
6495
+ try {
6496
+ // The JUDGE-FACING artifact. Its whole content is {id, prompt} per item — no `warmIsA`, no
6497
+ // arm names, no path back to the work order, and NOT the `skipped` list (whose reasons name
6498
+ // arms). Anything else here hands the judge the answer key (Codex QE CRITICAL-1).
6499
+ writeJsonOut(outPath, {
6500
+ kind: 'dz-epoch-replay-judge-prompts',
6501
+ version: 1,
6502
+ prompts: result.prompts.map((p) => ({ id: p.id, prompt: p.prompt })),
6503
+ });
6504
+ } catch (e) {
6505
+ return fail(`cannot write ${outPath}: ${e instanceof Error ? e.message : String(e)}`);
6506
+ }
6507
+ // `skipped` is OPERATOR-facing only — stdout / --json, never the file.
6508
+ if (json) write(JSON.stringify({ mode: 'judge', out: outPath, prompts: result.prompts.length, skipped: result.skipped, exitCode: 0 }, null, 2));
6509
+ else write(renderJudgePromptsSummary(result, outPath));
6510
+ return 0;
6511
+ }
6512
+
6513
+ // ── --score: un-blind + verdict (real mode, stage 3) ──
6514
+ for (const key of ['n', 'effect', 'tie-rate', 'limit', 'seed', 'out', 'project']) {
6515
+ if (options.has(key)) return fail(`--${key} is not valid with --score`);
6516
+ }
6517
+ // HIGH-B: a margin chosen once the counts are visible is not a pre-registration — and `--margin 99`
6518
+ // at scoring time would simply buy FALSIFIED. Real mode reads it from the work order, full stop.
6519
+ if (options.has('margin')) {
6520
+ return fail('--margin is not valid with --score: the non-superiority margin is PRE-REGISTERED at --emit and stored in the work order (re-emit to change it)');
6521
+ }
6522
+ const orderPath = options.get('work-order');
6523
+ if (orderPath === undefined) {
6524
+ return fail('--score requires --work-order <file>: un-blinding must use the PRE-REGISTERED assignment, not a label in the judgments file');
6525
+ }
6526
+ const orderRead = readJsonFile(resolve(cwd, orderPath));
6527
+ if ('error' in orderRead) return fail(orderRead.error);
6528
+ const verifiedOrder = asVerifiedWorkOrder(orderRead.value);
6529
+ if ('problems' in verifiedOrder) {
6530
+ return fail(
6531
+ `${resolve(cwd, orderPath)} is not a verifiable ${WORK_ORDER_KIND} — refusing to un-blind against it: ${verifiedOrder.problems.join('; ')}`,
6532
+ );
6533
+ }
6534
+ const order = verifiedOrder.order;
6535
+ const judgePath = resolve(cwd, options.get('score')!);
6536
+ const judgeRead = readJsonFile(judgePath);
6537
+ if ('error' in judgeRead) return fail(judgeRead.error);
6538
+ const rawRows = Array.isArray(judgeRead.value)
6539
+ ? judgeRead.value
6540
+ : typeof judgeRead.value === 'object' && judgeRead.value !== null && Array.isArray((judgeRead.value as { judgments?: unknown }).judgments)
6541
+ ? (judgeRead.value as { judgments: unknown[] }).judgments
6542
+ : null;
6543
+ if (rawRows === null) return fail(`${judgePath} must be an array of {id, winner} rows (or {"judgments": [...]})`);
6544
+ const unblind = unblindJudgments(
6545
+ order,
6546
+ rawRows.map((r) => {
6547
+ const o = (typeof r === 'object' && r !== null ? r : {}) as Record<string, unknown>;
6548
+ return { id: typeof o.id === 'string' ? o.id : '', winner: typeof o.winner === 'string' ? o.winner : '' };
6549
+ }),
6550
+ );
6551
+ // A duplicated judgement id is corrupt input, not a skippable row — refuse loudly.
6552
+ if (!unblind.ok) return fail(unblind.error ?? 'judgments refused');
6553
+ const { outcomes, skipped } = unblind;
6554
+
6555
+ const result = scoreEpochReplay(outcomes as EpochOutcome[], {
6556
+ slice: options.get('slice') ?? 'all',
6557
+ margin: order.margin, // PRE-REGISTERED in the work order, verified by the digest
6558
+ });
6559
+ if (result.refusal !== null) return fail(result.refusal);
6560
+ if (json) {
6561
+ write(JSON.stringify({
6562
+ mode: 'score',
6563
+ workOrder: resolve(cwd, orderPath),
6564
+ judgments: judgePath,
6565
+ scored: outcomes.length,
6566
+ skipped,
6567
+ provenance: { seed: order.seed, margin: order.margin, emittedAt: order.emittedAt, digest: order.digest, corpusFingerprint: order.corpusFingerprint, digestScope: DIGEST_HONEST_SCOPE },
6568
+ ...result,
6569
+ exitCode: 0,
6570
+ }, null, 2));
6571
+ } else {
6572
+ write(renderEpochReplayResult(result));
6573
+ if (skipped.length > 0) {
6574
+ write('');
6575
+ write(` ${skipped.length} judgment(s) SKIPPED (never guessed):`);
6576
+ for (const s of skipped) write(` · ${s.id}: ${s.reason}`);
6577
+ }
6578
+ // Provenance, so a reviewer can ask for the original emitted file and compare.
6579
+ write('');
6580
+ write(` WORK ORDER: seed ${order.seed} · margin ${order.margin} (pre-registered) · emitted ${order.emittedAt}`);
6581
+ write(` digest ${order.digest}`);
6582
+ write(` corpus ${order.corpusFingerprint}`);
6583
+ write(` ${DIGEST_HONEST_SCOPE}`);
6584
+ }
6585
+ return 0;
6586
+ }
6587
+
5867
6588
  /**
5868
6589
  * Env vars an INHERITED Claude session leaks into a child. Left in place, the probe can silently
5869
6590
  * read the parent's project instead of the target — the exact confound that made a hand-rolled
@@ -6974,6 +7695,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
6974
7695
  return cmdSkillsVerify(options, flags, cwd, write);
6975
7696
  case 'compounding':
6976
7697
  return cmdCompounding(options, flags, cwd, write);
7698
+ case 'epoch-replay':
7699
+ return cmdEpochReplay(options, flags, cwd, write);
6977
7700
  case 'score':
6978
7701
  return cmdScore(options, flags, cwd, write);
6979
7702
  case 'backlog':