@dzhechkov/harness-cli 0.3.254 → 0.3.257
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/.dz-manifest.json +12 -8
- package/README.md +118 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +472 -6
- package/dist/cli.js.map +1 -1
- package/package.json +2 -2
- package/sbom.json +17 -7
- package/src/cli.ts +447 -5
package/dist/cli.js
CHANGED
|
@@ -3,13 +3,15 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
|
-
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { chmodSync, closeSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
7
7
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
|
-
import { execSync, spawn } from 'node:child_process';
|
|
9
|
+
import { execFileSync, execSync, spawn } from 'node:child_process';
|
|
10
10
|
import { homedir, tmpdir } from 'node:os';
|
|
11
11
|
import { createRequire } from 'node:module';
|
|
12
|
-
import { createSkill, getSkillInfo, getWorkflow, isTargetName, listSkills, runDoctor, runInit, benchmarkSkill, benchmarkSkills, scanMcp, reconcileCapabilities, RECONCILE_BANNER, buildRegistry, discoverSkillPackDirs, checkUpstream, compareSkills, checkAllUpstream, sweepSkillDrift, syncCanonicalSkill, checkUpgrades, discoverPackages, discoverSourcePackages, fetchAllDownloads, filterByCategory, pretrain, recommend, generatePlugin, publishPackages, runSetup, runMigrate, searchRegistry, runSync, runVerify, runInitAgentsMd, runInitGeminiMd, TARGET_NAMES, buildParityMatrix, TARGET_CAPABILITIES, TARGET_SHORT_LABELS, WORKFLOW_NAMES, importEcc, recordPattern, resolveLearningBackend, storeStats, consolidateSessions, pruneNoisePatterns, lessonDeltaReport, removePatternsByIds, snapshotStore, recallHybrid, teachGuard, mirrorPatternsToVector, mirrorEntriesToVector, patternVectorEntry, readMemoryLearningConfig, promotePatterns, quarantineExpiryCandidates, pruneQuarantinePatterns, clearAgentdbQuarantine, vectorMirrorEnabled, vectorTierStatus, resolveVectorEngine, reindexVectorStore, harmonizeVectorStore, importRvfCheckpoint, statuslineData, writeFeatureAdrState, computeUsage, deriveUsageCalibration, normalizeClaudeUsageModelKey, readUsageLimits, claimCheck, summarize, queryBookKnowledge, loadStorePatternsSync, patternRecordId, loadStoreRecords, recordToPattern, bundleSkills, brainHome, listBrain, promoteProjectToBrain, updateBrainSource, queryBrain, groundPrompt, expandKu, reindexBrainVectors, buildPrimer, exportBrainSlice, importBrainSlice, registerKusToBrain, RECALL_USAGE_LOG_RELATIVE, RECALL_USAGE_LOG_MAX_BYTES, parseRecallUsageLog, buildRecallUsageReport, buildManifest, buildSbom, resolveTrustRoot, decideVerifyPolicy, generateSigningKeypair, evaluateGuard, resolveRules, auditRecord, guardExitCode, DEFAULT_RULES, parsePnpmLockImporters,
|
|
12
|
+
import { createSkill, getSkillInfo, getWorkflow, isTargetName, listSkills, runDoctor, runInit, benchmarkSkill, benchmarkSkills, scanMcp, reconcileCapabilities, RECONCILE_BANNER, buildRegistry, discoverSkillPackDirs, checkUpstream, compareSkills, checkAllUpstream, sweepSkillDrift, syncCanonicalSkill, checkUpgrades, discoverPackages, discoverSourcePackages, fetchAllDownloads, filterByCategory, pretrain, recommend, generatePlugin, publishPackages, runSetup, runMigrate, searchRegistry, runSync, runVerify, runInitAgentsMd, runInitGeminiMd, TARGET_NAMES, buildParityMatrix, TARGET_CAPABILITIES, TARGET_SHORT_LABELS, WORKFLOW_NAMES, importEcc, recordPattern, resolveLearningBackend, storeStats, consolidateSessions, pruneNoisePatterns, lessonDeltaReport, removePatternsByIds, snapshotStore, recallHybrid, teachGuard, mirrorPatternsToVector, mirrorEntriesToVector, patternVectorEntry, readMemoryLearningConfig, promotePatterns, quarantineExpiryCandidates, pruneQuarantinePatterns, clearAgentdbQuarantine, vectorMirrorEnabled, vectorTierStatus, resolveVectorEngine, reindexVectorStore, harmonizeVectorStore, importRvfCheckpoint, statuslineData, writeFeatureAdrState, computeUsage, deriveUsageCalibration, normalizeClaudeUsageModelKey, readUsageLimits, claimCheck, summarize, queryBookKnowledge, loadStorePatternsSync, patternRecordId, loadStoreRecords, recordToPattern, bundleSkills, brainHome, listBrain, promoteProjectToBrain, updateBrainSource, queryBrain, groundPrompt, expandKu, reindexBrainVectors, buildPrimer, exportBrainSlice, importBrainSlice, registerKusToBrain, RECALL_USAGE_LOG_RELATIVE, RECALL_USAGE_LOG_MAX_BYTES, parseRecallUsageLog, buildRecallUsageReport, EVENT_CHAIN_TAIL_BYTES, EMPTY_LOG_TAIL, readTailInfo, appendChainedLines, verifyEventChainText, buildManifest, buildSbom, resolveTrustRoot, decideVerifyPolicy, generateSigningKeypair, evaluateGuard, resolveRules, auditRecord, guardExitCode, DEFAULT_RULES, parsePnpmLockImporters,
|
|
13
|
+
// guard-promotion (feature guard-promotion, scout idea #1)
|
|
14
|
+
assembleCandidates, renderPromotionReport, renderPromotionAdr, normalizePromotionState, nextPromotionState, globMatch, promotionAdrRelPath, DEFAULT_WINDOW_DAYS, DEFAULT_PERIODS, MAX_CONTENT_FETCHES, BUILTIN_COVERAGE, decideProvenance, isInsideTree, signManifest, verifyManifest, listSignablePackFiles, assertKeyOutsideTree, decidePublishGate, collectPackageFacts, planReleaseGates, selectAffectedPackages, classifyGateExecutions, buildFailureIssue, buildReleaseNotes, releaseTagName, firstOutputLine, formatPublishError, MANIFEST_NAME, SBOM_NAME, buildArchitectureMap, renderMapHuman, findArchitectureDrift, renderDriftReport, scanWorkspacePackages, loadSubsystemManifest, loadProductVision, checkFeatureAgainstArchitecture, renderArchCheck, planProjectSkills, guidanceForStage, renderInjectionReport, analyzeCorpus, renderRakeReport, renderCriticSection, rakeAsLesson, rakeReward, DEFAULT_RAKE_THRESHOLDS, streamSessionEvents, findLatestTranscript, detectProcessRakes, buildRetro, renderRetro, retroLessonText, PROCESS_SIGNATURES, RETRO_DOMAIN, scanForSetup, buildSetupPlan, scaffoldFromSpec, renderScaffoldPreview, readExistingForScaffold, assembleChallengeContext, buildChallengeBrief, planDiscriminationCheck, classifyDiscrimination, pickAdversaryModel, CHALLENGE_QUESTIONS, loadOutcomes, renderOutcomes, statsForKey, selectAutoCost, recordProvisional, finalizeOutcome, COST_LADDER, splitScenarios, budgetPlan, selectWinner, proseScopeOk, renderProseDiff, readScenarioIds, DEFAULT_MAX_JUDGE_RUNS, collectDeliveryFacts, planDeliveryCheck, renderDeliveryBrief, classifyDelivery, isUsablePlaneResult, renderDeliveryReview, scanSkillsLayout, parseInitFacts, verifyRegistration, buildContentProbePrompt, classifyContentProbe, renderContentProbe, findNonRegistrableSkillDirs, assembleCompoundingReport,
|
|
13
15
|
// Cold-vs-warm EPOCH RUNNER (feature epoch-replay) — orchestrates + scores, never calls a model.
|
|
14
16
|
replayableInstances, buildWorkOrder, buildJudgePrompts, unblindJudgments, verifyWorkOrder, isValidMargin, DIGEST_HONEST_SCOPE, scoreEpochReplay, generateMockOutcomes, renderEpochReplayResult, renderWorkOrderSummary, renderJudgePromptsSummary, WORK_ORDER_KIND, DEFAULT_MOCK_N, DEFAULT_MOCK_SEED, scoreRun, renderScorecard, renderCompoundingReport, readReinforcementState, readQuarantineState, registrationExitCode, renderRegistrationReport,
|
|
15
17
|
// Smart Backlog (feature smart-backlog) — goal-directed idea pipeline over the Brain vector engine.
|
|
@@ -4605,6 +4607,47 @@ function gatherGuardFacts(op, root, text, storeCap) {
|
|
|
4605
4607
|
catch {
|
|
4606
4608
|
facts['lockfile'] = { parsed: false }; /* no lockfile (not a pnpm workspace) — rule stays silent */
|
|
4607
4609
|
}
|
|
4610
|
+
// change: the working-tree diff, for PROMOTED (template) rules. Without this fact a rule written
|
|
4611
|
+
// by `dz guard promote --apply` would be INERT — present in the config and enforcing nothing.
|
|
4612
|
+
// Contents are read only for the globs an active `format-match` rule actually asks about.
|
|
4613
|
+
try {
|
|
4614
|
+
const status = execSync('git status --porcelain', { cwd: root, encoding: 'utf-8' });
|
|
4615
|
+
const files = status
|
|
4616
|
+
.split('\n')
|
|
4617
|
+
.map((l) => l.slice(3).trim())
|
|
4618
|
+
.map((p) => (p.includes(' -> ') ? p.split(' -> ')[1].trim() : p)) // renames: the destination is the changed path
|
|
4619
|
+
.filter((p) => p !== '');
|
|
4620
|
+
const formatGlobs = (Array.isArray(loadGuardConfig(root).rules) ? loadGuardConfig(root).rules : [])
|
|
4621
|
+
.filter((r) => r?.template === 'format-match' && typeof r?.params?.file === 'string')
|
|
4622
|
+
.map((r) => r.params.file);
|
|
4623
|
+
const contents = {};
|
|
4624
|
+
if (formatGlobs.length > 0) {
|
|
4625
|
+
for (const f of files) {
|
|
4626
|
+
if (!formatGlobs.some((g) => globMatch(g, f)))
|
|
4627
|
+
continue;
|
|
4628
|
+
const abs = resolve(root, f);
|
|
4629
|
+
// Containment: a `git status` path is repo-relative, but `..` in one must never let the
|
|
4630
|
+
// LIVE reader step outside the repo the HISTORICAL reader is confined to.
|
|
4631
|
+
if (abs !== root && !abs.startsWith(root + sep))
|
|
4632
|
+
continue;
|
|
4633
|
+
try {
|
|
4634
|
+
// lstat, NOT stat (Codex QE MED-3). `git show <sha>:<path>` yields the SYMLINK TARGET
|
|
4635
|
+
// TEXT, never the file it points at, so a live reader that follows links answers a
|
|
4636
|
+
// different question than the replay — and `/dev/zero` behind a symlink hangs the read.
|
|
4637
|
+
// Skipping non-regular files restores replay/live equivalence and closes the DoS.
|
|
4638
|
+
const st = lstatSync(abs);
|
|
4639
|
+
if (!st.isFile())
|
|
4640
|
+
continue;
|
|
4641
|
+
if (st.size > MAX_CONTENT_BYTES)
|
|
4642
|
+
continue; // too large to be a spec file — undecidable, never guessed
|
|
4643
|
+
contents[f] = readFileSync(abs, 'utf8');
|
|
4644
|
+
}
|
|
4645
|
+
catch { /* deleted — leave it undecidable, never guess */ }
|
|
4646
|
+
}
|
|
4647
|
+
}
|
|
4648
|
+
facts['change'] = { files, ...(Object.keys(contents).length > 0 ? { contents } : {}) };
|
|
4649
|
+
}
|
|
4650
|
+
catch { /* not a git repo — every template rule stays silent (fail-open) */ }
|
|
4608
4651
|
}
|
|
4609
4652
|
if (op === 'consolidate') {
|
|
4610
4653
|
try {
|
|
@@ -4643,11 +4686,417 @@ function runGuardEvaluation(root, op, text, overrideReason) {
|
|
|
4643
4686
|
try {
|
|
4644
4687
|
const rec = auditRecord(result, new Date().toISOString(), overrideReason !== undefined ? { reason: overrideReason } : undefined);
|
|
4645
4688
|
mkdirSync(join(root, '.dz'), { recursive: true });
|
|
4646
|
-
|
|
4689
|
+
const auditPath = join(root, '.dz', 'guard-audit.jsonl');
|
|
4690
|
+
// event-chain (ADR-001): seq + prevHash derived from the LAST LINE ONLY — this file is the
|
|
4691
|
+
// evidence base `dz guard promote` decides on, and a rewrite that loses or duplicates a record
|
|
4692
|
+
// must not be able to look intact. A tail that cannot be read starts a MARKED segment rather
|
|
4693
|
+
// than blocking the audit: the verdict is never held hostage to a broken log.
|
|
4694
|
+
writeFileSync(auditPath, appendChainedLines([rec], readLogTail(auditPath)), { flag: 'a' });
|
|
4647
4695
|
}
|
|
4648
4696
|
catch { /* audit is best-effort, never blocks the verdict */ }
|
|
4649
4697
|
return result;
|
|
4650
4698
|
}
|
|
4699
|
+
/**
|
|
4700
|
+
* The tail facts of an append-only log, read from its END — O(1) in the file size, which is what
|
|
4701
|
+
* lets the chain be extended on every append without a full-file scan (FR-2). Anything unreadable
|
|
4702
|
+
* yields {@link EMPTY_LOG_TAIL}; the caller then starts a marked segment rather than blocking.
|
|
4703
|
+
*/
|
|
4704
|
+
function readLogTail(path) {
|
|
4705
|
+
let fd;
|
|
4706
|
+
try {
|
|
4707
|
+
if (!existsSync(path))
|
|
4708
|
+
return EMPTY_LOG_TAIL;
|
|
4709
|
+
fd = openSync(path, 'r');
|
|
4710
|
+
const size = fstatSync(fd).size;
|
|
4711
|
+
if (!Number.isFinite(size) || size <= 0)
|
|
4712
|
+
return EMPTY_LOG_TAIL;
|
|
4713
|
+
const want = Math.min(size, EVENT_CHAIN_TAIL_BYTES);
|
|
4714
|
+
const buf = Buffer.alloc(want);
|
|
4715
|
+
readSync(fd, buf, 0, want, size - want);
|
|
4716
|
+
return readTailInfo(buf.toString('utf-8'), { partial: want < size });
|
|
4717
|
+
}
|
|
4718
|
+
catch {
|
|
4719
|
+
// A read FAILURE is not an empty file (Codex re-QE LOW): EMPTY_LOG_TAIL means "there is
|
|
4720
|
+
// nothing", which lets the writer open an UNMARKED genesis on a file we merely failed to
|
|
4721
|
+
// read. An unreadable tail must force a marked reset, per the AM-6 contract.
|
|
4722
|
+
return { ...EMPTY_LOG_TAIL, unreadable: true };
|
|
4723
|
+
}
|
|
4724
|
+
finally {
|
|
4725
|
+
if (fd !== undefined) {
|
|
4726
|
+
try {
|
|
4727
|
+
closeSync(fd);
|
|
4728
|
+
}
|
|
4729
|
+
catch { /* nothing to do */ }
|
|
4730
|
+
}
|
|
4731
|
+
}
|
|
4732
|
+
}
|
|
4733
|
+
// ── `dz guard promote` (feature guard-promotion, scout idea #1) ─────────────────────────────────
|
|
4734
|
+
const PROMOTIONS_DIR = join('features', 'guard-promotion', 'promotions');
|
|
4735
|
+
const PROMOTION_STATE_FILE = join('.dz', 'promotion-state.json');
|
|
4736
|
+
/**
|
|
4737
|
+
* Ceiling on a single file read, applied IDENTICALLY to the historical (`git show`) and live
|
|
4738
|
+
* (working-tree) readers. A `format-match` target is a spec/manifest file; anything larger is not
|
|
4739
|
+
* one, and an unbounded read of a symlinked `/dev/zero` is a hang, not a measurement.
|
|
4740
|
+
*/
|
|
4741
|
+
const MAX_CONTENT_BYTES = 1024 * 1024;
|
|
4742
|
+
const GUARD_PROMOTE_USAGE = [
|
|
4743
|
+
'dz guard promote [--project <dir>] [--json] [--dry-run | --apply]',
|
|
4744
|
+
' [--window-days <N>] [--periods <N>] [--limit <N>]',
|
|
4745
|
+
].join('\n ');
|
|
4746
|
+
/**
|
|
4747
|
+
* Read real commit history as {@link ChangeSet}s — the shadow-replay corpus. `--name-only` gives the
|
|
4748
|
+
* change shape every v1 template consumes. Merges are excluded (their file list is a union of the
|
|
4749
|
+
* branches, not a decision anyone made).
|
|
4750
|
+
*
|
|
4751
|
+
* A missing/failing `git` yields `[]`, which makes every candidate `insufficient-data` — the command
|
|
4752
|
+
* still exits 0 and says why. No history is not a promotion.
|
|
4753
|
+
*/
|
|
4754
|
+
function readGitChanges(root, sinceIso) {
|
|
4755
|
+
let out = '';
|
|
4756
|
+
try {
|
|
4757
|
+
// execFileSync (argv form), NOT a shell string: `--name-only` paths come straight from the repo,
|
|
4758
|
+
// and a filename containing `$(…)` or a backtick would EXPAND inside a double-quoted shell
|
|
4759
|
+
// argument. `-z` is not used because the pretty header needs line framing; the argv form removes
|
|
4760
|
+
// the shell entirely instead.
|
|
4761
|
+
out = execFileSync('git', ['log', `--since=${sinceIso}`, '--no-merges', '--name-only', '--pretty=format:%x01%H%x09%cI'], {
|
|
4762
|
+
cwd: root,
|
|
4763
|
+
encoding: 'utf-8',
|
|
4764
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
4765
|
+
});
|
|
4766
|
+
}
|
|
4767
|
+
catch {
|
|
4768
|
+
return [];
|
|
4769
|
+
}
|
|
4770
|
+
const changes = [];
|
|
4771
|
+
let current = null;
|
|
4772
|
+
for (const raw of out.split('\n')) {
|
|
4773
|
+
if (raw.startsWith('\x01')) {
|
|
4774
|
+
if (current)
|
|
4775
|
+
changes.push(current);
|
|
4776
|
+
const [id, ts] = raw.slice(1).split('\t');
|
|
4777
|
+
current = { id: (id ?? '').slice(0, 12), ts: ts ?? '', files: [] };
|
|
4778
|
+
continue;
|
|
4779
|
+
}
|
|
4780
|
+
const line = raw.trim();
|
|
4781
|
+
if (line === '' || current === null)
|
|
4782
|
+
continue;
|
|
4783
|
+
current.files.push(line);
|
|
4784
|
+
}
|
|
4785
|
+
if (current)
|
|
4786
|
+
changes.push(current);
|
|
4787
|
+
return changes;
|
|
4788
|
+
}
|
|
4789
|
+
/**
|
|
4790
|
+
* Attach file text at each historical commit for the `format-match` candidates that need it.
|
|
4791
|
+
*
|
|
4792
|
+
* HARD CAP (`MAX_CONTENT_FETCHES`): over it we STOP fetching, which leaves those changes without
|
|
4793
|
+
* contents, which makes `templateFires` return `undecidable`, which makes the candidate
|
|
4794
|
+
* `insufficient-data`. What we deliberately do NOT do is fall back to the file's CURRENT content —
|
|
4795
|
+
* evaluating a historical commit against today's file is exactly the fabricated-win shape ADR-002
|
|
4796
|
+
* refused for `presence-check`.
|
|
4797
|
+
*/
|
|
4798
|
+
function attachChangeContents(root, changes, globs) {
|
|
4799
|
+
if (globs.length === 0)
|
|
4800
|
+
return [...changes];
|
|
4801
|
+
let budget = MAX_CONTENT_FETCHES;
|
|
4802
|
+
return changes.map((c) => {
|
|
4803
|
+
const wanted = c.files.filter((f) => globs.some((g) => globMatch(g, f)));
|
|
4804
|
+
if (wanted.length === 0)
|
|
4805
|
+
return c;
|
|
4806
|
+
const contents = {};
|
|
4807
|
+
for (const f of wanted) {
|
|
4808
|
+
if (budget <= 0)
|
|
4809
|
+
return c; // over cap ⇒ leave this change undecidable, never guess
|
|
4810
|
+
budget -= 1;
|
|
4811
|
+
try {
|
|
4812
|
+
// argv form, NOT a shell string: a repo path is untrusted input and `$(…)`/backticks would
|
|
4813
|
+
// expand inside a quoted shell argument. No `--` terminator — `git show -- <rev>:<path>`
|
|
4814
|
+
// exits 0 with EMPTY output (the terminator turns the rev-with-path into a pathspec). The
|
|
4815
|
+
// option-smuggling risk it would have covered is absent anyway: the argument always begins
|
|
4816
|
+
// with a 12-hex sha.
|
|
4817
|
+
const text = execFileSync('git', ['show', `${c.id}:${f}`], { cwd: root, encoding: 'utf-8', maxBuffer: MAX_CONTENT_BYTES });
|
|
4818
|
+
// Same size ceiling as the live reader, so replay and live agree on what is too big to judge.
|
|
4819
|
+
if (text.length > MAX_CONTENT_BYTES)
|
|
4820
|
+
return c;
|
|
4821
|
+
// EMPTY OUTPUT IS NOT CONTENT. git reported this path as changed in this commit, so an
|
|
4822
|
+
// empty body is far more likely a failed lookup than a genuinely empty file — and treating
|
|
4823
|
+
// it as content is the worst possible failure: `''.includes(x)` is false, so the rule would
|
|
4824
|
+
// FIRE on every single file and fabricate a clean sweep of wins. Undecidable instead.
|
|
4825
|
+
if (text === '')
|
|
4826
|
+
return c;
|
|
4827
|
+
contents[f] = text;
|
|
4828
|
+
}
|
|
4829
|
+
catch {
|
|
4830
|
+
return c; // deleted/renamed at that commit — undecidable, not clean
|
|
4831
|
+
}
|
|
4832
|
+
}
|
|
4833
|
+
return { ...c, contents };
|
|
4834
|
+
});
|
|
4835
|
+
}
|
|
4836
|
+
/** Every rule the engine would run: the built-ins plus any template rules already in `.dz/guard.json`. */
|
|
4837
|
+
function existingRuleViews(root) {
|
|
4838
|
+
const cfg = loadGuardConfig(root);
|
|
4839
|
+
const configRules = Array.isArray(cfg.rules) ? cfg.rules : [];
|
|
4840
|
+
const disabled = new Set(configRules.filter((r) => r?.enabled === false && typeof r.id === 'string').map((r) => r.id));
|
|
4841
|
+
// A built-in the operator has DISABLED does not cover anything — otherwise the promoter would
|
|
4842
|
+
// refuse a candidate as a duplicate of a rule that is not running, and the gap would stay open.
|
|
4843
|
+
const views = DEFAULT_RULES.filter((r) => !disabled.has(r.id)).map((r) => ({ id: r.id }));
|
|
4844
|
+
for (const o of configRules) {
|
|
4845
|
+
if (typeof o?.id !== 'string' || o.enabled === false)
|
|
4846
|
+
continue;
|
|
4847
|
+
// A rule op-scoped AWAY from publish covers nothing a change-shaped promotion targets — letting
|
|
4848
|
+
// it suppress a candidate as a "duplicate" keeps the gap open (Codex re-QE MED, mirror of the
|
|
4849
|
+
// disabled-builtin rationale above).
|
|
4850
|
+
const ops = o.ops;
|
|
4851
|
+
if (Array.isArray(ops) && !ops.includes('publish'))
|
|
4852
|
+
continue;
|
|
4853
|
+
if (views.some((v) => v.id === o.id))
|
|
4854
|
+
continue;
|
|
4855
|
+
views.push({ id: o.id, ...(typeof o.template === 'string' ? { template: o.template } : {}), ...(o.params && typeof o.params === 'object' ? { params: o.params } : {}) });
|
|
4856
|
+
}
|
|
4857
|
+
return views;
|
|
4858
|
+
}
|
|
4859
|
+
/** Atomic JSON write — tmp + rename, so a crash mid-write never leaves a half-parsed state file. */
|
|
4860
|
+
function writeJsonAtomic(path, value) {
|
|
4861
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
4862
|
+
const tmp = `${path}.tmp.${process.pid}`;
|
|
4863
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf-8');
|
|
4864
|
+
renameSync(tmp, path);
|
|
4865
|
+
}
|
|
4866
|
+
/** The rolled-up refusal record (ADR-004): one file, regenerated in place, one row per lesson. */
|
|
4867
|
+
function renderNotPromotableRollup(report, nowTs) {
|
|
4868
|
+
const refused = report.candidates.filter((c) => c.verdict === 'not-promotable');
|
|
4869
|
+
const out = [];
|
|
4870
|
+
out.push('# 000 — Not promotable (rolled-up refusal record)');
|
|
4871
|
+
out.push('');
|
|
4872
|
+
out.push(`**Decision:** REFUSED · **Date:** ${nowTs} · **Count:** ${refused.length} of ${report.totalLessons} lesson(s)`);
|
|
4873
|
+
out.push('');
|
|
4874
|
+
out.push('These lessons do not reduce to a v1 `dz guard promote` rule template. Rule code is NEVER');
|
|
4875
|
+
out.push('synthesised from lesson text (ADR-002), so a lesson that fits no template is refused aloud');
|
|
4876
|
+
out.push('rather than force-fitted. This file is regenerated in place on every run.');
|
|
4877
|
+
out.push('');
|
|
4878
|
+
out.push('| lesson | reason | first 90 chars |');
|
|
4879
|
+
out.push('|---|---|---|');
|
|
4880
|
+
for (const c of refused) {
|
|
4881
|
+
const t = c.lessonText.replace(/\|/g, '\\|').replace(/\n/g, ' ').slice(0, 90);
|
|
4882
|
+
out.push(`| \`${c.lessonId}\` | ${c.reason.replace(/\|/g, '\\|')} | ${t} |`);
|
|
4883
|
+
}
|
|
4884
|
+
return out.join('\n') + '\n';
|
|
4885
|
+
}
|
|
4886
|
+
/**
|
|
4887
|
+
* `dz guard promote` — lesson → guard-rule promotion with a "win twice to promote" gate.
|
|
4888
|
+
*
|
|
4889
|
+
* Thin by design: gather (lessons, existing rules, real commit history, state) → the PURE
|
|
4890
|
+
* `assembleCandidates` → render → write. Default PROPOSES (documents + journal only); `--dry-run`
|
|
4891
|
+
* writes nothing at all; `--apply` is the only path that touches `.dz/guard.json`, always SOFT.
|
|
4892
|
+
*/
|
|
4893
|
+
function cmdGuardPromote(options, flags, root, write) {
|
|
4894
|
+
const json = flags.has('json');
|
|
4895
|
+
const fail = (msg) => {
|
|
4896
|
+
write(json ? JSON.stringify({ error: msg, exitCode: 1 }) : `dz guard promote: ${msg}\n usage: ${GUARD_PROMOTE_USAGE}`);
|
|
4897
|
+
return 1;
|
|
4898
|
+
};
|
|
4899
|
+
for (const f of flags)
|
|
4900
|
+
if (!['json', 'dry-run', 'apply', 'help'].includes(f))
|
|
4901
|
+
return fail(`unknown option --${f}`);
|
|
4902
|
+
for (const k of options.keys()) {
|
|
4903
|
+
if (k === '_positional_0')
|
|
4904
|
+
continue; // the `promote` subcommand token itself
|
|
4905
|
+
if (k.startsWith('_positional_'))
|
|
4906
|
+
return fail(`unexpected argument "${options.get(k)}"`);
|
|
4907
|
+
if (!['project', 'window-days', 'periods', 'limit'].includes(k))
|
|
4908
|
+
return fail(`unknown option --${k}`);
|
|
4909
|
+
}
|
|
4910
|
+
if (flags.has('help')) {
|
|
4911
|
+
write(`dz guard promote — promote a learned lesson to a deterministic guard rule\n usage: ${GUARD_PROMOTE_USAGE}`);
|
|
4912
|
+
write(' A candidate must SHADOW-WIN twice consecutively over real commit history before it is proposed.');
|
|
4913
|
+
write(' Default: writes proposal/refusal documents only. --dry-run: writes nothing. --apply: writes the SOFT rule into .dz/guard.json.');
|
|
4914
|
+
return 0;
|
|
4915
|
+
}
|
|
4916
|
+
const dryRun = flags.has('dry-run');
|
|
4917
|
+
const apply = flags.has('apply');
|
|
4918
|
+
// NOT a silent precedence: two contradictory intents is an error, not a coin flip.
|
|
4919
|
+
if (dryRun && apply)
|
|
4920
|
+
return fail('--dry-run and --apply are mutually exclusive');
|
|
4921
|
+
const num = (key, dflt, lo, hi) => {
|
|
4922
|
+
const raw = options.get(key);
|
|
4923
|
+
if (raw === undefined)
|
|
4924
|
+
return dflt;
|
|
4925
|
+
const n = Number(raw);
|
|
4926
|
+
if (!Number.isFinite(n) || !Number.isInteger(n) || n < lo || n > hi)
|
|
4927
|
+
return null;
|
|
4928
|
+
return n;
|
|
4929
|
+
};
|
|
4930
|
+
const windowDays = num('window-days', DEFAULT_WINDOW_DAYS, 1, 365);
|
|
4931
|
+
if (windowDays === null)
|
|
4932
|
+
return fail('--window-days expects an integer in [1, 365]');
|
|
4933
|
+
const periods = num('periods', DEFAULT_PERIODS, 2, 52);
|
|
4934
|
+
if (periods === null)
|
|
4935
|
+
return fail('--periods expects an integer in [2, 52]');
|
|
4936
|
+
const limit = num('limit', 15, 1, 1000);
|
|
4937
|
+
if (limit === null)
|
|
4938
|
+
return fail('--limit expects an integer in [1, 1000]');
|
|
4939
|
+
const nowTs = new Date().toISOString();
|
|
4940
|
+
const sinceIso = new Date(Date.now() - windowDays * periods * 86_400_000).toISOString();
|
|
4941
|
+
// lessons — the SAME readers `dz compounding` uses; no second store.
|
|
4942
|
+
const lessons = loadStoreRecords(root).map((r) => ({
|
|
4943
|
+
dzId: r.id,
|
|
4944
|
+
text: typeof r.text === 'string' ? r.text : '',
|
|
4945
|
+
quarantined: readQuarantineState(r).quarantined,
|
|
4946
|
+
uses: readReinforcementState(r).uses,
|
|
4947
|
+
}));
|
|
4948
|
+
const existingRules = existingRuleViews(root);
|
|
4949
|
+
const changes = readGitChanges(root, sinceIso);
|
|
4950
|
+
// State is read on EVERY run, including --dry-run, because it carries the LOCAL-clock `firstSeen`
|
|
4951
|
+
// the elapsed gate reads (MED-7). --dry-run still writes nothing — which is exactly why a
|
|
4952
|
+
// dry-run-only workflow never starts that clock, and the wait reason says so.
|
|
4953
|
+
const state = normalizePromotionState((() => {
|
|
4954
|
+
try {
|
|
4955
|
+
return JSON.parse(readFileSync(join(root, PROMOTION_STATE_FILE), 'utf-8'));
|
|
4956
|
+
}
|
|
4957
|
+
catch {
|
|
4958
|
+
return null;
|
|
4959
|
+
}
|
|
4960
|
+
})());
|
|
4961
|
+
const firstSeen = {};
|
|
4962
|
+
for (const [id, e] of Object.entries(state.entries))
|
|
4963
|
+
if (e.firstSeenTs !== '')
|
|
4964
|
+
firstSeen[id] = e.firstSeenTs;
|
|
4965
|
+
// Pass 1 discovers which `format-match` candidates exist, so contents are fetched only for the
|
|
4966
|
+
// globs that actually need them (and only up to the cap).
|
|
4967
|
+
const pass1 = assembleCandidates({ lessons, existingRules, changes, nowTs, windowDays, periods, firstSeen });
|
|
4968
|
+
const formatGlobs = [...new Set(pass1.candidates.filter((c) => c.template === 'format-match' && typeof c.params?.file === 'string').map((c) => c.params.file))];
|
|
4969
|
+
const report = formatGlobs.length === 0
|
|
4970
|
+
? pass1
|
|
4971
|
+
: assembleCandidates({ lessons, existingRules, changes: attachChangeContents(root, changes, formatGlobs), nowTs, windowDays, periods, firstSeen });
|
|
4972
|
+
// ── write side ────────────────────────────────────────────────────────────────────────────────
|
|
4973
|
+
const written = [];
|
|
4974
|
+
const applied = [];
|
|
4975
|
+
const conflicts = [];
|
|
4976
|
+
if (!dryRun) {
|
|
4977
|
+
const adrSeqs = {};
|
|
4978
|
+
let seq = state.nextAdrSeq;
|
|
4979
|
+
let allocated = 0;
|
|
4980
|
+
for (const c of report.candidates) {
|
|
4981
|
+
if (c.verdict !== 'promote' && c.verdict !== 'duplicate')
|
|
4982
|
+
continue;
|
|
4983
|
+
const key = c.ruleId;
|
|
4984
|
+
// ONE document per CANDIDATE, not per run — but the reused thing is the integer SEQUENCE, never
|
|
4985
|
+
// a path. State is attacker-shaped input (a JSON file anyone can corrupt), and a path taken
|
|
4986
|
+
// from it and handed to writeFileSync overwrites whatever it names — with no `--apply`, no
|
|
4987
|
+
// promotion, and no way to notice. The path is DERIVED from the validated id + that integer.
|
|
4988
|
+
const existingSeq = state.entries[key]?.adrSeq;
|
|
4989
|
+
const useSeq = existingSeq ?? seq;
|
|
4990
|
+
const rel = promotionAdrRelPath(key, useSeq);
|
|
4991
|
+
if (rel === null)
|
|
4992
|
+
continue; // an id or sequence that fails validation writes NOTHING
|
|
4993
|
+
if (existingSeq === undefined) {
|
|
4994
|
+
seq += 1;
|
|
4995
|
+
allocated += 1;
|
|
4996
|
+
}
|
|
4997
|
+
// Belt to the derivation's braces: resolve and assert containment before writing. A derivation
|
|
4998
|
+
// that is correct today is not a substitute for checking the thing you are about to write.
|
|
4999
|
+
const abs = resolve(root, rel);
|
|
5000
|
+
const dir = resolve(root, PROMOTIONS_DIR);
|
|
5001
|
+
if (abs !== dir && !abs.startsWith(dir + sep))
|
|
5002
|
+
continue;
|
|
5003
|
+
try {
|
|
5004
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
5005
|
+
// Lexical containment is not PHYSICAL containment (Codex re-QE HIGH): a symlinked
|
|
5006
|
+
// promotions/ directory (or a symlink planted at the ADR leaf) redirects the write outside
|
|
5007
|
+
// the repo while every string check passes. realpath the directory that actually exists on
|
|
5008
|
+
// disk and require it to be the real promotions dir under the real root; refuse a leaf that
|
|
5009
|
+
// is a symlink.
|
|
5010
|
+
const realDir = realpathSync(dirname(abs));
|
|
5011
|
+
const expectedReal = join(realpathSync(root), PROMOTIONS_DIR.split('/').join(sep));
|
|
5012
|
+
if (realDir !== expectedReal)
|
|
5013
|
+
continue;
|
|
5014
|
+
if (existsSync(abs) && lstatSync(abs).isSymbolicLink())
|
|
5015
|
+
continue;
|
|
5016
|
+
writeFileSync(abs, renderPromotionAdr(c, useSeq, nowTs), 'utf-8');
|
|
5017
|
+
adrSeqs[key] = useSeq;
|
|
5018
|
+
written.push(rel);
|
|
5019
|
+
}
|
|
5020
|
+
catch { /* a document we cannot write must not lose the verdict */ }
|
|
5021
|
+
}
|
|
5022
|
+
if (report.candidates.some((c) => c.verdict === 'not-promotable')) {
|
|
5023
|
+
const rel = join(PROMOTIONS_DIR, '000-not-promotable.md');
|
|
5024
|
+
try {
|
|
5025
|
+
mkdirSync(join(root, PROMOTIONS_DIR), { recursive: true });
|
|
5026
|
+
writeFileSync(join(root, rel), renderNotPromotableRollup(report, nowTs), 'utf-8');
|
|
5027
|
+
written.push(rel);
|
|
5028
|
+
}
|
|
5029
|
+
catch { /* best-effort */ }
|
|
5030
|
+
}
|
|
5031
|
+
if (apply) {
|
|
5032
|
+
const cfg = loadGuardConfig(root);
|
|
5033
|
+
const rules = Array.isArray(cfg.rules) ? [...cfg.rules] : [];
|
|
5034
|
+
for (const c of report.candidates) {
|
|
5035
|
+
if (c.verdict !== 'promote' || c.proposedRule === null)
|
|
5036
|
+
continue;
|
|
5037
|
+
const want = c.proposedRule;
|
|
5038
|
+
const clash = rules.find((r) => r?.id === want.id);
|
|
5039
|
+
if (clash !== undefined) {
|
|
5040
|
+
// ID EQUALITY IS NOT IDEMPOTENCE (Codex QE MED-5). A rule that merely SHARES the id — a
|
|
5041
|
+
// hand-written bare entry, or a same-id rule with different params — is not the rule we
|
|
5042
|
+
// are promoting. Skipping it silently reports "applied" while installing nothing (the bare
|
|
5043
|
+
// entry does not even enforce, since resolveRules drops an unknown id with no template).
|
|
5044
|
+
// Same id + same BODY is genuine idempotence; same id + different body is a conflict, and a
|
|
5045
|
+
// conflict is refused out loud rather than resolved by guessing which side to keep.
|
|
5046
|
+
const sameBody = clash.template === want.template && JSON.stringify(clash.params ?? null) === JSON.stringify(want.params);
|
|
5047
|
+
// Same body but DISABLED (or op-scoped away from publish) is NOT idempotence: the rule
|
|
5048
|
+
// exists on paper and enforces nothing — "already installed" would be a false success
|
|
5049
|
+
// (Codex re-QE MED). Refuse loudly so the operator re-enables or removes it.
|
|
5050
|
+
const clashEnabled = clash.enabled !== false;
|
|
5051
|
+
const clashOps = clash.ops;
|
|
5052
|
+
const clashCoversPublish = !Array.isArray(clashOps) || clashOps.includes('publish');
|
|
5053
|
+
if (sameBody && clashEnabled && clashCoversPublish)
|
|
5054
|
+
continue; // already installed AND active — genuine idempotence
|
|
5055
|
+
if (sameBody) {
|
|
5056
|
+
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`);
|
|
5057
|
+
continue;
|
|
5058
|
+
}
|
|
5059
|
+
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`);
|
|
5060
|
+
continue;
|
|
5061
|
+
}
|
|
5062
|
+
rules.push(want);
|
|
5063
|
+
applied.push(want.id);
|
|
5064
|
+
}
|
|
5065
|
+
if (applied.length > 0)
|
|
5066
|
+
writeJsonAtomic(join(root, '.dz', 'guard.json'), { ...cfg, rules });
|
|
5067
|
+
}
|
|
5068
|
+
const next = nextPromotionState(state, report, nowTs, adrSeqs, allocated);
|
|
5069
|
+
const withApplied = applied.length === 0 ? next : {
|
|
5070
|
+
...next,
|
|
5071
|
+
entries: Object.fromEntries(Object.entries(next.entries).map(([k, v]) => (applied.includes(k) ? [k, { ...v, appliedTs: nowTs }] : [k, v]))),
|
|
5072
|
+
};
|
|
5073
|
+
try {
|
|
5074
|
+
writeJsonAtomic(join(root, PROMOTION_STATE_FILE), withApplied);
|
|
5075
|
+
}
|
|
5076
|
+
catch { /* best-effort */ }
|
|
5077
|
+
}
|
|
5078
|
+
// A refused conflict means the requested apply did NOT fully happen — exit non-zero rather than
|
|
5079
|
+
// let a zero exit report success for work that was deliberately not done.
|
|
5080
|
+
const exitCode = conflicts.length > 0 ? 1 : 0;
|
|
5081
|
+
if (json) {
|
|
5082
|
+
write(JSON.stringify({ ...report, mode: dryRun ? 'dry-run' : apply ? 'apply' : 'propose', written, applied, conflicts, exitCode }, null, 2));
|
|
5083
|
+
return exitCode;
|
|
5084
|
+
}
|
|
5085
|
+
write(renderPromotionReport(report, limit));
|
|
5086
|
+
write('');
|
|
5087
|
+
if (dryRun)
|
|
5088
|
+
write(' MODE: --dry-run — nothing was written (not even .dz/promotion-state.json)');
|
|
5089
|
+
else {
|
|
5090
|
+
write(` WROTE: ${written.length === 0 ? '(no decisions to record)' : written.join(', ')}`);
|
|
5091
|
+
if (apply)
|
|
5092
|
+
write(` APPLIED to .dz/guard.json: ${applied.length === 0 ? '(none)' : applied.join(', ')} — SOFT severity, always`);
|
|
5093
|
+
else
|
|
5094
|
+
write(' Nothing was written to .dz/guard.json — re-run with --apply to install the promoted rule(s).');
|
|
5095
|
+
}
|
|
5096
|
+
for (const c of conflicts)
|
|
5097
|
+
write(` ✗ CONFLICT — ${c}`);
|
|
5098
|
+
return exitCode;
|
|
5099
|
+
}
|
|
4651
5100
|
/**
|
|
4652
5101
|
* `dz guard` — the declarative constraint layer that refuses a self-mutating op when a HARD invariant is
|
|
4653
5102
|
* violated. Simple outside: `dz guard check --op publish` works with zero config (built-in defaults).
|
|
@@ -4703,8 +5152,13 @@ function cmdGuard(options, flags, cwd, write) {
|
|
|
4703
5152
|
}
|
|
4704
5153
|
return 0;
|
|
4705
5154
|
}
|
|
5155
|
+
// `promote` — lesson → guard-rule promotion. It lives HERE, not as a top-level `dz promote`,
|
|
5156
|
+
// because its object IS a guard rule: its evidence is .dz/guard-audit.jsonl + real commit history
|
|
5157
|
+
// and its write target is .dz/guard.json (ADR-001).
|
|
5158
|
+
if (sub === 'promote')
|
|
5159
|
+
return cmdGuardPromote(options, flags, options.get('project') !== undefined ? resolve(cwd, options.get('project')) : root, write);
|
|
4706
5160
|
if (sub !== 'check') {
|
|
4707
|
-
write(`dz guard: unknown subcommand '${sub}' — use: check --op <op> | --init | log`);
|
|
5161
|
+
write(`dz guard: unknown subcommand '${sub}' — use: check --op <op> | promote | --init | log`);
|
|
4708
5162
|
return 1;
|
|
4709
5163
|
}
|
|
4710
5164
|
// check
|
|
@@ -5604,7 +6058,19 @@ function cmdCompounding(options, flags, cwd, write) {
|
|
|
5604
6058
|
catch {
|
|
5605
6059
|
/* no audit yet */
|
|
5606
6060
|
}
|
|
5607
|
-
|
|
6061
|
+
// The evidence logs themselves, verbatim: the report verifies their hash chains (feature
|
|
6062
|
+
// event-chain). Handing over the TEXT rather than a pre-computed verdict keeps one definition of
|
|
6063
|
+
// "the chain is intact" — a second copy here is how a gate and its report start disagreeing.
|
|
6064
|
+
const evidenceLogs = [];
|
|
6065
|
+
for (const rel of ['.dz/recall-usage.jsonl', '.dz/guard-audit.jsonl']) {
|
|
6066
|
+
try {
|
|
6067
|
+
evidenceLogs.push({ log: rel, text: readFileSync(join(root, ...rel.split('/')), 'utf-8') });
|
|
6068
|
+
}
|
|
6069
|
+
catch {
|
|
6070
|
+
/* absent log — reported by its own gate above, not invented here */
|
|
6071
|
+
}
|
|
6072
|
+
}
|
|
6073
|
+
const report = assembleCompoundingReport({ lessons, usage, guard, nowTs: new Date().toISOString(), evidenceLogs });
|
|
5608
6074
|
if (json)
|
|
5609
6075
|
write(JSON.stringify({ ...report, exitCode: 0 }, null, 2));
|
|
5610
6076
|
else
|