@dzhechkov/harness-cli 0.8.2 → 0.8.5

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/dist/cli.js CHANGED
@@ -16,9 +16,9 @@ import { homedir, tmpdir } from 'node:os';
16
16
  import { createRequire } from 'node:module';
17
17
  import { createSkill, getSkillInfo, listSkillsDetailed, formatSkillLoadFailures, formatSkillApplyFailures, resolveTargetName, formatTargetProblem, formatTargetAliasNote, TARGET_NAMES_SORTED, runDoctor, runInit, resolvePackageSkillRoots, PACKAGE_SKILL_LAYOUTS, benchmarkSkill, benchmarkSkills, scanMcp, reconcileCapabilities, RECONCILE_BANNER, buildRegistry, discoverSkillPackDirs, discoverVerifiablePackDirs, checkUpstream, compareSkills, checkAllUpstream, sweepSkillDrift, syncCanonicalSkill, checkUpgrades, discoverPackages, discoverSourcePackages, fetchAllDownloads, filterByCategory, pretrain, recommend, generatePlugin, publishPackages, runSetup, runMigrate, searchRegistry, runSync, runVerify, runInitAgentsMd, runInitGeminiMd, runSyncAgentsPolicy, runSyncCodexHooks, resolveCodexHome, withNamedLockSync,
18
18
  // dz workflow run (feature dz-workflow-run): the pure scheduler + the dispatch adapters.
19
- TRACE_RUNID_RE, WF_RUN_OWNER_HOST, preflight, runWorkflow, makeClaudePDispatcher, makeCodexExecDispatcher, NamedLockTimeoutError, NamedLockCompromisedError, POLICY_SOURCES, detectPolicyDrift, hasPolicyFence, TARGET_NAMES, buildParityMatrix, downgradeForStaleEvidence, findStaleTranscriptEvidence, TARGET_CAPABILITIES, TARGET_SHORT_LABELS, WORKFLOW_TEMPLATES_RETIRED_MESSAGE, parsePlan, isParseErrors, validatePlan, normalizePlan, planDigest, toTraceProjection, renderPlan, mergeRender, lint, lintExitCode, LOOP_BLOBS, parseTrace, assembleTimeline, runInvariants, deriveAttestation, stampAttestation, corroborate, NOT_WITNESSED, renderTimelineHtml, 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, deriveCostLedger, planLedgerBackfill, listCostLedgerRuns, resolveLedgerRunId, AMBIGUOUS, stampCheckpointLine, LEDGER_FILL_SOURCE, renderCostLedger, verifyCostLedgerReport, writeCostLedgerJsonl, COST_LEDGER_SCOPE, deriveUsageCalibration, normalizeClaudeUsageModelKey, readUsageLimits, parseWeeklyResetAnchor, claimCheck, summarize, queryBookKnowledge, loadStorePatternsSync, patternRecordId, loadStoreRecords, recordToPattern, bundleSkills, brainHome, listBrain, bookKbPath, 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, scannableStubPath,
19
+ TRACE_RUNID_RE, WF_RUN_OWNER_HOST, preflight, runWorkflow, makeClaudePDispatcher, makeCodexExecDispatcher, NamedLockTimeoutError, NamedLockCompromisedError, POLICY_SOURCES, detectPolicyDrift, hasPolicyFence, TARGET_NAMES, buildParityMatrix, downgradeForStaleEvidence, findStaleTranscriptEvidence, TARGET_CAPABILITIES, TARGET_SHORT_LABELS, WORKFLOW_TEMPLATES_RETIRED_MESSAGE, parsePlan, isParseErrors, validatePlan, normalizePlan, planDigest, toTraceProjection, renderPlan, mergeRender, lint, lintExitCode, LOOP_BLOBS, parseTrace, assembleTimeline, runInvariants, deriveAttestation, stampAttestation, corroborate, NOT_WITNESSED, renderTimelineHtml, 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, deriveCostLedger, planLedgerBackfill, listCostLedgerRuns, resolveLedgerRunId, AMBIGUOUS, stampCheckpointLine, LEDGER_FILL_SOURCE, renderCostLedger, verifyCostLedgerReport, writeCostLedgerJsonl, COST_LEDGER_SCOPE, deriveUsageCalibration, normalizeClaudeUsageModelKey, readUsageLimits, parseWeeklyResetAnchor, claimCheck, summarize, BUNDLED_SLOP_REGISTRY_URL, DEFAULT_SLOP_CONFIG, parseSlopRegistry, slopLint, validateSlopLintConfig, queryBookKnowledge, loadStorePatternsSync, patternRecordId, loadStoreRecords, recordToPattern, bundleSkills, brainHome, listBrain, bookKbPath, 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, scannableStubPath,
20
20
  // guard-promotion (feature guard-promotion, scout idea #1)
21
- 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, classifyExecutionEvidence, pickAdversaryModel, CHALLENGE_QUESTIONS, loadOutcomes, renderOutcomes, statsForKey, selectAutoCost, recordProvisional, finalizeOutcome, harvestStageOutcomes, recommendModels, planFeed, GRADE_SUCCESS_FLOOR, COST_LADDER, splitScenarios, budgetPlan, selectWinner, proseScopeOk, renderProseDiff, readScenarioIds, DEFAULT_MAX_JUDGE_RUNS, collectDeliveryFacts, planDeliveryCheck, renderDeliveryBrief, classifyDelivery, isUsablePlaneResult, renderDeliveryReview, scanSkillsLayout, declaredPluginSurface, parseInitFacts, verifyRegistration, buildContentProbePrompt, classifyContentProbe, renderContentProbe, findNonRegistrableSkillDirs, assembleCompoundingReport, banditStats, narrowBanditReport, renderBanditHealth,
21
+ 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, classifyExecutionEvidence, pickAdversaryModel, CHALLENGE_QUESTIONS, loadOutcomes, renderOutcomes, statsForKey, selectAutoCost, recordProvisional, finalizeOutcome, harvestStageOutcomes, recommendModels, planFeed, GRADE_SUCCESS_FLOOR, COST_LADDER, splitScenarios, budgetPlan, selectWinner, proseScopeOk, renderProseDiff, readScenarioIds, DEFAULT_MAX_JUDGE_RUNS, collectDeliveryFacts, planDeliveryCheck, renderDeliveryBrief, classifyDelivery, isUsablePlaneResult, renderDeliveryReview, scanSkillsLayout, declaredPluginSurface, parseInitFacts, verifyRegistration, buildContentProbePrompt, classifyContentProbe, renderContentProbe, findNonRegistrableSkillDirs, assembleCompoundingReport, buildDeadwoodReport, compactCmdUsageIfNeeded, measureCmdUsageDepthDays, recordCommandInvocation, resolveCmdUsageRoot, renderDeadwoodReport, CMD_USAGE_LOG_RELATIVE, banditStats, narrowBanditReport, renderBanditHealth,
22
22
  // Cold-vs-warm EPOCH RUNNER (feature epoch-replay) — orchestrates + scores, never calls a model.
23
23
  replayableInstances, buildWorkOrder, buildJudgePrompts, unblindJudgments, verifyWorkOrder, isValidMargin, DIGEST_HONEST_SCOPE, scoreEpochReplay, generateMockOutcomes, renderEpochReplayResult, renderWorkOrderSummary, renderJudgePromptsSummary, WORK_ORDER_KIND, DEFAULT_MOCK_N, DEFAULT_MOCK_SEED, scoreRun, readQeGrade, recapWindow, decideHorizon, withinWindow, buildRecap, renderRecap, parseSourceManifest, tgPostHtmlIssues, tgVisibleLength, decideTgSend, TG_TEXT_LIMIT, countRecallEventsForRun, unknownFlagNotice, mirrorWriterExplanation, appendRecallUsage, closenessLine, anyAboveFloor, decideNameCheck, renderNameCheck, exportedNamesIn, dispatchedCommandsIn, decideSourceProvenance, renderSourceProvenance, REFUSED_HORIZONS, renderScorecard, renderCompoundingReport, readReinforcementState, readQuarantineState, registrationExitCode, renderRegistrationReport,
24
24
  // Smart Backlog (feature smart-backlog) — goal-directed idea pipeline over the Brain vector engine.
@@ -26,11 +26,28 @@ readBacklogConfig, readIdeas, writeIdeas, ideaId, dedupIdea, readGoalMap, readGo
26
26
  // qe-bridge (feature qe-bridge-claude, ADR-001): the pure half of the reverse QE bridge.
27
27
  KNOWN_CLAUDE, isSafeClaudeId, claudeProbeArgs, claudeReviewArgs, interpretClaudeProbe, modelFamily, buildBridgePrompt, parseBridgeOutput, buildBridgeFailureRecord, buildBridgeSignoffRecord, renderBridgeReport, isSafeSlug, hasUnsafePathChars, hasDotDotSegment, buildReqeBrief, settleReqeDebt, renderReqeList, REQE_SCOPE,
28
28
  // Mutation gate (feature ha-mutation-gate) — break each named protection, run the suite, require red.
29
- parseMutationRegistry, applyMutationToText, countFailingTests, detectSuiteCompletionReceipt, detectSuiteReceiptMismatch, classifyBaseline, classifyRunFailure, classifyMutationOutcome, mutationGateExitCode, summarizeMutationResults, renderMutationReport, TRACE_BUNDLE_LEDGER_PATH, TRACE_BUNDLE_SCHEMA, TRACE_BUNDLE_RUN_META_FILE, buildBundle, serializeBundle, parseBundle, planImport, decideCheckpointWrite, amendmentSection, planSaysNoAmendments, parseAmendments, resolveAmendments, decideAmendmentOutcome, amendmentVerdictLine, amendmentsMissingFromPlan, AMENDMENT_VACUITY_NOTE, decideSignableSet, signableSetLine, decideRecordWrite, decideReadBack, recordVerdictLine, buildCadenceReport, tgVisibleSha256, CADENCE_WINDOW_DAYS, readQeRounds, QE_ROUNDS_DEFAULT_CEILING, describeStoreLocation, storeLocationLine, resolveTeachTarget, teachReasonPhrase, readTeachToConfig, TeachTargetError, mergeStoreHits, sameStore, globalStoreRoot, storeCountLabel,
29
+ parseMutationRegistry, applyMutationToText, countFailingTests, detectSuiteCompletionReceipt, detectSuiteReceiptMismatch, classifyBaseline, classifyRunFailure, classifyMutationOutcome, mutationGateExitCode, summarizeMutationResults, renderMutationReport, TRACE_BUNDLE_LEDGER_PATH, TRACE_BUNDLE_SCHEMA, TRACE_BUNDLE_RUN_META_FILE, buildBundle, serializeBundle, parseBundle, planImport, decideCheckpointWrite, amendmentSection, planSaysNoAmendments, parseAmendments, resolveAmendments, decideAmendmentOutcome, amendmentVerdictLine, amendmentsMissingFromPlan, AMENDMENT_VACUITY_NOTE, extractContractChecklist, parseContractVerdictReport, verifyContractVerdicts, decideSignableSet, signableSetLine, decideRecordWrite, decideReadBack, recordVerdictLine, buildCadenceReport, tgVisibleSha256, CADENCE_WINDOW_DAYS, readQeRounds, QE_ROUNDS_DEFAULT_CEILING, adviseRestart, describeStoreLocation, storeLocationLine, resolveTeachTarget, teachReasonPhrase, readTeachToConfig, TeachTargetError, mergeStoreHits, sameStore, globalStoreRoot, storeCountLabel,
30
30
  // operator-profile (ADR-001): per-user 0600 store + marked block in ~/.claude/CLAUDE.md
31
31
  renderProfileBlock, readProfile, writeProfile, syncProfileBlock, checkProfileDrift, parseRegister, registerOwnerWord, profileAgeDays, parseDomainList, domainListText, parseYesNo, REGISTERS, } from '@dzhechkov/harness-core';
