@dzhechkov/harness-cli 0.3.254 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dzhechkov/harness-cli",
3
- "version": "0.3.254",
3
+ "version": "0.3.256",
4
4
  "description": "The dz CLI — install AI skills for Claude Code, Codex, OpenCode, Hermes, OpenClaude, GitHub Copilot. 35 commands, 13 presets, 6 platform targets.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,7 +41,7 @@
41
41
  "sbom.json"
42
42
  ],
43
43
  "dependencies": {
44
- "@dzhechkov/harness-core": "^0.3.144",
44
+ "@dzhechkov/harness-core": "^0.3.145",
45
45
  "@dzhechkov/harness-presets": "^0.5.0",
46
46
  "@dzhechkov/scout": "^0.8.0",
47
47
  "@dzhechkov/skills-devops": "^0.3.0",
package/sbom.json CHANGED
@@ -25,7 +25,7 @@
25
25
  "hashes": [
26
26
  {
27
27
  "alg": "SHA-256",
28
- "content": "fc57c105e5031d2d6751ef08b64769dc463cd79c5cf7637b48bc8cb7190e5b3a"
28
+ "content": "5f73e2c6d9c0ea38d5324f058cbd921bdb28dab60aa97ded97979ed994426731"
29
29
  }
30
30
  ]
31
31
  },
@@ -105,7 +105,7 @@
105
105
  "hashes": [
106
106
  {
107
107
  "alg": "SHA-256",
108
- "content": "4268f56e38f72625c2c490add4b17ee12d7ff7db991a2090f426afbb026b98a9"
108
+ "content": "18d5f55ed3c56718e470fef8bd677c55de08f4505e188b1dd29a0f0bbec09d4b"
109
109
  }
110
110
  ]
111
111
  },
@@ -115,7 +115,7 @@
115
115
  "hashes": [
116
116
  {
117
117
  "alg": "SHA-256",
118
- "content": "fe24568930cc226e0bad8b4ccba559e2f837bb4cb068c2cc37750b5a10c27a70"
118
+ "content": "c47d11fd3ed7e6049b1080cd9292ed3498e113d8bc74a9af65a027d70fa96435"
119
119
  }
120
120
  ]
121
121
  },
@@ -125,7 +125,7 @@
125
125
  "hashes": [
126
126
  {
127
127
  "alg": "SHA-256",
128
- "content": "4a0b554fab78cd50fc46cff653411b2003b7dd9a4df1b16af6e9f5a0e24379ff"
128
+ "content": "684ea0c6fa4edbbbea1ffcd943167cd374166eb196100433d4e8d02d70560794"
129
129
  }
130
130
  ]
131
131
  },
@@ -185,7 +185,7 @@
185
185
  "hashes": [
186
186
  {
187
187
  "alg": "SHA-256",
188
- "content": "c6469d0f7539ce6c0a8176d0b795952a667df2b975c9f93c66e7cd6eba843383"
188
+ "content": "154755702a4652597bf8ca1410f9a3303b76c6a8dae8dacd867921a88c7b3626"
189
189
  }
190
190
  ]
191
191
  },
@@ -205,7 +205,7 @@
205
205
  "hashes": [
206
206
  {
207
207
  "alg": "SHA-256",
208
- "content": "13d3946992186e019310c1c8666fd724ce74880b8fda19850eeb8b6e0399e3d7"
208
+ "content": "0dce827134ab5f7aaf55bd76325b5e1e17881770310e64e0d66bafbedc91687e"
209
209
  }
210
210
  ]
211
211
  },
@@ -239,6 +239,16 @@
239
239
  }
240
240
  ]
241
241
  },
242
+ {
243
+ "type": "file",
244
+ "name": "test/guard-promote-cli.test.ts",
245
+ "hashes": [
246
+ {
247
+ "alg": "SHA-256",
248
+ "content": "f8e35085106a98be239104394539c3aec350123eed4a115abf14acc2cb6b5bb9"
249
+ }
250
+ ]
251
+ },
242
252
  {
243
253
  "type": "file",
244
254
  "name": "tsconfig.json",
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,
@@ -4964,6 +4979,42 @@ function gatherGuardFacts(op: string, root: string, text: string | undefined, st
4964
4979
  facts['lockfile'] = { parsed: true, importers: rows };
4965
4980
  }
4966
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) */ }
4967
5018
  }
4968
5019
  if (op === 'consolidate') {
4969
5020
  try { facts['drift'] = sweepSkillDrift(root, { scope: 'packages', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name); } catch { /* skip */ }
@@ -4999,6 +5050,341 @@ function runGuardEvaluation(root: string, op: string, text: string | undefined,
4999
5050
  return result;
5000
5051
  }
5001
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
+
5002
5388
  /**
5003
5389
  * `dz guard` — the declarative constraint layer that refuses a self-mutating op when a HARD invariant is
5004
5390
  * violated. Simple outside: `dz guard check --op publish` works with zero config (built-in defaults).
@@ -5040,8 +5426,13 @@ function cmdGuard(options: Map<string, string>, flags: Set<string>, cwd: string,
5040
5426
  return 0;
5041
5427
  }
5042
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
+
5043
5434
  if (sub !== 'check') {
5044
- 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`);
5045
5436
  return 1;
5046
5437
  }
5047
5438