32
32
  import { getPreset, PRESET_NAMES } from '@dzhechkov/harness-presets';
33
33
  import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, ScoutMemory } from '@dzhechkov/scout';
34
+ /** Literal command inventory, pinned against the main dispatch switch by a layer-1 test. */
35
+ export const DZ_COMMANDS = [
36
+ 'init', 'verify', 'sync', 'update', 'list', 'create-skill', 'info', 'scout',
37
+ 'workflow', 'workflow-lint', 'workflow-trace', 'migrate', 'doctor', 'install',
38
+ 'bundle', 'teach', 'consolidate', 'recall', 'vector', 'brain', 'statusline',
39
+ 'usage', 'claim-check', 'lint', 'sign', 'sbom', 'guard', 'verify-pack', 'setup',
40
+ 'pretrain', 'compose', 'diff', 'recommend', 'upgrade', 'auto-canonicalize',
41
+ 'publish', 'release', 'parity', 'registry', 'benchmark', 'mcp-scan',
42
+ 'sync-upstream', 'drift-check', 'hooks-sync', 'agents-sync', 'sync-canonical',
43
+ 'plugin', 'downloads', 'stats', 'architecture', 'project-skills', 'mr-rakes',
44
+ 'retro', 'feature-adr-setup', 'challenge', 'discrimination-check',
45
+ 'mutation-gate', 'delivery-check', 'skills-verify', 'compounding', 'deadwood',
46
+ 'epoch-replay', 'score', 'recap', 'cadence', 'qe-rounds', 'restart-advisor', 'tg-post',
47
+ 'name-check', 'provenance-check', 'feature-adr-record', 'amendment-check', 'contract-check',
48
+ 'feature-adr-checkpoint', 'profile', 'reqe', 'qe-bridge', 'backlog', 'routing',
49
+ 'bto-optimize', 'dashboard', 'roam', 'import-ecc',
50
+ ];
34
51
  const USAGE = `dz - DZ cross-platform harness CLI
35
52
 
36
53
  Usage:
@@ -64,6 +81,7 @@ Usage:
64
81
  dz challenge --plan <plan.md> [--author <model>] (the deterministic cartridge behind the challenge-panel adversarial plan-gate (R6): assembles the wide brief — plan + architecture/vision.md + testing.md + map.json + degradations.md — and prints the C1-C8 adversary prompt naming the cross-family reviewer to dispatch. exit 0 brief printed / 1 plan missing or empty)
65
82
  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)
66
83
  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)
84
+ dz deadwood [--weeks <n>] [--json] (advisory zero-usage candidates for human deprecation review; safety-excluded surfaces carry reasons; never deletes or deprecates anything; shallow history says INSUFFICIENT_DATA)
67
85
  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)
68
86
  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)
69
87
  dz epoch-replay --judge <filled-work-order.json> [--out <file>] (blind judge prompts from the filled plans)
@@ -72,6 +90,7 @@ Usage:
72
90
  dz recap [--day|--week|--month] [--at <ISO date>] [--project <dir>] [--json] (what was done over a window, from records only: deliveries with the grade an independent review STATED — a report naming two grades is reported ambiguous, never guessed — registry publishes, gate verdicts, knowledge reuse. --quarter/--half-year/--year are RECOGNISED and REFUSED with the real span in days: there is one complete quarter and the longest record is 174 days. Every section carries its own data-start date, and "the source was not read" never prints as zero. Contaminated measures — commit count, lines, tokens, learning-event volume, inventory counts, lesson count — are not computed, and the report says so. exit 0 reported / 2 refused)
73
91
  dz cadence [--window day|week|month|quarter|halfyear|year] [--json] (the WHAT-SHIPPED aggregator: graded-shipment cadence by ISO week + npm-publish cadence (recap cache) + guard repeat decay on the FIXED rule set + recall reuse; a window deeper than 2× the record is REFUSED with the depth named (ADR: a cadence from one point is scale forgery); exit 0 report / 2 refused-window / 1 usage)
74
92
  dz qe-rounds (--slug <feature> | --feature-dir <abs>) [--ceiling <n>] [--project <dir>] [--json] (how many Step-8 review rounds has this feature ALREADY had? Reads what dz qe-bridge already wrote — signoff-<runId>.json and failed-*.json under features/<slug>/.fa-state/qe-bridge — and writes nothing itself, so it can answer for runs already past. A round is a runId, not a file; an attempt with no verdict is counted SEPARATELY and never merged; an unreadable record is NAMED and the count is declared a LOWER BOUND. ONE directory, never a union across checkouts. exit 0 under the ceiling / 1 at-or-over — owner decides, the command does not judge whether the rounds were warranted / 2 NOT ESTABLISHED, which is never "zero rounds")
93
+ dz restart-advisor --slug <s> [--threshold C|D] [--rounds N] [--json] (read-only advisory decision over features/<slug>/.fa-state/checkpoints.jsonl and .dz/fa-training/<slug>/qe.jsonl. Defaults: threshold D, rounds 2 — both origins are printed. Equal sources corroborate; conflicts, torn/unreadable evidence, gaps, and unsafe paths are NOT ESTABLISHED. RECOMMENDATION ONLY: autoAction=false; never invokes feature-adr, deletes a stage, or writes advisor state. exit 0 established recommendation/no-recommendation / 2 NOT ESTABLISHED or invalid input / 1 unexpected runtime failure)
75
94
  dz tg-post --draft <file.html> [--manifest <sources.json>] [--channel <@name|id>] [--send --yes] [--night] [--preview] [--json] (the sender for an APPROVED channel post, per the accepted genai-tweets-channel ADRs: HTML mode only — never MarkdownV2; link preview OFF by default (x.com previews in Telegram are broken); the 00:00-06:00 MSK quiet window refuses without an explicit --night. DEFAULT IS A DRY-RUN: it validates the draft (tag balance, allowed tags, bare &/<, the 4096 visible-character limit with the overshoot counted) and runs the provenance gate over --manifest IN-PROCESS — a draft with no manifest is refused as unchecked, and anything but ALLOWED refuses. A real send needs --send --yes, stating ADR-004's manual-publishing decision out loud each time. The token comes from TELEGRAM_BOT_TOKEN or telegram.tokenFile in .dz/config.json and is never printed. exit 0 sent or clean dry-run / 1 refused or Telegram error / 2 usage)
76
95
  dz name-check [--command <n>] [--module <basename>] [--export <a,b>] [--project <dir>] [--json] (is this name free, BEFORE a line of code? Scans workspace SOURCE — never dist, because a stale build answers 'free' confidently. Checks a dz command name against the dispatcher AND the help block, a module basename against every package's src/, and exported identifiers against every declaration in the workspace. exit 0 all free / 1 at least one taken, naming where / 2 nothing asked or the scan did not run — an empty sweep is never a clean bill. Honest limit, printed on the passing path: it reads declarations, so a re-export under a different name stays the build's job)
77
96
  dz provenance-check --manifest <sources.json> [--project <dir>] [--json] (nothing goes out citing a source that may not leave this machine. Checks PROVENANCE, not words: every claim names its source, and only a KNOWN kind that resolves safely is cleared. Repo paths go through 'git -C <root> check-ignore' over the RESOLVED path — a symlink into an ignored directory is REFUSED (git classifies the string and never dereferences, MEASURED), and the verdict does not change with your working directory. Store records must be named in the git-TRACKED provenance-public.json, so declaring one public is a reviewable commit rather than a field inside an ignored store. An undeclared kind is refused, never inferred from the path's shape. exit 0 allowed / 1 blocked / 3 NOT ESTABLISHED — an empty manifest, an unreadable one, or an oracle that did not run is never a pass. It proves what was CITED: it cannot see a paraphrase with no citation, nor confidential text pasted by hand into an allowed file)
@@ -81,6 +100,7 @@ Usage:
81
100
  dz architecture [--check --slug <s> --desc <text>] [--project <dir>] [--revise] (the live product map + vision: --check is the soft Step-0 сверка of a new feature against them, reporting {signal,confidence} rather than blocking)
82
101
  dz sbom [--pack <name>] [--out <file>] (CycloneDX software bill of materials for the workspace, or for one pack with --pack)
83
102
  dz amendment-check --slug <slug> | --feature-dir <dir> | --all [--json] (the deterministic Step-8 amendment gate: every AM-N row must resolve to a test found INSIDE the file the row names; the PLAN is authoritative when it carries rows, and an ideation amendment the plan drops is a failure. exit 0 pass/skip, 1 fail, 3 NOT-ESTABLISHED — a section that parsed ZERO rows is never a pass. --all is a CENSUS and always exits 0. Does NOT prove non-vacuity — that is dz discrimination-check)
103
+ dz contract-check --slug <s> [--json] (read-only retrospective feature contract gate: extracts canonical AC-N + ADR Confirmation items, requires one artifact-anchored met|unmet|not-testable verdict per CC-N, and rejects A/B with unmet. exit 0 pass / 1 readable contract or verdict violation / 2 invalid invocation or unreadable/not-established artifacts)
84
104
  dz feature-adr-record --kind ledger|training-pair --stage <s> [--slug <s>] [--row|--pair <json>] [--mark <n>] [--once] [--json] (the witnessed writer for the run-cost ledger and training pairs: the payload arrives as an ARGUMENT, never as shell; a malformed or wrong-kind payload is REFUSED before any write; the timestamp is stamped before serialising; the append is verified by re-reading the tail. exit 0 written|duplicate|skipped, 2 refused, 3 not-verified — a record failure is never blocking)
85
105
  dz feature-adr-checkpoint (--slug <feature> | --feature-dir <abs>) --stage <s> --input-hash <h> --result <json> [--artifact a,b] [--json] (record a pipeline stage ONLY after measuring its artifacts on disk; refuses a null result, an absent artifact, or a stage that declares none — the subagent runs a COMMAND instead of hand-writing durable state)
86
106
  dz profile [init|show|set|sync] [--json] (WHO the assistant is talking to — per-user store at ~/.dz/profile.json (0600, NEVER in a project), delivered as a marked block in ~/.claude/CLAUDE.md so it loads in EVERY project, dz installed or not. init = five questions (language, register, deep/weak domains as comma lists — "networking (CCIE; NSX)" keeps the parenthetical as the note, Enter skips — teaches y/n with one re-ask, never a silent default); show ALWAYS prints the store path + age + drift verdict + the rendered block; set register|language|teaches <v> or set deep|weak add|rm <tag> [note] — register accepts the owner's own words (профи / профи лайт / просто), an unknown value is REFUSED naming the accepted set; sync re-writes the block (runs automatically after init/set; foreign content byte-for-byte, timestamped backup before every modifying write). The register changes FORM, never FACTS, and governs dialogue only — never ADRs/commits/QE reports; both rules are baked into the rendered block at every level. exit 0 done / 1 no profile or failed / 2 refused input)
@@ -125,6 +145,7 @@ Usage:
125
145
  dz usage [--json] [--project <dir>] | dz usage --calibrate --session <pct> --weekly <pct> [--model fable=<pct>] [--project <dir>] (ESTIMATE Claude usage from fixed reset windows; optional per-model weekly binding; exit 0 ALWAYS; pct=null when limits unconfigured)
126
146
  dz usage --by-stage [--run <runId> | --slug <slug>] [--epsilon <0..1>] [--write <file.jsonl>] [--json] (per-stage cost ledger for ONE feature-adr run + the reconciliation invariant: accounted + unaccounted = run total; verdict BALANCED | DEFECT | INSUFFICIENT_DATA; local transcript ESTIMATES — catches ATTRIBUTION errors, not pricing errors)
127
147
  dz claim-check [paths...] [--json] [--fail-on high|medium|none] [--project <dir>] (enforce the Integrity Rule: flag untagged/overstated accuracy claims; default scan = root README.md + every discovered package's README.md + features/*/08_qe_report.md + docs/**/*.md (historical feature artifacts are NOT scanned — pass paths explicitly); exit 1 only at/above --fail-on, default high)
148
+ dz lint [paths...] [--json] [--config <file>] [--registry <file>] [--project <dir>] (advisory EN/RU prose-style lint; findings exit 0, incomplete input/policy exits 1, usage exits 2)
128
149
  dz pretrain [--project <dir>]
129
150
  dz recommend "<task description>"
130
151
  dz compose <preset1+preset2+...> [--target <name>]
@@ -2178,6 +2199,111 @@ function cmdQeRounds(options, flags, cwd, write) {
2178
2199
  write(' under the ceiling — another round is within the documented budget');
2179
2200
  return 0;
2180
2201
  }
2202
+ /** Read one fixed advisor evidence path without following a symlink or escaping the project root. */
2203
+ function readRestartAdvisorEvidence(root, relativePath) {
2204
+ const contained = containedUnderRoot(root, relativePath);
2205
+ if (!contained.ok) {
2206
+ return { text: null, diagnostic: `${relativePath}: ${contained.why}` };
2207
+ }
2208
+ let stat;
2209
+ try {
2210
+ stat = lstatSync(contained.path);
2211
+ }
2212
+ catch (error) {
2213
+ if (error.code === 'ENOENT')
2214
+ return { text: null, diagnostic: null };
2215
+ return { text: null, diagnostic: `${relativePath}: evidence cannot be inspected (${error.message})` };
2216
+ }
2217
+ if (stat.isSymbolicLink()) {
2218
+ return { text: null, diagnostic: `${relativePath}: symlink evidence is refused` };
2219
+ }
2220
+ if (!stat.isFile()) {
2221
+ return { text: null, diagnostic: `${relativePath}: evidence exists but is not a regular file` };
2222
+ }
2223
+ try {
2224
+ return { text: readFileSync(contained.path, 'utf-8'), diagnostic: null };
2225
+ }
2226
+ catch (error) {
2227
+ return { text: null, diagnostic: `${relativePath}: evidence cannot be read (${error.message})` };
2228
+ }
2229
+ }
2230
+ /** Manual restart recommendation only. I/O ends here; the core remains deterministic and pure. */
2231
+ function cmdRestartAdvisor(options, flags, cwd, write) {
2232
+ const json = flags.has('json');
2233
+ const rawSlug = options.get('slug') ?? '';
2234
+ const slug = rawSlug.trim();
2235
+ const thresholdRaw = options.get('threshold');
2236
+ const roundsRaw = options.get('rounds');
2237
+ const thresholdOrigin = thresholdRaw === undefined ? 'default' : 'flag';
2238
+ const roundsOrigin = roundsRaw === undefined ? 'default' : 'flag';
2239
+ const emit = (advice) => {
2240
+ if (json) {
2241
+ write(JSON.stringify(advice));
2242
+ }
2243
+ else {
2244
+ write(`dz restart-advisor: ${advice.recommendation} — advisory only; autoAction=false`);
2245
+ write(` policy: threshold ${String(advice.policy.threshold)} (${advice.policy.thresholdOrigin}), rounds ${String(advice.policy.rounds)} (${advice.policy.roundsOrigin})`);
2246
+ write(` source: ${advice.sourcePath ?? 'none'}${advice.corroborated ? ' (corroborated by both stores)' : ''}`);
2247
+ for (const diagnostic of advice.diagnostics)
2248
+ write(` diagnostic: ${JSON.stringify(diagnostic)}`);
2249
+ if (advice.diagnosticsSummary.truncated) {
2250
+ write(` diagnostics: ${advice.diagnosticsSummary.returned}/${advice.diagnosticsSummary.total} shown`);
2251
+ }
2252
+ write(advice.decisionLogLine);
2253
+ }
2254
+ return advice.recommendation === 'RESTART_CODE_STAGE'
2255
+ || advice.recommendation === 'NO_RESTART_RECOMMENDATION'
2256
+ ? 0
2257
+ : 2;
2258
+ };
2259
+ const inputErrors = [];
2260
+ for (const flag of flags) {
2261
+ if (flag !== 'json' && flag !== 'help')
2262
+ inputErrors.push(`--${flag} requires a value or is not supported`);
2263
+ }
2264
+ for (const key of options.keys()) {
2265
+ if (key !== 'slug' && key !== 'threshold' && key !== 'rounds') {
2266
+ inputErrors.push(key.startsWith('_positional_')
2267
+ ? `unexpected argument ${JSON.stringify(options.get(key))}`
2268
+ : `unsupported option --${key}`);
2269
+ }
2270
+ }
2271
+ if (!isSafeSlug(slug)) {
2272
+ inputErrors.push(`--slug ${JSON.stringify(rawSlug)} must be one kebab-case path segment (max 40 characters)`);
2273
+ }
2274
+ const threshold = thresholdRaw ?? 'D';
2275
+ if (threshold !== 'C' && threshold !== 'D') {
2276
+ inputErrors.push(`--threshold ${JSON.stringify(thresholdRaw)} must be exactly C or D`);
2277
+ }
2278
+ const roundsValue = roundsRaw === undefined ? 2 : Number(roundsRaw);
2279
+ if (!Number.isFinite(roundsValue) || !Number.isInteger(roundsValue) || roundsValue < 1) {
2280
+ inputErrors.push(`--rounds ${JSON.stringify(roundsRaw)} must be a positive integer`);
2281
+ }
2282
+ if (inputErrors.length > 0) {
2283
+ return emit(adviseRestart({ slug, inputErrors }, {
2284
+ thresholdOrigin,
2285
+ roundsOrigin,
2286
+ }));
2287
+ }
2288
+ const root = resolve(cwd);
2289
+ const checkpointPath = `features/${slug}/.fa-state/checkpoints.jsonl`;
2290
+ const trainingPath = `.dz/fa-training/${slug}/qe.jsonl`;
2291
+ const checkpoints = readRestartAdvisorEvidence(root, checkpointPath);
2292
+ const trainingPairs = readRestartAdvisorEvidence(root, trainingPath);
2293
+ const readDiagnostics = [checkpoints.diagnostic, trainingPairs.diagnostic]
2294
+ .filter((entry) => entry !== null);
2295
+ return emit(adviseRestart({
2296
+ slug,
2297
+ checkpointsJsonl: checkpoints.text,
2298
+ trainingPairsJsonl: trainingPairs.text,
2299
+ readDiagnostics,
2300
+ }, {
2301
+ threshold: threshold,
2302
+ rounds: roundsValue,
2303
+ thresholdOrigin,
2304
+ roundsOrigin,
2305
+ }));
2306
+ }
2181
2307
  function cmdCadence(options, flags, cwd, write) {
2182
2308
  const root = resolve(cwd, options.get('project') ?? '.');
2183
2309
  const windowRaw = (options.get('window') ?? 'week').trim();
@@ -5918,6 +6044,253 @@ function cmdBenchmark(options, flags, cwd, write) {
5918
6044
  write(`\nL0 only. For L1/L2 judge evaluation: /bto-test ${skillDir}`);
5919
6045
  return score.passRate >= 80 ? 0 : 1;
5920
6046
  }
6047
+ const SLOP_MAX_FILE_BYTES = 2 * 1024 * 1024;
6048
+ const SLOP_COURSE_TEXT_KEYS = new Set([
6049
+ 'back', 'courseDescription', 'courseTitle', 'description', 'explanation', 'front', 'instruction',
6050
+ 'keyConcept', 'keyConcepts', 'note', 'options', 'question', 'reflection', 'shortTitle', 'strengths',
6051
+ 'theory', 'title', 'weaknesses', 'wrapup',
6052
+ ]);
6053
+ function slopDisplayPath(root, absolute) {
6054
+ const rel = relative(root, absolute);
6055
+ return rel !== '' && !rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel) ? rel : absolute;
6056
+ }
6057
+ function slopWalk(dir, depth = 0) {
6058
+ if (depth > 16)
6059
+ return [];
6060
+ const out = [];
6061
+ let entries;
6062
+ try {
6063
+ entries = readdirSync(dir, { withFileTypes: true });
6064
+ }
6065
+ catch {
6066
+ return out;
6067
+ }
6068
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
6069
+ for (const entry of entries) {
6070
+ if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'build')
6071
+ continue;
6072
+ if (entry.isSymbolicLink())
6073
+ continue;
6074
+ const full = join(dir, entry.name);
6075
+ if (entry.isDirectory())
6076
+ out.push(...slopWalk(full, depth + 1));
6077
+ else if (entry.isFile() && (['.md', '.mdx'].includes(extname(entry.name).toLowerCase()) || entry.name === 'course.json'))
6078
+ out.push(full);
6079
+ }
6080
+ return out;
6081
+ }
6082
+ function defaultSlopScanSet(root) {
6083
+ const paths = [];
6084
+ const readme = join(root, 'README.md');
6085
+ if (existsSync(readme))
6086
+ paths.push(readme);
6087
+ try {
6088
+ for (const pkg of discoverPackages(root)) {
6089
+ const packageReadme = join(pkg.dir, 'README.md');
6090
+ if (existsSync(packageReadme))
6091
+ paths.push(packageReadme);
6092
+ }
6093
+ }
6094
+ catch { /* a foreign project need not be a dz workspace */ }
6095
+ paths.push(...slopWalk(join(root, 'packages', '@dzhechkov', 'sitedoc', 'src', 'content'))
6096
+ .filter((path) => ['.md', '.mdx'].includes(extname(path).toLowerCase())));
6097
+ try {
6098
+ const featureDir = join(root, 'features');
6099
+ for (const entry of readdirSync(featureDir, { withFileTypes: true })) {
6100
+ if (!entry.isDirectory() || entry.isSymbolicLink())
6101
+ continue;
6102
+ const course = join(featureDir, entry.name, 'course.json');
6103
+ if (existsSync(course))
6104
+ paths.push(course);
6105
+ }
6106
+ }
6107
+ catch { /* no features directory */ }
6108
+ return [...new Set(paths.map((path) => resolve(path)))].sort((a, b) => {
6109
+ const left = slopDisplayPath(root, a);
6110
+ const right = slopDisplayPath(root, b);
6111
+ return left < right ? -1 : left > right ? 1 : 0;
6112
+ });
6113
+ }
6114
+ function decodeSlopUtf8(path) {
6115
+ const stat = lstatSync(path);
6116
+ if (!stat.isFile())
6117
+ throw new Error('not a regular file');
6118
+ if (stat.size > SLOP_MAX_FILE_BYTES)
6119
+ throw new Error(`file exceeds ${SLOP_MAX_FILE_BYTES} byte limit`);
6120
+ const bytes = readFileSync(path);
6121
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
6122
+ }
6123
+ function projectCourseJson(text) {
6124
+ let value;
6125
+ try {
6126
+ value = JSON.parse(text);
6127
+ }
6128
+ catch {
6129
+ return null;
6130
+ }
6131
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
6132
+ return null;
6133
+ const root = value;
6134
+ if (typeof root.language !== 'string' || typeof root.courseTitle !== 'string' ||
6135
+ !Array.isArray(root.topics) || !Array.isArray(root.sections))
6136
+ return null;
6137
+ const output = [];
6138
+ const visit = (current, key = '') => {
6139
+ if (typeof current === 'string') {
6140
+ if (SLOP_COURSE_TEXT_KEYS.has(key) && current.trim() !== '')
6141
+ output.push(current);
6142
+ return;
6143
+ }
6144
+ if (Array.isArray(current)) {
6145
+ for (const item of current)
6146
+ visit(item, key);
6147
+ return;
6148
+ }
6149
+ if (current === null || typeof current !== 'object')
6150
+ return;
6151
+ for (const [childKey, child] of Object.entries(current))
6152
+ visit(child, childKey);
6153
+ };
6154
+ visit(root);
6155
+ return output.join('\n\n');
6156
+ }
6157
+ function slopLoadJson(path, validate) {
6158
+ const decoded = decodeSlopUtf8(path);
6159
+ let parsed;
6160
+ try {
6161
+ parsed = JSON.parse(decoded);
6162
+ }
6163
+ catch (error) {
6164
+ throw new Error(`invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
6165
+ }
6166
+ const result = validate(parsed);
6167
+ if (!result.ok)
6168
+ throw new Error(result.errors.map((error) => `${error.field}=${JSON.stringify(error.value)}: ${error.reason}`).join('; '));
6169
+ return result.value;
6170
+ }
6171
+ /**
6172
+ * Read-only adapter over the pure slopLint core. Style findings are advisory by construction:
6173
+ * only usage errors return 2 and incomplete policy/input evidence returns 1.
6174
+ */
6175
+ function cmdLint(options, flags, cwd, write) {
6176
+ const json = flags.has('json');
6177
+ const root = resolve(cwd, options.get('project') ?? '.');
6178
+ const usageError = (message) => {
6179
+ if (json)
6180
+ write(JSON.stringify({ schema: 'dz-slop-lint/1', advisory: true, ok: false, status: 'incomplete', findings: [], scanned: [], skipped: [], errors: [{ message }] }));
6181
+ else
6182
+ write(`dz lint: ${message}`);
6183
+ return 2;
6184
+ };
6185
+ if (flags.has('config'))
6186
+ return usageError('--config requires a file');
6187
+ if (flags.has('registry'))
6188
+ return usageError('--registry requires a file');
6189
+ let config = DEFAULT_SLOP_CONFIG;
6190
+ let registry;
6191
+ const setupErrors = [];
6192
+ try {
6193
+ if (options.has('config'))
6194
+ config = slopLoadJson(resolve(root, options.get('config')), validateSlopLintConfig);
6195
+ }
6196
+ catch (error) {
6197
+ const path = options.get('config');
6198
+ setupErrors.push({ ...(path === undefined ? {} : { path }), message: `config: ${error instanceof Error ? error.message : String(error)}` });
6199
+ }
6200
+ try {
6201
+ const registryPath = options.has('registry') ? resolve(root, options.get('registry')) : fileURLToPath(BUNDLED_SLOP_REGISTRY_URL);
6202
+ registry = slopLoadJson(registryPath, parseSlopRegistry);
6203
+ }
6204
+ catch (error) {
6205
+ const path = options.get('registry');
6206
+ setupErrors.push({ ...(path === undefined ? {} : { path }), message: `registry: ${error instanceof Error ? error.message : String(error)}` });
6207
+ registry = { schema: 'dz-slop-registry/1', metadata: {}, markers: [], adjectives: [] };
6208
+ }
6209
+ const requested = [];
6210
+ for (let index = 0;; index += 1) {
6211
+ const value = options.get(`_positional_${index}`);
6212
+ if (value === undefined)
6213
+ break;
6214
+ requested.push(resolve(root, value));
6215
+ }
6216
+ const explicit = requested.length > 0;
6217
+ const candidates = explicit ? requested.flatMap((path) => {
6218
+ try {
6219
+ const stat = lstatSync(path);
6220
+ if (stat.isSymbolicLink())
6221
+ return [path];
6222
+ return stat.isDirectory() ? slopWalk(path) : [path];
6223
+ }
6224
+ catch {
6225
+ return [path];
6226
+ }
6227
+ }) : defaultSlopScanSet(root);
6228
+ const scanSet = [...new Set(candidates.map((path) => resolve(path)))].sort((a, b) => {
6229
+ const left = slopDisplayPath(root, a);
6230
+ const right = slopDisplayPath(root, b);
6231
+ return left < right ? -1 : left > right ? 1 : 0;
6232
+ });
6233
+ const findings = [];
6234
+ const scanned = [];
6235
+ const errors = [...setupErrors];
6236
+ if (setupErrors.length === 0) {
6237
+ for (const path of scanSet) {
6238
+ const display = slopDisplayPath(root, path);
6239
+ let source;
6240
+ try {
6241
+ source = decodeSlopUtf8(path);
6242
+ }
6243
+ catch (error) {
6244
+ const message = error instanceof TypeError ? `invalid UTF-8: ${error.message}` : error instanceof Error ? error.message : String(error);
6245
+ scanned.push({ path: display, status: 'skipped', reason: message });
6246
+ errors.push({ path: display, message });
6247
+ continue;
6248
+ }
6249
+ if (basename(path) === 'course.json') {
6250
+ const projected = projectCourseJson(source);
6251
+ if (projected === null) {
6252
+ const message = 'unsupported course.json shape';
6253
+ scanned.push({ path: display, status: 'skipped', reason: message });
6254
+ if (explicit)
6255
+ errors.push({ path: display, message });
6256
+ continue;
6257
+ }
6258
+ source = projected;
6259
+ }
6260
+ else if (!['.md', '.mdx'].includes(extname(path).toLowerCase())) {
6261
+ const message = 'unsupported input type; expected Markdown, MDX, or recognized course.json';
6262
+ scanned.push({ path: display, status: 'skipped', reason: message });
6263
+ errors.push({ path: display, message });
6264
+ continue;
6265
+ }
6266
+ const result = slopLint(source, { config, registry });
6267
+ if (result.paragraphCount === 0)
6268
+ errors.push({ path: display, message: 'no analyzable prose' });
6269
+ for (const diagnostic of result.diagnostics)
6270
+ errors.push({ path: display, message: `${diagnostic.code} at line ${diagnostic.line}: ${diagnostic.message}` });
6271
+ for (const finding of result.findings)
6272
+ findings.push({ ...finding, file: display });
6273
+ scanned.push({ path: display, status: 'scanned', paragraphs: result.paragraphCount, findings: result.findings.length });
6274
+ }
6275
+ }
6276
+ // A valid empty directory/default scope is a clean advisory no-op. Explicit missing paths stay
6277
+ // in scanSet and fail above, while a supported file containing no prose remains incomplete.
6278
+ const skipped = scanned.filter((row) => row.status === 'skipped');
6279
+ const status = errors.length > 0 ? 'incomplete' : findings.length > 0 ? 'findings' : 'clean';
6280
+ const report = {
6281
+ schema: 'dz-slop-lint/1', advisory: true, ok: errors.length === 0, status, findings, scanned, skipped, errors,
6282
+ };
6283
+ if (json)
6284
+ write(JSON.stringify(report));
6285
+ else {
6286
+ write(`dz lint: ${findings.length} finding(s), ${scanned.filter((row) => row.status === 'scanned').length} file(s) scanned — ${status}`);
6287
+ for (const finding of findings)
6288
+ write(` [${finding.ruleId}] ${finding.file}:${finding.lineStart}:${finding.columnStart} — ${finding.excerpt}`);
6289
+ for (const error of errors)
6290
+ write(` incomplete${error.path ? ` ${error.path}` : ''}: ${error.message}`);
6291
+ }
6292
+ return errors.length > 0 ? 1 : 0;
6293
+ }
5921
6294
  /**
5922
6295
  * Exit-code contract for `dz claim-check` (named in the ADR, locked by tests):
5923
6296
  * exit 0 when no finding at/above `failOn` exists; exit 1 only when one does.
@@ -10843,6 +11216,262 @@ function cmdFeatureAdrRecord(options, flags, cwd, write) {
10843
11216
  }
10844
11217
  return emit(decideReadBack(lineToWrite, lastLine), { target });
10845
11218
  }
11219
+ function contractRepoRoot(cwd) {
11220
+ let root = cwd;
11221
+ try {
11222
+ root = execSync('git rev-parse --show-toplevel', {
11223
+ cwd,
11224
+ encoding: 'utf-8',
11225
+ stdio: ['ignore', 'pipe', 'ignore'],
11226
+ }).trim() || cwd;
11227
+ }
11228
+ catch { /* temporary repository fixtures intentionally use cwd as their root */ }
11229
+ return resolve(root);
11230
+ }
11231
+ function contractReadConfined(repoRoot, absolute, artifact) {
11232
+ let rootReal;
11233
+ let targetReal;
11234
+ try {
11235
+ rootReal = realpathSync(repoRoot);
11236
+ }
11237
+ catch {
11238
+ return {
11239
+ ok: false,
11240
+ diagnostic: { code: 'repository-unreadable', message: 'repository root cannot be resolved', artifact: '.' },
11241
+ };
11242
+ }
11243
+ try {
11244
+ targetReal = realpathSync(absolute);
11245
+ }
11246
+ catch {
11247
+ return {
11248
+ ok: false,
11249
+ diagnostic: { code: 'artifact-unreadable', message: `required artifact cannot be resolved or read: ${artifact}`, artifact },
11250
+ };
11251
+ }
11252
+ const rel = relative(rootReal, targetReal);
11253
+ if (rel === '' || rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel)) {
11254
+ return {
11255
+ ok: false,
11256
+ diagnostic: { code: 'artifact-outside-repository', message: `artifact resolves outside the repository: ${artifact}`, artifact },
11257
+ };
11258
+ }
11259
+ try {
11260
+ if (!statSync(targetReal).isFile())
11261
+ throw new Error('not a regular file');
11262
+ return { ok: true, text: readFileSync(targetReal, 'utf-8'), realPath: targetReal };
11263
+ }
11264
+ catch {
11265
+ return {
11266
+ ok: false,
11267
+ diagnostic: { code: 'artifact-unreadable', message: `required artifact cannot be read as a file: ${artifact}`, artifact },
11268
+ };
11269
+ }
11270
+ }
11271
+ function contractDirectoryConfined(repoRoot, absolute, artifact) {
11272
+ let rootReal;
11273
+ let targetReal;
11274
+ try {
11275
+ rootReal = realpathSync(repoRoot);
11276
+ }
11277
+ catch {
11278
+ return {
11279
+ ok: false,
11280
+ diagnostic: { code: 'repository-unreadable', message: 'repository root cannot be resolved', artifact: '.' },
11281
+ };
11282
+ }
11283
+ try {
11284
+ targetReal = realpathSync(absolute);
11285
+ }
11286
+ catch {
11287
+ return {
11288
+ ok: false,
11289
+ diagnostic: { code: 'adr-directory-unreadable', message: `required ADR directory cannot be resolved: ${artifact}`, artifact },
11290
+ };
11291
+ }
11292
+ const rel = relative(rootReal, targetReal);
11293
+ if (rel === '' || rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel)) {
11294
+ return {
11295
+ ok: false,
11296
+ diagnostic: { code: 'artifact-outside-repository', message: `artifact resolves outside the repository: ${artifact}`, artifact },
11297
+ };
11298
+ }
11299
+ try {
11300
+ if (!statSync(targetReal).isDirectory())
11301
+ throw new Error('not a directory');
11302
+ return { ok: true, realPath: targetReal };
11303
+ }
11304
+ catch {
11305
+ return {
11306
+ ok: false,
11307
+ diagnostic: { code: 'adr-directory-unreadable', message: `required ADR directory is not readable: ${artifact}`, artifact },
11308
+ };
11309
+ }
11310
+ }
11311
+ function contractDiagnosticLine(entry) {
11312
+ const where = [entry.artifact, entry.contractId ?? entry.sourceId].filter((part) => part !== undefined).join(' · ');
11313
+ return ` [${entry.code}]${where === '' ? '' : ` ${where} —`} ${entry.message}`;
11314
+ }
11315
+ function cmdContractCheck(options, flags, cwd, write, writeErr) {
11316
+ const json = flags.has('json');
11317
+ const emitEarly = (outcome, exitCode, diagnostics) => {
11318
+ if (json) {
11319
+ write(JSON.stringify({ outcome, exitCode, diagnostics }));
11320
+ }
11321
+ else {
11322
+ for (const entry of diagnostics)
11323
+ writeErr(contractDiagnosticLine(entry));
11324
+ write(`contract-check: ${outcome === 'fail' ? 'FAIL' : 'NOT-ESTABLISHED'} — ${diagnostics[0]?.message ?? 'no trustworthy verdict'}`);
11325
+ }
11326
+ return exitCode;
11327
+ };
11328
+ for (const flag of flags) {
11329
+ if (flag !== 'json' && flag !== 'help') {
11330
+ return emitEarly('not-established', 2, [{ code: 'usage-invalid', message: `unknown option --${flag}`, observed: `--${flag}` }]);
11331
+ }
11332
+ }
11333
+ for (const key of options.keys()) {
11334
+ if (key !== 'slug') {
11335
+ return emitEarly('not-established', 2, [{
11336
+ code: 'usage-invalid',
11337
+ message: key.startsWith('_positional_') ? `unexpected argument ${JSON.stringify(options.get(key))}` : `unknown option --${key}`,
11338
+ observed: key.startsWith('_positional_') ? options.get(key) ?? '' : `--${key}`,
11339
+ }]);
11340
+ }
11341
+ }
11342
+ const slug = (options.get('slug') ?? '').trim();
11343
+ if (!isSafeSlug(slug)) {
11344
+ return emitEarly('not-established', 2, [{
11345
+ code: 'slug-invalid',
11346
+ message: 'a kebab-case --slug <feature> is required (one path segment, max 40 characters)',
11347
+ observed: slug,
11348
+ }]);
11349
+ }
11350
+ const repoRoot = contractRepoRoot(cwd);
11351
+ const featureDir = join(repoRoot, 'features', slug);
11352
+ const requirementsRel = `features/${slug}/01_requirements.md`;
11353
+ const reportRel = `features/${slug}/08_qe_report.md`;
11354
+ const requirementsRead = contractReadConfined(repoRoot, join(featureDir, '01_requirements.md'), requirementsRel);
11355
+ if (!requirementsRead.ok)
11356
+ return emitEarly('not-established', 2, [requirementsRead.diagnostic]);
11357
+ const adrDirRel = `features/${slug}/03_adr`;
11358
+ const adrDirectory = contractDirectoryConfined(repoRoot, join(featureDir, '03_adr'), adrDirRel);
11359
+ if (!adrDirectory.ok)
11360
+ return emitEarly('not-established', 2, [adrDirectory.diagnostic]);
11361
+ const adrDir = adrDirectory.realPath;
11362
+ let adrNames;
11363
+ try {
11364
+ adrNames = readdirSync(adrDir, { withFileTypes: true })
11365
+ .filter((entry) => entry.name.endsWith('.md') && (entry.isFile() || entry.isSymbolicLink()))
11366
+ .map((entry) => entry.name)
11367
+ .sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
11368
+ }
11369
+ catch {
11370
+ return emitEarly('not-established', 2, [{
11371
+ code: 'adr-directory-unreadable',
11372
+ message: `required ADR directory cannot be read: ${adrDirRel}`,
11373
+ artifact: adrDirRel,
11374
+ }]);
11375
+ }
11376
+ if (adrNames.length === 0) {
11377
+ return emitEarly('not-established', 2, [{
11378
+ code: 'adr-artifacts-missing',
11379
+ message: `no direct ADR Markdown artifacts exist under ${adrDirRel}`,
11380
+ artifact: adrDirRel,
11381
+ observed: 0,
11382
+ }]);
11383
+ }
11384
+ const adrs = [];
11385
+ const adrReadErrors = [];
11386
+ for (const name of adrNames) {
11387
+ const rel = `features/${slug}/03_adr/${name}`;
11388
+ const read = contractReadConfined(repoRoot, join(adrDir, name), rel);
11389
+ if (read.ok)
11390
+ adrs.push({ path: rel, text: read.text });
11391
+ else
11392
+ adrReadErrors.push(read.diagnostic);
11393
+ }
11394
+ if (adrReadErrors.length > 0)
11395
+ return emitEarly('not-established', 2, adrReadErrors);
11396
+ const extracted = extractContractChecklist({
11397
+ requirements: { path: requirementsRel, text: requirementsRead.text },
11398
+ adrs,
11399
+ });
11400
+ if (!extracted.ok)
11401
+ return emitEarly('fail', 1, extracted.diagnostics);
11402
+ const reportRead = contractReadConfined(repoRoot, join(featureDir, '08_qe_report.md'), reportRel);
11403
+ if (!reportRead.ok)
11404
+ return emitEarly('not-established', 2, [reportRead.diagnostic]);
11405
+ const parsed = parseContractVerdictReport(reportRead.text);
11406
+ if (!parsed.ok) {
11407
+ const diagnostics = parsed.diagnostics.map((entry) => ({
11408
+ ...entry,
11409
+ artifact: entry.artifact ?? reportRel,
11410
+ }));
11411
+ return emitEarly(parsed.established ? 'fail' : 'not-established', parsed.established ? 1 : 2, diagnostics);
11412
+ }
11413
+ const evidenceCache = new Map();
11414
+ const reader = {
11415
+ reportArtifact: reportRel,
11416
+ read(artifact) {
11417
+ const cached = evidenceCache.get(artifact);
11418
+ if (cached !== undefined)
11419
+ return cached;
11420
+ const disk = contractReadConfined(repoRoot, join(repoRoot, artifact), artifact);
11421
+ let result;
11422
+ if (!disk.ok) {
11423
+ result = { ok: false, code: `evidence-${disk.diagnostic.code}`, detail: disk.diagnostic.message };
11424
+ }
11425
+ else if (disk.realPath === reportRead.realPath) {
11426
+ result = { ok: false, code: 'evidence-self-citation', detail: `${artifact} resolves to the QE verdict payload itself` };
11427
+ }
11428
+ else {
11429
+ result = { ok: true, text: disk.text };
11430
+ }
11431
+ evidenceCache.set(artifact, result);
11432
+ return result;
11433
+ },
11434
+ };
11435
+ const rawVerification = verifyContractVerdicts(extracted.checklist, parsed.report, reader);
11436
+ const withReportArtifact = (entry) => ({
11437
+ ...entry,
11438
+ artifact: entry.artifact ?? reportRel,
11439
+ });
11440
+ const verification = {
11441
+ ...rawVerification,
11442
+ diagnostics: rawVerification.diagnostics.map(withReportArtifact),
11443
+ items: rawVerification.items.map((item) => ({
11444
+ ...item,
11445
+ diagnostics: item.diagnostics.map(withReportArtifact),
11446
+ })),
11447
+ };
11448
+ if (json) {
11449
+ write(JSON.stringify({
11450
+ contract: extracted.checklist,
11451
+ report: parsed.report,
11452
+ items: verification.items,
11453
+ diagnostics: verification.diagnostics,
11454
+ counts: verification.counts,
11455
+ overallGrade: verification.overallGrade,
11456
+ outcome: verification.outcome,
11457
+ exitCode: verification.exitCode,
11458
+ }));
11459
+ return verification.exitCode;
11460
+ }
11461
+ for (const item of verification.items) {
11462
+ const reason = item.reason === undefined ? '' : ` — ${item.reason}`;
11463
+ write(` ${item.id}: ${item.verdict ?? 'missing'} · evidence ${item.evidence}${reason}`);
11464
+ }
11465
+ write(` counts: contract=${verification.counts.contractItems} verdict=${verification.counts.verdictItems} met=${verification.counts.met} unmet=${verification.counts.unmet} not-testable=${verification.counts.notTestable} invalid-evidence=${verification.counts.invalidEvidence}`);
11466
+ write(` overall grade: ${verification.overallGrade}`);
11467
+ for (const entry of verification.diagnostics)
11468
+ writeErr(contractDiagnosticLine(entry));
11469
+ const summary = verification.outcome === 'pass'
11470
+ ? `${verification.counts.met} contract item(s) met`
11471
+ : `${verification.diagnostics.length} contract or evidence violation(s)`;
11472
+ write(`contract-check: ${verification.outcome === 'pass' ? 'PASS' : 'FAIL'} — ${summary}`);
11473
+ return verification.exitCode;
11474
+ }
10846
11475
  function cmdAmendmentCheck(options, flags, cwd, write) {
10847
11476
  const json = flags.has('json');
10848
11477
  const readOr = (abs) => {
@@ -12010,6 +12639,85 @@ function readRecallUsageEvents(root) {
12010
12639
  }
12011
12640
  return usage;
12012
12641
  }
12642
+ function readOptionalText(path) {
12643
+ try {
12644
+ return readFileSync(path, 'utf8');
12645
+ }
12646
+ catch {
12647
+ return '';
12648
+ }
12649
+ }
12650
+ function deadwoodAllowlistText() {
12651
+ const require = createRequire(import.meta.url);
12652
+ const corePackage = require.resolve('@dzhechkov/harness-core/package.json');
12653
+ return readFileSync(join(dirname(corePackage), 'src', 'deadwood-allowlist.json'), 'utf8');
12654
+ }
12655
+ function cmdUsageDepthDays(root, now) {
12656
+ const text = readOptionalText(join(root, CMD_USAGE_LOG_RELATIVE));
12657
+ if (text === '')
12658
+ return null;
12659
+ return measureCmdUsageDepthDays(text, now);
12660
+ }
12661
+ /** Canonical deadwood candidates keyed to every alternate top-level dispatch token. */
12662
+ const DEADWOOD_COMMAND_ALIASES = {
12663
+ sync: ['update'],
12664
+ };
12665
+ function deadwoodInventory(root) {
12666
+ const aliasTokens = new Set(Object.values(DEADWOOD_COMMAND_ALIASES).flat());
12667
+ const inventory = DZ_COMMANDS
12668
+ .filter((surface) => !aliasTokens.has(surface))
12669
+ .map((surface) => ({
12670
+ surface,
12671
+ kind: 'command',
12672
+ ...(DEADWOOD_COMMAND_ALIASES[surface] === undefined
12673
+ ? {}
12674
+ : { aliases: DEADWOOD_COMMAND_ALIASES[surface] }),
12675
+ }));
12676
+ for (const rule of DEFAULT_RULES)
12677
+ inventory.push({ surface: rule.id, kind: 'rule' });
12678
+ const skillDir = resolve(root, '.claude/skills');
12679
+ const { skills } = listSkillsDetailed(skillDir);
12680
+ for (const skill of skills)
12681
+ inventory.push({ surface: skill.id, kind: 'skill' });
12682
+ return inventory;
12683
+ }
12684
+ /** `dz deadwood` is a read-only advisory report; findings never affect the exit code. */
12685
+ function cmdDeadwood(options, flags, cwd, write, writeErr) {
12686
+ if (flags.has('weeks')) {
12687
+ writeErr('dz deadwood: --weeks requires an integer value');
12688
+ return 1;
12689
+ }
12690
+ const rawWeeks = options.get('weeks') ?? '8';
12691
+ const weeks = Number(rawWeeks);
12692
+ if (!Number.isInteger(weeks) || weeks <= 0 || weeks > 520) {
12693
+ writeErr(`dz deadwood: --weeks must be an integer from 1 to 520 (received ${JSON.stringify(rawWeeks)})`);
12694
+ return 1;
12695
+ }
12696
+ const root = resolve(cwd);
12697
+ try {
12698
+ // Observe integrity before maintenance: compaction may discard malformed lines, but this run
12699
+ // still has to report that they existed rather than laundering the count to zero.
12700
+ const cmdUsageText = readOptionalText(join(resolveCmdUsageRoot(root), CMD_USAGE_LOG_RELATIVE));
12701
+ const report = buildDeadwoodReport({
12702
+ cmdUsageText,
12703
+ guardAuditText: readOptionalText(join(root, '.dz', 'guard-audit.jsonl')),
12704
+ inventory: deadwoodInventory(root),
12705
+ allowlistText: deadwoodAllowlistText(),
12706
+ weeks,
12707
+ now: new Date(),
12708
+ });
12709
+ compactCmdUsageIfNeeded(root);
12710
+ if (flags.has('json'))
12711
+ write(JSON.stringify({ ...report, exitCode: 0 }, null, 2));
12712
+ else
12713
+ write(renderDeadwoodReport(report, 'text'));
12714
+ return 0;
12715
+ }
12716
+ catch (error) {
12717
+ writeErr(`dz deadwood: ${error instanceof Error ? error.message : String(error)}`);
12718
+ return 1;
12719
+ }
12720
+ }
12013
12721
  /**
12014
12722
  * `dz compounding` — does the learning loop actually PAY? (feature compounding, scout C2.)
12015
12723
  * Gathers the facts (store rows, apply-leg usage log, guard audit) and hands them to the PURE
@@ -12085,7 +12793,15 @@ function cmdCompounding(options, flags, cwd, write) {
12085
12793
  /* absent log — reported by its own gate above, not invented here */
12086
12794
  }
12087
12795
  }
12088
- const report = assembleCompoundingReport({ lessons, usage, guard, nowTs: new Date().toISOString(), evidenceLogs });
12796
+ const now = new Date();
12797
+ const report = assembleCompoundingReport({
12798
+ lessons,
12799
+ usage,
12800
+ guard,
12801
+ nowTs: now.toISOString(),
12802
+ evidenceLogs,
12803
+ cmdUsageDepthDays: cmdUsageDepthDays(root, now),
12804
+ });
12089
12805
  // lesson-bandit-rerank §11: the payoff axis joins THIS report rather than growing a private
12090
12806
  // dashboard — the `rewardEvents : exposureEvents` row asks exactly the question this command
12091
12807
  // already asks of the reinforcement loop (is the apply leg alive, or is it a write-only log?).
@@ -14008,8 +14724,10 @@ export async function runCli(argv, io = {}) {
14008
14724
  // reads appear nowhere in help, and static extraction over the dispatch table lost `--week` from
14009
14725
  // `dz recap` — a refusal built on either list would reject working commands, which is a worse
14010
14726
  // failure than the one being fixed. Goes to STDERR so a `--json` consumer's stdout stays clean.
14011
- for (const notice of unknownFlagNotice([...flags, ...options.keys()].filter((k) => !k.startsWith('_positional_')), KNOWN_CLI_FLAGS)) {
14012
- writeErr(notice.line);
14727
+ if (command !== 'contract-check') {
14728
+ for (const notice of unknownFlagNotice([...flags, ...options.keys()].filter((k) => !k.startsWith('_positional_')), KNOWN_CLI_FLAGS)) {
14729
+ writeErr(notice.line);
14730
+ }
14013
14731
  }
14014
14732
  // ── `dz --version` / `dz -v` / `dz version` — PRE-DISPATCH, before the help branch ──
14015
14733
  //
@@ -14035,6 +14753,13 @@ export async function runCli(argv, io = {}) {
14035
14753
  write(USAGE);
14036
14754
  return 0;
14037
14755
  }
14756
+ // Only registered command identifiers are telemetry. An unknown first argv token may be a path,
14757
+ // typo, or secret-like value; persisting it would violate the command-name-only privacy boundary.
14758
+ // `contract-check` has an explicit byte-for-byte read-only contract: even the advisory command
14759
+ // usage ledger would mutate the repository being audited and invalidate its own safety proof.
14760
+ if (command !== 'contract-check') {
14761
+ recordCommandInvocation(cwd, DZ_COMMANDS.includes(command) ? command : '', new Date());
14762
+ }
14038
14763
  try {
14039
14764
  switch (command) {
14040
14765
  case 'init':
@@ -14085,6 +14810,8 @@ export async function runCli(argv, io = {}) {
14085
14810
  return cmdUsage(options, optionLists, flags, cwd, write);
14086
14811
  case 'claim-check':
14087
14812
  return cmdClaimCheck(options, optionLists, flags, cwd, write);
14813
+ case 'lint':
14814
+ return cmdLint(options, flags, cwd, write);
14088
14815
  case 'sign':
14089
14816
  return cmdSign(options, flags, cwd, write);
14090
14817
  case 'sbom':
@@ -14157,6 +14884,8 @@ export async function runCli(argv, io = {}) {
14157
14884
  return cmdSkillsVerify(options, flags, cwd, write);
14158
14885
  case 'compounding':
14159
14886
  return cmdCompounding(options, flags, cwd, write);
14887
+ case 'deadwood':
14888
+ return cmdDeadwood(options, flags, cwd, write, writeErr);
14160
14889
  case 'epoch-replay':
14161
14890
  return cmdEpochReplay(options, flags, cwd, write);
14162
14891
  case 'score':
@@ -14167,6 +14896,8 @@ export async function runCli(argv, io = {}) {
14167
14896
  return cmdCadence(options, flags, cwd, write);
14168
14897
  case 'qe-rounds':
14169
14898
  return cmdQeRounds(options, flags, cwd, write);
14899
+ case 'restart-advisor':
14900
+ return cmdRestartAdvisor(options, flags, cwd, write);
14170
14901
  case 'tg-post':
14171
14902
  return cmdTgPost(options, flags, cwd, write);
14172
14903
  case 'name-check':
@@ -14177,6 +14908,8 @@ export async function runCli(argv, io = {}) {
14177
14908
  return cmdFeatureAdrRecord(options, flags, cwd, write);
14178
14909
  case 'amendment-check':
14179
14910
  return cmdAmendmentCheck(options, flags, cwd, write);
14911
+ case 'contract-check':
14912
+ return cmdContractCheck(options, flags, cwd, write, writeErr);
14180
14913
  case 'feature-adr-checkpoint':
14181
14914
  return cmdFeatureAdrCheckpoint(options, flags, cwd, write);
14182
14915
  case 'profile':