@dzhechkov/harness-cli 0.8.10 → 0.8.15

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
@@ -10,6 +10,7 @@ import { request as httpsRequest } from 'node:https';
10
10
  import { KNOWN_CLI_FLAGS } from './known-flags.js';
11
11
  import { isBooleanFlag } from './boolean-flags.js';
12
12
  import { resolveInstallSpec } from './install-spec.js';
13
+ import { dispatchedCommands, documentedCommands } from './command-inventory.js';
13
14
  import { execFile, execFileSync, execSync, spawn, spawnSync } from 'node:child_process';
14
15
  import { createHash, randomBytes } from 'node:crypto';
15
16
  import { homedir, hostname, tmpdir } from 'node:os';
@@ -17,9 +18,9 @@ import { createRequire } from 'node:module';
17
18
  import { isDeepStrictEqual } from 'node:util';
18
19
  import { createSkill, getSkillInfo, listSkillsDetailed, formatSkillLoadFailures, formatSkillApplyFailures, resolveTargetName, formatTargetProblem, formatTargetAliasNote, TARGET_NAMES_SORTED, runDoctor, runInit, discoverSkillIds, resolveSelection, formatSelectRefusal, runIntegrationsVerify, 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,
19
20
  // dz workflow run (feature dz-workflow-run): the pure scheduler + the dispatch adapters.
20
- 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, recordLessonForms, normalizeLessonForms, 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, CHECKPOINT_STAGES, estimateEta, extractStageSamples, formatEta, parseCheckpointLines, segmentRun, 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, patternIdentityOf, mergeLessonMatchedForms, 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, classifyChainDefects, CHAINED_JOURNALS, buildManifest, buildSbom, resolveTrustRoot, decideVerifyPolicy, generateSigningKeypair, evaluateGuard, resolveRules, auditRecord, guardExitCode, DEFAULT_RULES, parsePnpmLockImporters, scannableStubPath,
21
+ 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, recordLessonForms, normalizeLessonForms, resolveLearningBackend, storeStats, consolidateSessions, pruneNoisePatterns, lessonDeltaReport, removePatternsByIds, snapshotStore, recallHybrid, teachGuard, mirrorPatternsToVector, mirrorEntriesToVector, patternVectorEntry, readMemoryLearningConfig, promotePatterns, quarantineExpiryCandidates, pruneQuarantinePatterns, clearAgentdbQuarantine, vectorMirrorEnabled, vectorTierStatus, resolveVectorEngine, reindexVectorStore, harmonizeVectorStore, importRvfCheckpoint, renderFeatureAdrPhaseLine, statuslineData, countLearningStoreRowsReadonly, readStoreMark, writeStoreMark, resetStoreMark, checkStoreHealth, storeGuardPath, storeSnapshotPath, writeFeatureAdrState, writeFeatureAdrStateDetailed, CHECKPOINT_STAGES, estimateEta, extractStageSamples, formatEta, parseCheckpointLines, segmentRun, 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, patternIdentityOf, mergeLessonMatchedForms, SWARM_BRIEF_CONTRACT, checkSwarmBrief, visibleText, 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, classifyChainDefects, CHAINED_JOURNALS, buildManifest, buildSbom, resolveTrustRoot, decideVerifyPolicy, generateSigningKeypair, appendTransition, evaluateGuard, resolveRules, auditRecord, guardExitCode, DEFAULT_RULES, parsePnpmLockImporters, scannableStubPath,
21
22
  // guard-promotion (feature guard-promotion, scout idea #1)
22
- assembleCandidates, renderPromotionReport, renderPromotionAdr, normalizePromotionState, nextPromotionState, recordPromotionRunEvidence, isLessonRuleContentAnchor, isOffsetIsoTimestamp, 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, unfedRuns, 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,
23
+ assembleCandidates, renderPromotionReport, renderPromotionAdr, normalizePromotionState, nextPromotionState, recordPromotionRunEvidence, isLessonRuleContentAnchor, isOffsetIsoTimestamp, globMatch, promotionAdrRelPath, DEFAULT_WINDOW_DAYS, DEFAULT_PERIODS, MAX_CONTENT_FETCHES, BUILTIN_COVERAGE, decideProvenance, isInsideTree, signManifest, verifyManifest, listPackFiles, 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, resolveScanTailTranscript, detectProcessRakes, buildRetro, renderRetro, retroLessonText, PROCESS_SIGNATURES, RETRO_DOMAIN, runRetroTailScan, scanForSetup, buildSetupPlan, scaffoldFromSpec, renderScaffoldPreview, readExistingForScaffold, assembleChallengeContext, buildChallengeBrief, planDiscriminationCheck, classifyDiscrimination, classifyExecutionEvidence, pickAdversaryModel, CHALLENGE_QUESTIONS, loadOutcomes, renderOutcomes, statsForKey, selectAutoCost, recordProvisional, finalizeOutcome, harvestStageOutcomes, recommendModels, planFeed, unfedRuns, 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,
23
24
  // Cold-vs-warm EPOCH RUNNER (feature epoch-replay) — orchestrates + scores, never calls a model.
24
25
  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, scoreReceiptToAggregateRow, readScoreAggregateRows, dedupeScoreAggregateRows, buildScoreAggregateReport, renderScoreAggregateReport, 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,
25
26
  // Smart Backlog (feature smart-backlog) — goal-directed idea pipeline over the Brain vector engine.
@@ -27,16 +28,39 @@ readBacklogConfig, readIdeas, writeIdeas, ideaId, dedupIdea, readGoalMap, readGo
27
28
  // qe-bridge (feature qe-bridge-claude, ADR-001): the pure half of the reverse QE bridge.
28
29
  KNOWN_CLAUDE, isSafeClaudeId, claudeProbeArgs, claudeReviewArgs, interpretClaudeProbe, modelFamily, buildBridgePrompt, parseBridgeOutput, buildBridgeFailureRecord, buildBridgeSignoffRecord, renderBridgeReport, isSafeSlug, hasUnsafePathChars, hasDotDotSegment, buildReqeBrief, settleReqeDebt, renderReqeList, REQE_SCOPE,
29
30
  // Mutation gate (feature ha-mutation-gate) — break each named protection, run the suite, require red.
30
- parseMutationRegistry, applyMutationToText, attributeBaselineRedness, countFailingTests, detectSuiteCompletionReceipt, detectSuiteReceiptMismatch, classifyBaseline, classifyRunFailure, classifyMutationOutcome, mutationGateExitCode, summarizeMutationResults, renderMutationReport, runWithOneInternalRetry, 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,
31
+ parseMutationRegistry, applyMutationToText, attributeBaselineRedness, countFailingTests, detectSuiteCompletionReceipt, detectSuiteReceiptMismatch, classifyBaseline, classifyRunFailure, classifyMutationOutcome, mutationGateExitCode, summarizeMutationResults, renderMutationReport, runWithOneInternalRetry, TRACE_BUNDLE_LEDGER_PATH, TRACE_BUNDLE_SCHEMA, TRACE_BUNDLE_RUN_META_FILE, buildBundle, serializeBundle, parseBundle, planImport, decideCheckpointWrite, amendmentSection, amendmentSectionCount, amendmentDeclarationAmbiguity, 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,
31
32
  // operator-profile (ADR-001): per-user 0600 store + marked block in ~/.claude/CLAUDE.md
32
33
  renderProfileBlock, readProfile, writeProfile, syncProfileBlock, checkProfileDrift, parseRegister, registerOwnerWord, profileAgeDays, parseDomainList, domainListText, parseYesNo, REGISTERS, } from '@dzhechkov/harness-core';
33
34
  import { getPreset, PRESET_NAMES } from '@dzhechkov/harness-presets';
34
35
  import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, ScoutMemory } from '@dzhechkov/scout';
36
+ /**
37
+ * Область, по которой гейт дрейфа собирает факты. ПОЛНАЯ, а не только корни установки.
38
+ *
39
+ * ПОЧЕМУ. Под областью `installs` сравниваются лишь корни установки (`.claude/skills`,
40
+ * `.agents/skills` и далее). Навык, чьи копии лежат в РАЗНЫХ корнях — канон в `packages/`, живая
41
+ * копия в `.claude/skills` — имеет там ОДНУ копию, а одну копию не с чем сравнивать: она
42
+ * отбрасывается как не дублированная. То есть главный класс расхождения был для гейта невидим.
43
+ *
44
+ * ИЗМЕРЕНО 2026-09-03: `brutal-honesty-review` разошёлся ровно так (канон в skills-qe, копия в
45
+ * бандле p-replicator, живая в .claude/skills), и гейт не мог увидеть это В ПРИНЦИПЕ. Я тогда
46
+ * написал в отчёте «гейт разблокирован» — он никогда не был на этом заблокирован.
47
+ *
48
+ * Узкая область давала 19 дублирующихся навыков, полная даёт 211. Безопасность расширения
49
+ * проверена ДО правки: с полной областью и списком исключений дрейфа сегодня НОЛЬ.
50
+ */
51
+ const DRIFT_SWEEP_SCOPE = 'all';
52
+ /**
53
+ * Базовая дата правила `backlog-covers-features`. Каталоги фич, заведённые ДО неё, правило не
54
+ * трогает: они появились раньше самого правила. ИЗМЕРЕНО 2026-09-03 — без базы правило даёт 236
55
+ * нарушений из 336 каталогов, и проверка, изобретающая полсотни нарушений в первый день, учит
56
+ * людей себя игнорировать. Дата = день, когда правило принято владельцем.
57
+ */
58
+ const BACKLOG_COVERAGE_BASELINE = '2026-09-03';
35
59
  /** Literal command inventory, pinned against the main dispatch switch by a layer-1 test. */
36
60
  export const DZ_COMMANDS = [
37
61
  'init', 'verify', 'sync', 'update', 'list', 'create-skill', 'info', 'scout',
38
62
  'workflow', 'workflow-lint', 'workflow-trace', 'migrate', 'doctor', 'install',
39
- 'bundle', 'teach', 'consolidate', 'recall', 'vector', 'brain', 'statusline',
63
+ 'bundle', 'teach', 'consolidate', 'recall', 'vector', 'brain', 'statusline', 'store-guard',
40
64
  'usage', 'claim-check', 'lint', 'sign', 'sbom', 'guard', 'verify-pack', 'setup',
41
65
  'pretrain', 'compose', 'diff', 'recommend', 'upgrade', 'auto-canonicalize',
42
66
  'publish', 'release', 'parity', 'registry', 'benchmark', 'mcp-scan',
@@ -45,7 +69,7 @@ export const DZ_COMMANDS = [
45
69
  'retro', 'feature-adr-setup', 'challenge', 'discrimination-check',
46
70
  'mutation-gate', 'delivery-check', 'skills-verify', 'compounding', 'deadwood',
47
71
  'epoch-replay', 'score', 'recap', 'cadence', 'qe-rounds', 'restart-advisor', 'tg-post',
48
- 'name-check', 'provenance-check', 'feature-adr-record', 'amendment-check', 'contract-check',
72
+ 'name-check', 'brief-check', 'provenance-check', 'feature-adr-record', 'amendment-check', 'contract-check',
49
73
  'feature-adr-checkpoint', 'profile', 'reqe', 'qe-bridge', 'backlog', 'routing',
50
74
  'bto-optimize', 'dashboard', 'roam', 'import-ecc', 'chain',
51
75
  ];
@@ -95,13 +119,14 @@ Usage:
95
119
  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)
96
120
  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)
97
121
  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)
122
+ dz brief-check <file> [--json] (does a swarm brief declare OUTPUT_DIR, UNITS and ASSEMBLY_UNIT? parsed as DATA, refused by name; verifies the brief DECLARED the contract, not that the agent follows it. exit 0 ok / 1 refused / 2 unreadable)
98
123
  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)
99
124
  dz project-skills [--project <dir>] [--json] [--stages-json] (polymorphic feature-adr: resolve architecture/project-skills.json — fixed roles product-vision/critic/brand/impl-bar plus an open extra[] — into per-stage guidance. READ-ONLY. --project names the root explicitly, so it works from any cwd; without it the manifest is read from the current repo. No manifest ⇒ a byte-identical generic run)
100
125
  dz discrimination-check --slug <slug> [--base <ref>] [--json] (does the ADR's named test actually DISCRIMINATE? Re-runs it on a worktree at the pre-feature commit, where it MUST go red. A test that passes with the feature removed proves nothing; dz amendment-check proves the test exists, this proves it bites)
101
126
  dz guard [check|promote|init] [--json] [--force] (HARD/SOFT repo rules — readme-first, lockfile-in-sync, claim tagging — run automatically as a pre-flight inside dz publish. HARD blocks, SOFT warns)
102
127
  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)
103
128
  dz sbom [--pack <name>] [--out <file>] (CycloneDX software bill of materials for the workspace, or for one pack with --pack)
104
- 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)
129
+ dz amendment-check --slug <slug> | --feature-dir <dir> | --all [--json] (the deterministic Step-8 amendment gate: every AM-N / AM-CP-N row must resolve to a test found INSIDE the file the row names (the challenge-panel prefix is part of the id: AM-CP-1 is never AM-1); 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, UNLESS the plan explicitly declares \"None\"/\"нет\", which is an answer and reports skip. --all is a CENSUS and always exits 0. Does NOT prove non-vacuity — that is dz discrimination-check)
105
130
  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)
106
131
  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)
107
132
  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)
@@ -109,7 +134,7 @@ Usage:
109
134
  dz reqe [--slug <feature> [--done --report <f>]] [--json] (the re-QE debt ledger: a usage-switched run whose Step-8 QE ran on the coder's OWN family records a debt; list debts, print the cross-family review brief, settle FAIL-CLOSED against a graded report — the settlement lands in 08_qe_report.md)
110
135
  dz qe-bridge --family claude --slug <feature> [--coder-family codex|claude] [--model <id>] [--files a,b] [--out <f>] [--timeout <s>] [--allow-same-family] [--json] (the REVERSE QE bridge: run an INDEPENDENT Claude reviewer over a feature's Step-8 artifacts from ANY host — a Codex session included, plain shell, no Claude agent plane needed — and land a PARSED signoff. The reviewer runs ISOLATED: an EMPTY temp cwd plus --safe-mode --strict-mcp-config --tools '' --no-session-persistence, so no CLAUDE.md/skills/plugins/hooks/MCP load, and the verdict is read from the --output-format json RESULT ENVELOPE — text a session customization printed onto the same stdout can never become a signoff. Probes the model before trusting it; sends SCOPED extracts with a loud 200k-char ceiling (never silent truncation); the grade must AGREE across three LAST-anchored channels (terminal marker line, fenced qe-bridge-signoff JSON, the report's own GRADE line) AND the marker must be the FINAL content — empty, gradeless, self-contradicting or miscounted output is one of 17 NAMED failures with an audit record under features/<slug>/.fa-state/qe-bridge/ (runId, resolved executable + binOverride, prompt sha256, channel offsets, requestedOut, reportWritten, retained raw stdout; 0600 files in a 0700 dir), never a clean review. A --coder-family that contradicts the recorded reqe debt is refused. Writes features/<slug>/08b_reqe_report.md, which dz reqe --done settles unchanged. DISCLOSURE: the extracts you scope are sent to the Claude runtime; the bridge cannot classify secrets. DZ_QE_BRIDGE_CLAUDE_BIN is a TEST SEAM, not a flag. exit 0 signoff parsed (ANY grade — it reports, it does not gate) / 1 named failure / 2 usage)
111
136
  dz mutation-gate [--package <dir>] [--registry <file>] [--test-cmd "<cmd>"] [--only <id[,id]>] [--timeout <ms>] [--rebaseline per-entry|final] [--keep-scratch] [--json] (prove each NAMED protection has a test that DISCRIMINATES: copy the package to a scratch dir, verify the baseline suite is green, apply each registry mutation, run the suite, REQUIRE red, restore. The red must be BEHAVIOURAL: a mutation that no longer parses is MUTATION_UNPARSEABLE; a red run whose OWN output reports a test FILE failing to load (node --test file-level not-ok with exitCode, vitest Failed Suites) is MUTATION_LOAD_FATAL — the signal comes from the same run as the failing count, never from a separate isolated import; red output whose shape matches no known runner is INCONCLUSIVE (a runner-coverage gap, loud, never PROVEN); a count far above the entry's bound is OVER_FAILING; a restored tree that does not reproduce green makes the entry INCONCLUSIVE (flaky). Mutation writes are realpath-contained to the scratch copy: a symlink escape or a node_modules/ target is refused (exit 2), the real tree is never written. A mutation that does not apply, a green suite, or an inconclusive run is a FAILURE — never a skip. exit 0 all proven / 1 gate failed / 2 setup error)
112
- dz backlog add "<idea>" [--effort 1-5] [--proposal <text>] [--dry-run] [--project <dir>] [--json] (capture an idea: semantic dedup against existing ideas via the Brain vector engine (DUPLICATE>=0.92 merges, RELATED links, NEW creates) + GoalMap alignment; --dry-run classifies without writing)
137
+ dz backlog add "<idea>" [--effort 1-5] [--proposal <text>] [--dry-run] [--allow-cold-start] [--project <dir>] [--json] (capture an idea: semantic dedup against existing ideas via the Brain vector engine (DUPLICATE>=0.92 merges, RELATED links, NEW creates) + GoalMap alignment; --dry-run classifies without writing)
113
138
  dz backlog list [--status <s>] [--goal <id>] [--project <dir>] [--json] (list captured ideas, filterable by status/goal)
114
139
  dz backlog show <id> [--project <dir>] [--json] (full record for one idea)
115
140
  dz backlog goals [--validate] [--project <dir>] [--json] (list/validate the compass at .dz/backlog/goals.json)
@@ -123,7 +148,7 @@ Usage:
123
148
  dz backlog jira <id> [--project <dir>] [--json] (draft a Jira issue via the configurable adapter (backlog.jira.adapter: jira-mcp|copilot-mcp|none); none writes an auditable jira-outbox/<id>.json stub)
124
149
  dz backlog harmonize [--apply] [--threshold <0-1>] [--project <dir>] [--json] (batch semantic dedup of the backlog ideas; --dry-run default, --apply snapshots first)
125
150
  dz setup --target <name> [--preset <name>] [--select id,id,...] [--skills-dir <dir>] [--project <dir>] [--memory agentdb] [--no-memory] [--no-hooks] [--no-verify] [--install-driver] [--force] [--enrich] (--target codex ALSO installs + LIVE-verifies the codex hooks; an unverified hook exits non-zero WITHOUT aborting the rest of setup)
126
- dz teach "<pattern>" [--class-form "<template with :slot>"] [--reward <0-1>] [--domain <name>] [--type rule|success-pattern|lesson-learned] [--project <dir>] [--no-mirror] (class form is optional; rejection never blocks the specific write; --project pins the learned store to <dir>/.dz)
151
+ dz teach "<pattern>" [--class-form "<template with :slot>"] [--reward <0-1>] [--domain <name>] [--type rule|success-pattern|lesson-learned] [--project <dir>] [--no-mirror] [--allow-cold-start] (class form is optional; rejection never blocks the specific write; --project pins the learned store to <dir>/.dz)
127
152
  dz teach --from-json <file> [--project <dir>] [--no-mirror] (bulk-import a 'dz recall --all --json' export — share a learned store across machines)
128
153
  dz consolidate [--sessions-dir <dir>] [--project <dir>] [--no-mirror] [--prune-noise [--apply]] [--prune-quarantine [--apply]] (both prunes: DRY-RUN by default; --apply snapshots then deletes; prune-quarantine = expired unproven lessons ONLY, never coupled to noise)
129
154
  dz recall "<query>" [--limit <N>] [--domain <name>] [--semantic | --no-semantic] [--books [--book <slug>]] [--project <dir>] | dz recall --all [--json] | dz recall --usage [--json] | dz recall --forget <dzId>[,<dzId>] [--apply] | dz recall --promote <dzId>[,<dzId>] [--apply] (--domain <name> BOOSTS lessons of that domain without dropping foreign ones — a shared store keeps its cross-domain transfers; forget/promote: dry-run default; forget snapshots before removing; promote lifts lesson-quarantine)
@@ -143,7 +168,8 @@ Usage:
143
168
  dz brain expand <kuId> [--source <slug>] [--json] (full-content lookup for a citation kuId; --json emits the full KU object)
144
169
  dz brain init [--project <dir>] [--k <N>] (wire the grounding hook into .claude/settings.json — opt-in)
145
170
  dz statusline [--json] [--install] [--project <dir>] (live self-learning panel for Claude Code's status bar; reads the CC JSON payload from STDIN)
146
- dz statusline --fa-record --slug <s> --step "<label>" [--kind <feature-adr|loop>] [--recalled <n>] [--stored <n>] [--mode <m>] (feature-adr: record live per-run learning state 📐 panel segment)
171
+ dz store-guard [--status|--reset] [--yes] [--project <dir>] (show the monotonic external high-water mark; --reset is the only lowering path and requires confirmation or --yes)
172
+ dz statusline --fa-record --slug <s> --step "<label>" [--kind <feature-adr|loop>] [--tier <S|M|L|XL>] [--recalled <n>] [--stored <n>] [--mode <m>] (feature-adr: record live per-run learning state + phase → 📐 SECOND-LINE phase panel; a plain "Step <n>" label that goes BACKWARDS against a slot younger than 90 min is absorbed as a stale duplicate — prefix the label with ⛔ or ⏸ to record a legitimate regression)
147
173
  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)
148
174
  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)
149
175
  dz chain [--project <dir>] [--json] (verify EVERY hash-chained journal in ONE command: coverage is DERIVED from the CHAINED_JOURNALS registry, never typed, so a journal cannot be given a chain and checked by nobody. An ABSENT journal is NAMED absent, never omitted — omission and cleanliness are indistinguishable in a report. Statuses: ok | healed (defects the current unbroken run has outlived — verdicts over present records are sound) | unchained (present, no chained record yet — legal) | absent | broken | unreadable. Exit 1 on broken/unreadable: a verifier that reports damage and exits 0 is one no automation can act on)
@@ -171,6 +197,10 @@ Usage:
171
197
  dz dashboard
172
198
  dz roam [--apply] [--slug <slug>]
173
199
  dz import-ecc [--local-path <dir>] [--select id,id,...] [--limit N] [--output <dir>] [--force]
200
+ dz retro [transcript-path] [--json] [--threshold N] [--no-teach] [--project <dir>] [--install-hook] (per-session retrospective + co-learning: mines the session transcript for recurring PROCESS rakes, drills you, and teaches the same lesson to the store)
201
+ dz feature-adr-setup [--plan] [--from-spec <spec.json>] [--guards [--loc-cap <n>]] [--gates [--target <name>]] [--apply] [--json] (scaffold the project-awareness files feature-adr reads — vision / map / testing / project-skills — plus the deterministic project guards and the portable delivery gates; --guards and --gates work STANDALONE or with --from-spec, and --apply writes for all three; without --apply everything is a preview)
202
+ dz mr-rakes [--json] [--candidate N] [--confirmed N] [--teach] [--gen-critic <path> [--apply]] (experimental: mine the review corpus — features' QE reports + REVIEW files — for RECURRING mistakes and close them into self-learning)
203
+ dz bto-optimize --split | --plan | --select | --scope-check | --diff [--json] (experimental: deterministic tune/holdout split, budget plan and holdout-no-regress winner selection behind the /bto-optimize skill)
174
204
  dz help
175
205
 
176
206
  Global: --version | -v [--json] (prints this CLI's own semver on one line, exit 0; "unknown" + exit 1 when unresolvable)
@@ -749,7 +779,7 @@ async function cmdScout(options, flags, cwd, write) {
749
779
  write('Scanning 9 sources (GitHub + npm + HN + MCP Registry + Glama + OSSInsight + Smithery + Semantic Scholar + arXiv)...\n');
750
780
  try {
751
781
  const scanTopics = topicsArg ? topicsArg.split(',').map((t) => t.trim()) : undefined;
752
- const { results: repos, totalBySource } = await scanAllSources({
782
+ const { results: repos, totalBySource, statusBySource } = await scanAllSources({
753
783
  token,
754
784
  topics: scanTopics,
755
785
  since,
@@ -761,10 +791,17 @@ async function cmdScout(options, flags, cwd, write) {
761
791
  .map(([src, count]) => `${src}: ${count}`)
762
792
  .join(', ');
763
793
  write(`Sources: ${sourceLines}`);
764
- // Memory: diff with previous scan
794
+ // Memory: diff with previous scan.
795
+ //
796
+ // СОСТОЯНИЕ ИСТОЧНИКОВ ПЕРЕДАЁТСЯ ОБЯЗАТЕЛЬНО. Без него разность не выводит исчезновений
797
+ // вообще — и это правильно: источник, ответивший кодом ошибки, раньше делал ВСЕ свои записи
798
+ // «пропавшими» на экране, то есть отчёт печатал факт о нашей сети как факт о мире.
765
799
  if (showDiff || memory.size > 0) {
766
- const diff = memory.diff(repos);
767
- if (diff.newRepos.length > 0 || diff.goneRepos.length > 0 || diff.changedScore.length > 0) {
800
+ const health = {};
801
+ for (const [source, status] of Object.entries(statusBySource))
802
+ health[source] = status.health;
803
+ const diff = memory.diff(repos, health);
804
+ if (diff.newRepos.length > 0 || diff.goneRepos.length > 0 || diff.changedScore.length > 0 || diff.goneOmittedReason !== undefined) {
768
805
  write(memory.diffMarkdown(diff));
769
806
  }
770
807
  else if (memory.size > 0) {
@@ -1591,6 +1628,47 @@ function cmdBundle(options, flags, cwd, write) {
1591
1628
  }
1592
1629
  return 0;
1593
1630
  }
1631
+ /**
1632
+ * Команда npm для установки пакета В ЦЕЛЕВОЙ КАТАЛОГ, а не куда решит npm.
1633
+ *
1634
+ * ЗАЧЕМ `--prefix`. Без него npm при отсутствии `package.json` в текущем каталоге поднимается по
1635
+ * дереву до первого найденного и мутирует ЕГО — а `dz` потом ищет пакет в
1636
+ * `<цель>/node_modules` и не находит. Место установки и место проверки были двумя независимыми
1637
+ * предположениями, и совпадали они только по удаче.
1638
+ *
1639
+ * ИЗМЕРЕНО 2026-09-03 (полевой случай владельца): установка в каталог без `package.json`
1640
+ * записала в `/home`, где лежит ЧУЖОЙ проект; ручной откат вернул `package.json`, а запись
1641
+ * `extraneous` в `/home/package-lock.json` пережила откат.
1642
+ *
1643
+ * ПОЧЕМУ НЕ ОТКАЗ (ADR-001, вариант A отвергнут). Отказ запретил бы законный сценарий: проект
1644
+ * внутри монорепо, намеренно не имеющий своего `package.json` и опирающийся на родительский
1645
+ * воркспейс. `--prefix` согласует установку с проверкой ПО ПОСТРОЕНИЮ и сценарий сохраняет.
1646
+ *
1647
+ * ЧИСТАЯ: ни файловой системы, ни запуска npm — проверяется без обоих. Путь экранируется, потому
1648
+ * что каталоги с пробелом в имени встречаются в наших же тестах.
1649
+ */
1650
+ export function buildInstallArgs(npmSpec, projectRoot) {
1651
+ return ['install', npmSpec, '--prefix', projectRoot, '--save-dev', '--no-fund', '--no-audit'];
1652
+ }
1653
+ /**
1654
+ * Та же команда СТРОКОЙ — только для показа человеку и для тестового шва.
1655
+ *
1656
+ * НЕ ДЛЯ ИСПОЛНЕНИЯ, и это не стилистическая оговорка. `JSON.stringify` НЕ является экранированием
1657
+ * для оболочки: внутри двойных кавычек оболочка по-прежнему выполняет `$(...)` и обратные кавычки.
1658
+ * ИЗМЕРЕНО 2026-09-03 — `execSync('echo ' + JSON.stringify('pkg$(touch ФАЙЛ)'))` создал файл.
1659
+ * Прежняя редакция этого комментария утверждала «путь экранируется»; это было неверно, и находку
1660
+ * предъявило кросс-семейное ревью (gpt-5.6-sol), а я подтвердил её пробой.
1661
+ *
1662
+ * Боевой путь исполняется через `execFileSync` массивом аргументов — оболочки в цепочке нет вовсе,
1663
+ * поэтому подставлять некуда. Это структурное лечение, а не более хитрое экранирование.
1664
+ */
1665
+ export function buildInstallCommand(npmSpec, projectRoot) {
1666
+ // ЗНАЧЕНИЯ в кавычках, ФЛАГИ без — та же форма, что печаталась до этой фичи, чтобы читатель
1667
+ // (и закреплённые тесты) видели знакомую строку. Кавычки здесь — ЧИТАЕМОСТЬ, а не безопасность:
1668
+ // безопасность даёт отсутствие оболочки на боевом пути.
1669
+ return `npm install ${JSON.stringify(npmSpec)} --prefix ${JSON.stringify(projectRoot)}`
1670
+ + ' --save-dev --no-fund --no-audit';
1671
+ }
1594
1672
  async function cmdInstall(options, flags, cwd, write, writeErr, installRunner) {
1595
1673
  const pkg = options.get('_positional_0');
1596
1674
  if (!pkg) {
@@ -1649,17 +1727,38 @@ async function cmdInstall(options, flags, cwd, write, writeErr, installRunner) {
1649
1727
  if (targetResolution.via === 'alias')
1650
1728
  writeErr(formatTargetAliasNote('dz install', targetOpt, target));
1651
1729
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
1730
+ // ПРЕДПОСЫЛКА НАЗЫВАЕТСЯ ДО ПОБОЧНОГО ЭФФЕКТА, А НЕ ПОСЛЕ (ADR-001, FR-2).
1731
+ //
1732
+ // Проверка стоит ЗДЕСЬ, до развилки installRunner/execSync, и это не стилистика. Поставить её
1733
+ // внутрь ветки execSync значило бы оставить боевой путь непокрытым при зелёных тестах — ровно
1734
+ // то состояние, из которого фича и родилась.
1735
+ const hasOwnManifest = existsSync(join(projectRoot, 'package.json'));
1736
+ if (!hasOwnManifest) {
1737
+ write(`dz install: ${projectRoot} — не npm-проект (нет своего package.json).`);
1738
+ write(` Ставлю ЛОКАЛЬНО в него: npm получит --prefix, package.json и node_modules появятся здесь.`);
1739
+ write(` Без --prefix npm поднялся бы по дереву и записал в ЧУЖОЙ проект выше — измерено 2026-09-03.`);
1740
+ }
1652
1741
  // Step 1: npm install the package (installRunner is the CliIo test seam — unset in production)
1653
1742
  write(`Installing ${specResolution.npmSpec}${specResolution.kind === 'name' ? '' : ` (${specResolution.kind} → node_modules/${specResolution.dirName})`}...`);
1654
- const installCmd = `npm install ${JSON.stringify(specResolution.npmSpec)} --save-dev --no-fund --no-audit`;
1743
+ const installCmd = buildInstallCommand(specResolution.npmSpec, projectRoot);
1655
1744
  try {
1656
1745
  if (installRunner)
1657
1746
  installRunner(installCmd, projectRoot);
1747
+ // БЕЗ ОБОЛОЧКИ. execFileSync с массивом аргументов не запускает shell, поэтому имя пакета или
1748
+ // путь с `$(...)` подставить нечему. Строка выше — для показа и для тестового шва, не для
1749
+ // исполнения (см. докстринг buildInstallCommand).
1658
1750
  else
1659
- execSync(installCmd, { cwd: projectRoot, stdio: 'pipe', encoding: 'utf-8' });
1751
+ execFileSync('npm', [...buildInstallArgs(specResolution.npmSpec, projectRoot)], { cwd: projectRoot, stdio: 'pipe', encoding: 'utf-8' });
1660
1752
  }
1661
1753
  catch (err) {
1662
1754
  write(`dz install: npm install failed — ${err instanceof Error ? err.message : String(err)}`);
1755
+ // НЕАТОМАРНЫЙ ОТКАЗ НАЗЫВАЕТСЯ ВСЛУХ (ADR-001, FR-4). Названо кросс-семейной проверкой
1756
+ // 2026-09-03: npm мог успеть изменить package.json, файл замков и node_modules и упасть уже
1757
+ // после этого. Отката у нас нет — и молчать об этом хуже, чем не откатывать: пользователь
1758
+ // считает каталог нетронутым. Полевой случай: ручной откат вернул package.json, а запись
1759
+ // extraneous в файле замков пережила его.
1760
+ write(` npm мог успеть изменить файлы ДО падения — проверьте ${join(projectRoot, 'package.json')},`);
1761
+ write(` ${join(projectRoot, 'package-lock.json')} и ${join(projectRoot, 'node_modules')}: отката dz не делает.`);
1663
1762
  return 1;
1664
1763
  }
1665
1764
  // Step 2: Find SKILL.md files in the installed package — under the RESOLVED dir name, never the
@@ -1910,7 +2009,7 @@ function cmdStatuslineInstall(options, cwd, write) {
1910
2009
  * `--kind <feature-adr|loop>` identifies the producer, defaults to `feature-adr`, and rejects any
1911
2010
  * other value rather than silently weakening panel arbitration.
1912
2011
  */
1913
- function cmdStatuslineFaRecord(options, cwd, write) {
2012
+ function cmdStatuslineFaRecord(options, cwd, write, writeErr) {
1914
2013
  const slug = (options.get('slug') ?? '').trim();
1915
2014
  const step = (options.get('step') ?? '').trim();
1916
2015
  // `--recalled auto` derives the count from the recall-usage log for `--run <id>`, replacing the
@@ -1970,18 +2069,40 @@ function cmdStatuslineFaRecord(options, cwd, write) {
1970
2069
  write(' Example: dz statusline --fa-record --slug add-user-auth --step "Step 0" --kind feature-adr --recalled 5 --stored 2');
1971
2070
  return 1;
1972
2071
  }
2072
+ // fa-phase-statusline (acid A1): --tier drives done/total on the phase line — an invalid tier is
2073
+ // REJECTED before anything is written (nothing slotted, nothing ledgered), never silently dropped.
2074
+ const tierRaw = options.get('tier');
2075
+ const tier = tierRaw?.trim();
2076
+ if (tier !== undefined && tier !== 'S' && tier !== 'M' && tier !== 'L' && tier !== 'XL') {
2077
+ write(`dz statusline --fa-record: --tier must be S, M, L or XL (got "${tierRaw}")`);
2078
+ write(' Example: dz statusline --fa-record --slug add-user-auth --step "Step 7 Code" --tier M');
2079
+ return 1;
2080
+ }
1973
2081
  const mode = options.get('mode');
1974
2082
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
1975
- const state = writeFeatureAdrState(projectRoot, {
2083
+ const outcome = writeFeatureAdrStateDetailed(projectRoot, {
1976
2084
  kind: kindRaw, slug, step, recalled, stored,
1977
2085
  ...(reinforced > 0 ? { reinforced } : {}),
1978
2086
  ...(mode !== undefined && mode.trim() !== '' ? { mode: mode.trim() } : {}),
2087
+ ...(tier !== undefined ? { tier } : {}),
1979
2088
  });
2089
+ const state = outcome.state;
1980
2090
  if (state === undefined) {
2091
+ // [AM-5] A REFUSED slot write is LOUD. A held `fa-phase-slot` lock or an unwritable `.dz` used
2092
+ // to return a bare `undefined`, and a caller reading silence as success is exactly the
2093
+ // "absence of a receipt is not success" class. The reason goes to stderr — diagnosis, not
2094
+ // data — and the EXIT CODE is unchanged for a refusal, because the panel must never break the
2095
+ // pipeline that is only reporting to it.
2096
+ if (outcome.refused !== undefined) {
2097
+ writeErr(`fa-record: slot write refused (${slug}): ${outcome.refused}`);
2098
+ return 0;
2099
+ }
1981
2100
  write(`dz statusline --fa-record: could not write learning state under ${projectRoot}/.dz/feature-adr/`);
1982
2101
  return 1;
1983
2102
  }
1984
- write(`dz statusline: recorded /feature-adr learning state for "${slug}" (${step}) 🎓 ${state.pool} pool · ↑${state.recalled} used · +${state.stored} new · ↻${state.reinforced ?? 0} reinforced`);
2103
+ // state.step, not the flag: the monotonic guard may have kept a LATER step against a stale
2104
+ // duplicate record (fa-phase-statusline P1) — print what actually stands in the slot.
2105
+ write(`dz statusline: recorded /feature-adr learning state for "${slug}" (${state.step}) — 🎓 ${state.pool} pool · ↑${state.recalled} used · +${state.stored} new · ↻${state.reinforced ?? 0} reinforced`);
1985
2106
  return 0;
1986
2107
  }
1987
2108
  function statuslineEtaStage(step) {
@@ -2136,16 +2257,21 @@ function statuslineEta(projectRoot, state, nowMs) {
2136
2257
  * least a minimal `dz` even on total failure.
2137
2258
  *
2138
2259
  * Flags: `--install` wires it into settings.json; `--fa-record` records a live `/feature-adr`
2139
- * learning state (WRITES — see {@link cmdStatuslineFaRecord}); `--json` prints the raw data object;
2140
- * default prints the status line (with a 📐 pipeline segment prepended when a fresh run is in flight).
2260
+ * learning state (WRITES — see {@link cmdStatuslineFaRecord}); `--json` prints the raw data object
2261
+ * (plus `featureAdrLine`, the rendered phase line, when a fresh /feature-adr run is in flight);
2262
+ * default prints the status line, with the 📐 phase panel as its OWN SECOND LINE (format B —
2263
+ * fa-phase-statusline ADR-001 D1; Claude Code renders every stdout line of a statusline command).
2264
+ * The ETA fragment main shipped for that panel rides the SECOND line with it (fa-phase-statusline ADR-001 D1) — the panel
2265
+ * moved, the estimate was not dropped.
2141
2266
  */
2142
- function cmdStatusline(options, flags, cwd, write, readStdin) {
2267
+ function cmdStatusline(options, flags, cwd, write, readStdin, writeErr) {
2143
2268
  if (flags.has('install'))
2144
2269
  return cmdStatuslineInstall(options, cwd, write);
2145
2270
  if (flags.has('fa-record'))
2146
- return cmdStatuslineFaRecord(options, cwd, write);
2271
+ return cmdStatuslineFaRecord(options, cwd, write, writeErr);
2147
2272
  try {
2148
2273
  const projectRoot = statuslineProjectRoot(readStdin(), options, cwd);
2274
+ warnLearningStoreRead(projectRoot, writeErr, 'dz statusline');
2149
2275
  const data = statuslineData(projectRoot);
2150
2276
  const fa = data.featureAdr;
2151
2277
  let eta;
@@ -2162,27 +2288,56 @@ function cmdStatusline(options, flags, cwd, write, readStdin) {
2162
2288
  etaFragment = undefined;
2163
2289
  }
2164
2290
  }
2291
+ // fa-phase-statusline (ADR-001 D1): the phase line renders from the slot ALONE — a pure
2292
+ // function over data.featureAdr, computed once here for both the plain and --json surfaces.
2293
+ const phaseLine = fa !== undefined ? renderFeatureAdrPhaseLine(fa) : undefined;
2165
2294
  if (flags.has('json')) {
2166
- write(JSON.stringify({ ...data, ...(eta !== undefined ? { eta } : {}) }));
2295
+ write(JSON.stringify({
2296
+ ...data,
2297
+ ...(eta !== undefined ? { eta } : {}),
2298
+ ...(phaseLine !== undefined ? { featureAdrLine: phaseLine } : {}),
2299
+ }));
2167
2300
  return 0;
2168
2301
  }
2169
- let line = `🎓 dz: ${data.patterns} patterns${data.usedPatterns !== undefined ? ` · ${data.usedPatterns} used` : ''} · 🧠 ${data.brainSources} sources`;
2302
+ const breakdown = data.patternBreakdown;
2303
+ let line = breakdown === undefined
2304
+ ? `🎓 dz: ${data.patterns} patterns`
2305
+ : `🎓 dz: ${data.patterns} (${breakdown.active} актив${breakdown.quarantined > 0
2306
+ ? ` · ${breakdown.quarantined} карантин${breakdown.attention ? ' ⚠' : ''}`
2307
+ : ''})${breakdown.tierDelta !== undefined ? ` ⚠ тиры Δ${breakdown.tierDelta}` : ''}`;
2308
+ if (data.storeHealth?.verdict === 'collapsed') {
2309
+ line += ` ⛔ ОБВАЛ: было ${data.storeHealth.previousMax ?? '?'} · dz store-guard --reset`;
2310
+ }
2311
+ else if (data.storeHealth?.verdict === 'cold-start-over-existing') {
2312
+ line += ` ⛔ СТОР ПУСТ: было ${data.storeHealth.previousMax ?? '?'} · восстановить из снимков ${data.storeHealth.snapshotPath ?? ''}`.trimEnd();
2313
+ }
2314
+ else if (data.storeHealth?.verdict === 'unreadable') {
2315
+ line += ` ⛔ СТОР НЕЧИТАЕМ${data.storeHealth.unreadableFiles !== undefined && data.storeHealth.unreadableFiles.length > 0
2316
+ ? `: ${data.storeHealth.unreadableFiles.join(', ')}` : ''}`;
2317
+ }
2318
+ else if (data.storeHealth?.verdict === 'source-changed') {
2319
+ line += ' ⚠ смена источника хранения';
2320
+ }
2321
+ line += `${data.usedPatterns !== undefined ? ` · ${data.usedPatterns} used` : ''} · 🧠 ${data.brainSources} sources`;
2170
2322
  const branch = statuslineGitBranch(projectRoot);
2171
2323
  if (branch !== undefined)
2172
2324
  line += ` · ⎇ ${branch}`;
2173
2325
  if (data.consolidatedAgeH !== undefined)
2174
2326
  line += ` · ⟳ ${data.consolidatedAgeH}h`;
2175
- // Live /feature-adr run in flight → PREPEND the pipeline learning segment to the base dz line.
2176
- if (fa !== undefined) {
2177
- // The producer marker reached data and arbitration in a previous round but not this label, so the bar asserted a pipeline that was not running.
2178
- if (fa.kind === 'loop') {
2179
- line = `🔁 loop ${fa.step} · ${line}`;
2180
- }
2181
- else {
2182
- line = `📐 feature-adr ${fa.step} · ${etaFragment !== undefined ? `${etaFragment} · ` : ''}🎓 ${fa.pool} pool · ↑${fa.recalled} used · +${fa.stored} new · ↻${fa.reinforced ?? 0} reinforced · ${line}`;
2183
- }
2327
+ // Live loop run in flight → PREPEND its segment to the base dz line (unchanged). A live
2328
+ // /feature-adr run no longer glues into line 1: its 📐 segment IS the second line (format B)
2329
+ // Claude Code renders every stdout line of a statusline command (fa-phase-statusline ADR-001 D1).
2330
+ if (fa !== undefined && fa.kind === 'loop') {
2331
+ line = `🔁 loop ${fa.step} · ${line}`;
2184
2332
  }
2185
2333
  write(line);
2334
+ // fa-phase-statusline ADR-001 D1: the phase panel moved to line 2 and TOOK main's ETA fragment with it. The move is
2335
+ // the point of format B (ADR-001 D1); dropping the estimate would have been a silent
2336
+ // regression of a feature `main` shipped while this branch was stranded, so it rides here
2337
+ // instead. A phase line that renders (fresh, non-terminal, non-loop slot) is the only gate.
2338
+ if (phaseLine !== undefined) {
2339
+ write(`${phaseLine}${etaFragment !== undefined ? ` · ${etaFragment}` : ''}`);
2340
+ }
2186
2341
  return 0;
2187
2342
  }
2188
2343
  catch {
@@ -2766,6 +2921,259 @@ function learningStoreLine(storeRoot, projectOption, target, verb) {
2766
2921
  const reason = teachReasonPhrase(target.reason);
2767
2922
  return storeLocationLine(describeStoreLocation(storeRoot, projectOption, target.store === 'global' ? 'global' : undefined), verb) + (reason ? ' [' + reason + ']' : '');
2768
2923
  }
2924
+ function inspectLearningStore(projectRoot) {
2925
+ const mark = readStoreMark(projectRoot);
2926
+ const rows = countLearningStoreRowsReadonly(projectRoot);
2927
+ return { mark, rows, health: checkStoreHealth({ projectRoot, ...rows, mark }) };
2928
+ }
2929
+ function shellQuote(value) {
2930
+ return `'${value.replace(/'/g, `'\\''`)}'`;
2931
+ }
2932
+ function storeGuardResetCommand(projectRoot) {
2933
+ return `dz store-guard --reset --project ${shellQuote(projectRoot)}`;
2934
+ }
2935
+ function lexicalSourceLines(rows) {
2936
+ return [
2937
+ ` lexical selected: ${rows.lexicalSourcePath} (${rows.lexicalSource}, ${rows.lexicalRows} rows)`,
2938
+ ...(rows.lexicalIgnoredSourcePath === undefined ? [] : [
2939
+ ` lexical ignored: ${rows.lexicalIgnoredSourcePath} (${rows.lexicalIgnoredRows} rows)`,
2940
+ ]),
2941
+ ];
2942
+ }
2943
+ function storeGuardRecoveryLines(projectRoot, mark, health, rows) {
2944
+ const snapshots = storeSnapshotPath(projectRoot);
2945
+ const markPath = storeGuardPath(projectRoot);
2946
+ let lexicalSnapshot;
2947
+ let vectorSnapshot = false;
2948
+ try {
2949
+ const names = existsSync(snapshots) ? readdirSync(snapshots) : [];
2950
+ const hasSqlite = names.some((name) => /^lexical\..+\.sqlite$/.test(name));
2951
+ const hasJsonl = names.some((name) => /^lexical\..+\.jsonl$/.test(name));
2952
+ const preferred = mark?.lexicalSource === 'sqlite' || mark?.lexicalSource === 'jsonl'
2953
+ ? mark.lexicalSource
2954
+ : rows?.lexicalSource;
2955
+ if (preferred === 'jsonl' && hasJsonl)
2956
+ lexicalSnapshot = 'jsonl';
2957
+ else if (preferred === 'sqlite' && hasSqlite)
2958
+ lexicalSnapshot = 'sqlite';
2959
+ else if (hasSqlite)
2960
+ lexicalSnapshot = 'sqlite';
2961
+ else if (hasJsonl)
2962
+ lexicalSnapshot = 'jsonl';
2963
+ vectorSnapshot = names.some((name) => /^vector\..+\.sqlite$/.test(name));
2964
+ }
2965
+ catch {
2966
+ lexicalSnapshot = undefined;
2967
+ vectorSnapshot = false;
2968
+ }
2969
+ const lines = [
2970
+ `dz store guard: REFUSED — ${health.reason}`,
2971
+ ` mark: ${markPath}`,
2972
+ ...(mark === undefined ? [] : [` recorded rows: lexical=${mark.lexicalMax} (${mark.lexicalSource}), vector=${mark.vectorMax}`]),
2973
+ ...(rows === undefined ? [] : lexicalSourceLines(rows)),
2974
+ ];
2975
+ if (lexicalSnapshot !== undefined && vectorSnapshot) {
2976
+ const lexicalDestination = lexicalSnapshot === 'sqlite'
2977
+ ? join(projectRoot, '.dz', 'memory', 'patterns.sqlite')
2978
+ : join(projectRoot, '.dz', 'patterns.jsonl');
2979
+ lines.push(` snapshots: ${snapshots}/`, ` restore: mkdir -p ${shellQuote(dirname(lexicalDestination))} && cp ${shellQuote(join(snapshots, `lexical.<timestamp>.${lexicalSnapshot}`))} ${shellQuote(lexicalDestination)} && cp ${shellQuote(join(snapshots, 'vector.<timestamp>.sqlite'))} ${shellQuote(join(projectRoot, '.dz', 'agentdb.db'))}`);
2980
+ }
2981
+ else {
2982
+ lines.push(` snapshots: none found in ${snapshots}/`, ` create one manually: scripts/dz-store-snapshot.sh --project ${shellQuote(projectRoot)}`);
2983
+ }
2984
+ lines.push(` accept current counts: ${storeGuardResetCommand(projectRoot)}`, ' continue intentionally: set DZ_ALLOW_COLD_START=1 or pass --allow-cold-start');
2985
+ return lines;
2986
+ }
2987
+ function observedRows(rows) {
2988
+ return typeof rows.lexicalRows === 'number' && typeof rows.vectorRows === 'number'
2989
+ ? { lexicalRows: rows.lexicalRows, vectorRows: rows.vectorRows, lexicalSource: rows.lexicalSource }
2990
+ : undefined;
2991
+ }
2992
+ /** Mark maintenance is diagnostic: the store operation already completed and must keep its exit code. */
2993
+ function refreshLearningStoreMark(projectRoot, writeErr, command, options = {}) {
2994
+ try {
2995
+ const rows = countLearningStoreRowsReadonly(projectRoot);
2996
+ const counts = observedRows(rows);
2997
+ if (counts === undefined) {
2998
+ writeErr(`⚠ dz store guard: ${options.reader ? 'reader observation' : 'store operation'} completed but the external mark was not updated — a store tier is unreadable`);
2999
+ return;
3000
+ }
3001
+ writeStoreMark(projectRoot, {
3002
+ ...counts,
3003
+ observedAt: new Date().toISOString(),
3004
+ command,
3005
+ }, options.reader ? { timeoutMs: 0 } : {});
3006
+ }
3007
+ catch (error) {
3008
+ if (options.reader && error instanceof NamedLockTimeoutError)
3009
+ return;
3010
+ writeErr(`⚠ dz store guard: ${options.reader ? 'reader observation' : 'store operation'} completed but the external mark could not be updated — ${error instanceof Error ? error.message : String(error)}`);
3011
+ }
3012
+ }
3013
+ function storeGuardResetReminder(projectRoot, writeErr, command) {
3014
+ try {
3015
+ const rows = countLearningStoreRowsReadonly(projectRoot);
3016
+ const mark = readStoreMark(projectRoot);
3017
+ writeErr(`⚠ DZ STORE GUARD — ${command}: store now lexical=${rows.lexicalRows}, vector=${rows.vectorRows}; maximum remains lexical=${mark?.lexicalMax ?? 'none'}, vector=${mark?.vectorMax ?? 'none'}; reconcile explicitly: ${storeGuardResetCommand(projectRoot)}`);
3018
+ for (const line of lexicalSourceLines(rows))
3019
+ writeErr(line);
3020
+ }
3021
+ catch (error) {
3022
+ writeErr(`⚠ DZ STORE GUARD — ${command}: store changed; inspect it and reconcile explicitly with ${storeGuardResetCommand(projectRoot)} (${error instanceof Error ? error.message : String(error)})`);
3023
+ }
3024
+ }
3025
+ /** Fail closed for store writers, except for an explicit per-process/per-command override. */
3026
+ function allowLearningStoreWrite(projectRoot, flags, writeErr, command) {
3027
+ let inspection;
3028
+ try {
3029
+ inspection = inspectLearningStore(projectRoot);
3030
+ }
3031
+ catch (error) {
3032
+ const health = {
3033
+ verdict: 'unreadable',
3034
+ reason: `cannot read the external mark (${error instanceof Error ? error.message : String(error)})`,
3035
+ };
3036
+ for (const line of storeGuardRecoveryLines(projectRoot, undefined, health))
3037
+ writeErr(line);
3038
+ return false;
3039
+ }
3040
+ if (inspection.health.verdict === 'no-mark' || inspection.health.verdict === 'ok') {
3041
+ // The successful write path records the resulting counts. Refreshing here as
3042
+ // well would emit the same telemetry failure twice when the external mark is
3043
+ // unavailable, and would receipt a source transition before the command's
3044
+ // own row had landed.
3045
+ return true;
3046
+ }
3047
+ if (inspection.health.verdict === 'source-changed') {
3048
+ const counts = observedRows(inspection.rows);
3049
+ if (counts === undefined)
3050
+ return false;
3051
+ writeErr(`⚠ DZ STORE GUARD WARNING — SOURCE CHANGED: ${inspection.health.reason}; ${storeGuardResetCommand(projectRoot)}`);
3052
+ for (const line of lexicalSourceLines(inspection.rows))
3053
+ writeErr(line);
3054
+ try {
3055
+ // Consume the single migration allowance BEFORE the store write. If the
3056
+ // following command fails, the safe result is a consumed allowance that
3057
+ // requires an explicit reset, never a silently reusable permission.
3058
+ writeStoreMark(projectRoot, { ...counts, observedAt: new Date().toISOString(), command }, {
3059
+ expectedPreviousLexicalSource: inspection.mark?.lexicalSource ?? 'unknown',
3060
+ });
3061
+ return true;
3062
+ }
3063
+ catch (error) {
3064
+ writeErr(`dz store guard: REFUSED — source-change allowance could not be recorded: ${error instanceof Error ? error.message : String(error)}`);
3065
+ return false;
3066
+ }
3067
+ }
3068
+ const allowed = process.env.DZ_ALLOW_COLD_START === '1' || flags.has('allow-cold-start');
3069
+ if (allowed) {
3070
+ const label = inspection.health.verdict.replaceAll('-', ' ').toUpperCase();
3071
+ writeErr(`⚠ DZ STORE GUARD WARNING — ${label}: ${inspection.health.reason}; explicit cold-start override accepted`);
3072
+ return true;
3073
+ }
3074
+ for (const line of storeGuardRecoveryLines(projectRoot, inspection.mark, inspection.health, inspection.rows))
3075
+ writeErr(line);
3076
+ return false;
3077
+ }
3078
+ /** Readers warn on damage and bootstrap/refresh a healthy non-empty store mark. */
3079
+ function warnLearningStoreRead(projectRoot, writeErr, command) {
3080
+ try {
3081
+ const { health, rows, mark } = inspectLearningStore(projectRoot);
3082
+ if (health.verdict === 'collapsed' || health.verdict === 'cold-start-over-existing' || health.verdict === 'unreadable'
3083
+ || health.verdict === 'source-changed') {
3084
+ writeErr(`⚠ DZ STORE GUARD WARNING — ${health.verdict.replaceAll('-', ' ').toUpperCase()}: ${health.reason}`);
3085
+ for (const line of lexicalSourceLines(rows))
3086
+ writeErr(line);
3087
+ return;
3088
+ }
3089
+ const counts = observedRows(rows);
3090
+ if (counts !== undefined && counts.lexicalRows + counts.vectorRows > 0
3091
+ && (mark === undefined || mark.lexicalLast !== counts.lexicalRows || mark.vectorLast !== counts.vectorRows
3092
+ || mark.lexicalSource !== counts.lexicalSource
3093
+ || mark.lexicalMax < counts.lexicalRows || mark.vectorMax < counts.vectorRows)) {
3094
+ refreshLearningStoreMark(projectRoot, writeErr, command, { reader: true });
3095
+ }
3096
+ }
3097
+ catch (error) {
3098
+ writeErr(`⚠ DZ STORE GUARD WARNING — external mark unreadable: ${error instanceof Error ? error.message : String(error)}`);
3099
+ }
3100
+ }
3101
+ async function cmdStoreGuard(options, flags, cwd, write, writeErr, stdinText, interactive) {
3102
+ const projectRoot = resolve(cwd, options.get('project') ?? '.');
3103
+ const path = storeGuardPath(projectRoot);
3104
+ const reset = flags.has('reset');
3105
+ const status = flags.has('status') || options.has('status');
3106
+ if (reset && status) {
3107
+ writeErr('dz store-guard: --status and --reset are mutually exclusive');
3108
+ return 2;
3109
+ }
3110
+ if (reset) {
3111
+ const rows = countLearningStoreRowsReadonly(projectRoot);
3112
+ const counts = observedRows(rows);
3113
+ if (counts === undefined) {
3114
+ writeErr(`dz store-guard: REFUSED — cannot reset from an unreadable store; mark: ${path}`);
3115
+ return 1;
3116
+ }
3117
+ try {
3118
+ const previous = readStoreMark(projectRoot);
3119
+ const beforeLexical = previous?.lexicalMax ?? counts.lexicalRows;
3120
+ const beforeVector = previous?.vectorMax ?? counts.vectorRows;
3121
+ writeErr('⚠ dz store-guard --reset: manual operator decision required; this lowers the recorded high-water evidence');
3122
+ writeErr(` old maximum: lexical=${beforeLexical}, vector=${beforeVector}`);
3123
+ writeErr(` new observed: lexical=${counts.lexicalRows} (${counts.lexicalSource}), vector=${counts.vectorRows}`);
3124
+ for (const line of lexicalSourceLines(rows))
3125
+ writeErr(line);
3126
+ let answer = stdinText?.trim().split(/\r?\n/, 1)[0]?.trim().toLowerCase() ?? '';
3127
+ if (!flags.has('yes') && answer === '' && interactive && process.stdin.isTTY) {
3128
+ const { createInterface } = await import('node:readline/promises');
3129
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
3130
+ try {
3131
+ answer = (await rl.question(' type yes to continue: ')).trim().toLowerCase();
3132
+ }
3133
+ finally {
3134
+ rl.close();
3135
+ }
3136
+ }
3137
+ if (!flags.has('yes') && !['y', 'yes', 'да'].includes(answer)) {
3138
+ writeErr(`dz store-guard: REFUSED — reset was not confirmed; re-run with --yes or answer yes`);
3139
+ return 1;
3140
+ }
3141
+ const current = countLearningStoreRowsReadonly(projectRoot);
3142
+ const currentCounts = observedRows(current);
3143
+ if (currentCounts === undefined || !isDeepStrictEqual(currentCounts, counts)) {
3144
+ writeErr('dz store-guard: REFUSED — store counts changed after confirmation; inspect and confirm again');
3145
+ return 1;
3146
+ }
3147
+ const mark = resetStoreMark(projectRoot, {
3148
+ ...counts,
3149
+ observedAt: new Date().toISOString(),
3150
+ command: 'dz store-guard --reset',
3151
+ });
3152
+ write(`dz store-guard: RESET — accepted lexical=${mark.lexicalMax}, vector=${mark.vectorMax}`);
3153
+ write(` mark: ${path}`);
3154
+ write(` receipt: ${mark.resetAt?.at} — ${mark.resetAt?.reason}`);
3155
+ return 0;
3156
+ }
3157
+ catch (error) {
3158
+ writeErr(`dz store-guard: reset failed — ${error instanceof Error ? error.message : String(error)}; mark: ${path}`);
3159
+ return 1;
3160
+ }
3161
+ }
3162
+ try {
3163
+ const inspection = inspectLearningStore(projectRoot);
3164
+ write(`dz store-guard: ${inspection.health.verdict.toUpperCase()} — ${inspection.health.reason}`);
3165
+ write(` mark: ${path}`);
3166
+ write(` current rows: lexical=${inspection.rows.lexicalRows}, vector=${inspection.rows.vectorRows}`);
3167
+ for (const line of lexicalSourceLines(inspection.rows))
3168
+ write(line);
3169
+ write(` recorded: ${inspection.mark === undefined ? 'none' : JSON.stringify(inspection.mark)}`);
3170
+ return 0;
3171
+ }
3172
+ catch (error) {
3173
+ writeErr(`dz store-guard: mark unreadable — ${error instanceof Error ? error.message : String(error)}; mark: ${path}`);
3174
+ return 1;
3175
+ }
3176
+ }
2769
3177
  async function runTeachGuardReinforcement(projectRoot, dzId, reward) {
2770
3178
  const backend = resolveLearningBackend(projectRoot);
2771
3179
  backend.addSample({ dzId, kind: 'reinforce', reward, ts: new Date().toISOString() });
@@ -2793,6 +3201,13 @@ async function cmdTeach(options, flags, cwd, write, writeErr = (line) => { conso
2793
3201
  // repo's own store holds 361 records written under that behaviour, and every other user's store
2794
3202
  // is the same. Only an explicit choice moves it.
2795
3203
  const { storeRoot, target: teachTarget } = resolved;
3204
+ const teachWillWrite = flags.has('harmonize')
3205
+ ? false
3206
+ : options.has('from-json')
3207
+ || (options.get('reinforce') ?? '').trim() !== ''
3208
+ || (options.get('_positional_0') ?? '').trim() !== '';
3209
+ if (teachWillWrite && !allowLearningStoreWrite(storeRoot, flags, writeErr, 'dz teach'))
3210
+ return 1;
2796
3211
  // The verb is per OUTCOME, not per command: a harmonize dry-run and a failed --reinforce READ
2797
3212
  // the store and change nothing, so saying "written" there is a false claim about what happened
2798
3213
  // (cross-family QE round 2, 2026-08-27).
@@ -2831,10 +3246,11 @@ async function cmdTeach(options, flags, cwd, write, writeErr = (line) => { conso
2831
3246
  // worse defect than the invisibility it was closing (measured live, cross-family QE round 2).
2832
3247
  if (!flags.has('json'))
2833
3248
  write(storeLine(flags.has('apply') ? 'written' : 'read'));
2834
- return runHarmonize(storeRoot, options, flags, write, {
3249
+ const code = await runHarmonize(storeRoot, options, flags, write, writeErr, {
2835
3250
  store: join(storeRoot, '.dz'),
2836
3251
  storeChosenBy: teachTarget.reason,
2837
3252
  });
3253
+ return code;
2838
3254
  }
2839
3255
  // Bulk import: `dz teach --from-json <file>` ingests a `dz recall --all --json`
2840
3256
  // export (an array of learned patterns) — the portable way to SHARE a learned
@@ -2932,6 +3348,8 @@ async function cmdTeach(options, flags, cwd, write, writeErr = (line) => { conso
2932
3348
  const report = await harmonizeVectorStore(storeRoot, {});
2933
3349
  write(` ℹ ${imported} imported — ${report.clusters.length} near-duplicate cluster(s): review with dz vector harmonize (dry-run); merge with dz vector harmonize --apply after backup`);
2934
3350
  }
3351
+ if (imported > 0)
3352
+ refreshLearningStoreMark(storeRoot, writeErr, 'dz teach --from-json');
2935
3353
  return 0;
2936
3354
  }
2937
3355
  const reinforce = options.get('reinforce');
@@ -2952,6 +3370,7 @@ async function cmdTeach(options, flags, cwd, write, writeErr = (line) => { conso
2952
3370
  if (clearedQ.cleared > 0)
2953
3371
  write(` ↳ promoted out of quarantine (mirror updated)`);
2954
3372
  write(storeLine('written'));
3373
+ refreshLearningStoreMark(storeRoot, writeErr, 'dz teach --reinforce');
2955
3374
  return 0;
2956
3375
  }
2957
3376
  // HIGH-fix: a no-match must NOT auto-teach the raw argument — callers pass dzIds or truncated
@@ -2999,6 +3418,7 @@ async function cmdTeach(options, flags, cwd, write, writeErr = (line) => { conso
2999
3418
  const clearedQ = clearAgentdbQuarantine(storeRoot, [verdict.dzId]);
3000
3419
  if (clearedQ.cleared > 0)
3001
3420
  write(' ↳ promoted out of quarantine (mirror updated)');
3421
+ refreshLearningStoreMark(storeRoot, writeErr, 'dz teach --guard');
3002
3422
  return 0;
3003
3423
  }
3004
3424
  write(`dz teach --guard: reinforce of ${verdict.dzId} did not flush (backend off or write failure) — teaching the lesson normally instead`);
@@ -3115,9 +3535,13 @@ async function cmdTeach(options, flags, cwd, write, writeErr = (line) => { conso
3115
3535
  }
3116
3536
  // The lexical write above is durable — the vector mirror is strictly best-effort (I-3).
3117
3537
  await emitMirrorQ(storeRoot, recordsToMirror, 'dz-teach', quarantineOn);
3538
+ if (stored.records.length > 0) {
3539
+ write(` ID: ${stored.records.map((record) => patternRecordId(record)).join(', ')}`);
3540
+ refreshLearningStoreMark(storeRoot, writeErr, 'dz teach');
3541
+ }
3118
3542
  return commandFailed ? 1 : 0;
3119
3543
  }
3120
- async function cmdConsolidate(options, flags, cwd, write) {
3544
+ async function cmdConsolidate(options, flags, cwd, write, writeErr) {
3121
3545
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
3122
3546
  const sessionsDirOpt = options.get('sessions-dir');
3123
3547
  const pruneNoise = flags.has('prune-noise');
@@ -3141,6 +3565,8 @@ async function cmdConsolidate(options, flags, cwd, write) {
3141
3565
  write(`dz consolidate --prune-quarantine: removed ${res.removed} expired quarantined lesson(s)`);
3142
3566
  if (res.snapshot !== undefined)
3143
3567
  write(` snapshot: ${res.snapshot}`);
3568
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz consolidate --prune-quarantine --apply');
3569
+ storeGuardResetReminder(projectRoot, writeErr, 'dz consolidate --prune-quarantine --apply');
3144
3570
  return 0;
3145
3571
  }
3146
3572
  // --prune-noise: RETRO-PRUNE legacy noise (tool telemetry + system-wrapper "responses") from
@@ -3250,6 +3676,10 @@ async function cmdConsolidate(options, flags, cwd, write) {
3250
3676
  }
3251
3677
  }
3252
3678
  catch { /* best-effort — the ranking is advisory, never fails the consolidate */ }
3679
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz consolidate');
3680
+ if (pruneNoise && applyPrune) {
3681
+ storeGuardResetReminder(projectRoot, writeErr, 'dz consolidate --prune-noise --apply');
3682
+ }
3253
3683
  return 0;
3254
3684
  }
3255
3685
  function recallUsagePatternRefs(projectRoot) {
@@ -3360,7 +3790,7 @@ function cmdRecallUsage(options, flags, projectRoot, write) {
3360
3790
  * DRY-RUN BY DEFAULT, and it snapshots before deleting: `.dz/` is git-ignored and unversioned, so a
3361
3791
  * mistaken id is unrecoverable. Use `dz recall --all --json` to find ids.
3362
3792
  */
3363
- async function cmdRecallForget(options, flags, projectRoot, write) {
3793
+ async function cmdRecallForget(options, flags, projectRoot, write, writeErr) {
3364
3794
  const raw = options.get('forget') ?? '';
3365
3795
  const ids = new Set(raw.split(',').map((s) => s.trim()).filter((s) => s !== ''));
3366
3796
  if (ids.size === 0) {
@@ -3386,7 +3816,7 @@ async function cmdRecallForget(options, flags, projectRoot, write) {
3386
3816
  write(`dz recall --forget: DRY RUN — ${found.length} record(s) would be removed. Re-run with --apply.`);
3387
3817
  return 0;
3388
3818
  }
3389
- const dest = join(projectRoot, '.dz', `patterns-pre-forget-${Date.now()}.json`);
3819
+ const dest = join(storeSnapshotPath(projectRoot), `forget-${Date.now()}.json`);
3390
3820
  const snap = snapshotStore(projectRoot, dest);
3391
3821
  if (snap.error !== undefined) {
3392
3822
  write(`dz recall --forget: snapshot failed (${snap.error}) — nothing removed; the store is not versioned`);
@@ -3398,6 +3828,8 @@ async function cmdRecallForget(options, flags, projectRoot, write) {
3398
3828
  if (result.error !== undefined)
3399
3829
  write(` ⚠ ${result.error}`);
3400
3830
  write(' the vector mirror still holds them — run `dz vector reindex` to resync');
3831
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz recall --forget --apply');
3832
+ storeGuardResetReminder(projectRoot, writeErr, 'dz recall --forget --apply');
3401
3833
  return 0;
3402
3834
  }
3403
3835
  /**
@@ -3477,12 +3909,17 @@ async function cmdRecallPromote(options, flags, projectRoot, write) {
3477
3909
  }
3478
3910
  async function cmdRecall(options, flags, cwd, write, writeErr, classMatcher) {
3479
3911
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
3912
+ warnLearningStoreRead(projectRoot, writeErr, 'dz recall');
3913
+ const globalRootForGuard = globalStoreRoot();
3914
+ if (!sameStore(projectRoot, globalRootForGuard) && existsSync(join(globalRootForGuard, '.dz', 'memory'))) {
3915
+ warnLearningStoreRead(globalRootForGuard, writeErr, 'dz recall');
3916
+ }
3480
3917
  const asJson = flags.has('json');
3481
3918
  const all = flags.has('all');
3482
3919
  if (flags.has('usage'))
3483
3920
  return cmdRecallUsage(options, flags, projectRoot, write);
3484
3921
  if (options.has('forget'))
3485
- return cmdRecallForget(options, flags, projectRoot, write);
3922
+ return cmdRecallForget(options, flags, projectRoot, write, writeErr);
3486
3923
  if (options.has('promote'))
3487
3924
  return cmdRecallPromote(options, flags, projectRoot, write);
3488
3925
  // --all: dump the entire learned store (backend-agnostic, via loadStorePatternsSync).
@@ -4047,7 +4484,7 @@ function renderHarmonize(report, write) {
4047
4484
  * and `dz teach --harmonize` — ONE implementation, no bespoke second path (QR-6). Guards (AC-6):
4048
4485
  * `--apply` + `--dry-run` together is rejected; `--threshold` must be in `(0, 1]`; no flag ⇒ dry-run.
4049
4486
  */
4050
- async function runHarmonize(projectRoot, options, flags, write,
4487
+ async function runHarmonize(projectRoot, options, flags, write, writeErr,
4051
4488
  /**
4052
4489
  * Where this harmonize is pointed and what chose it. Under `--json` the human store line is
4053
4490
  * suppressed to keep stdout ONE document, so the destination has to travel INSIDE that document
@@ -4070,6 +4507,10 @@ storeAnnotation) {
4070
4507
  }
4071
4508
  }
4072
4509
  const report = await harmonizeVectorStore(projectRoot, { apply, ...(threshold !== undefined ? { threshold } : {}) });
4510
+ if (apply && report.error === undefined) {
4511
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz vector harmonize --apply');
4512
+ storeGuardResetReminder(projectRoot, writeErr, 'dz vector harmonize --apply');
4513
+ }
4073
4514
  if (flags.has('json')) {
4074
4515
  write(JSON.stringify(storeAnnotation !== undefined ? { ...report, ...storeAnnotation } : report));
4075
4516
  return report.error !== undefined ? 1 : 0;
@@ -4077,7 +4518,7 @@ storeAnnotation) {
4077
4518
  renderHarmonize(report, write);
4078
4519
  return report.error !== undefined ? 1 : 0;
4079
4520
  }
4080
- async function cmdVector(options, flags, cwd, write) {
4521
+ async function cmdVector(options, flags, cwd, write, writeErr) {
4081
4522
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
4082
4523
  const sub = options.get('_positional_0');
4083
4524
  if (sub === 'status') {
@@ -4131,6 +4572,10 @@ async function cmdVector(options, flags, cwd, write) {
4131
4572
  if (sub === 'reindex') {
4132
4573
  const report = await reindexVectorStore(projectRoot);
4133
4574
  if (flags.has('json')) {
4575
+ if (report.error === undefined) {
4576
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz vector reindex');
4577
+ storeGuardResetReminder(projectRoot, writeErr, 'dz vector reindex');
4578
+ }
4134
4579
  write(JSON.stringify(report));
4135
4580
  return report.error !== undefined ? 1 : 0;
4136
4581
  }
@@ -4150,6 +4595,8 @@ async function cmdVector(options, flags, cwd, write) {
4150
4595
  if (report.staleTaskTypes.includes('book-knowledge'))
4151
4596
  write(' run \`dz brain reindex\` to rebuild the brain\'s book vectors');
4152
4597
  }
4598
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz vector reindex');
4599
+ storeGuardResetReminder(projectRoot, writeErr, 'dz vector reindex');
4153
4600
  return 0;
4154
4601
  }
4155
4602
  if (sub === 'export') {
@@ -4201,7 +4648,7 @@ async function cmdVector(options, flags, cwd, write) {
4201
4648
  // harmonize (alias: dz teach --harmonize) — SEMANTIC dedup of the learned store, NON-DESTRUCTIVE:
4202
4649
  // dry-run by default (previews clusters, writes nothing); --apply drops after a restorable backup.
4203
4650
  if (sub === 'harmonize') {
4204
- return runHarmonize(projectRoot, options, flags, write);
4651
+ return runHarmonize(projectRoot, options, flags, write, writeErr);
4205
4652
  }
4206
4653
  // import <file.rvf> — the missing HALF of the RVF cycle: UPSERT-BY-dzId, never overwrites.
4207
4654
  if (sub === 'import') {
@@ -4212,6 +4659,8 @@ async function cmdVector(options, flags, cwd, write) {
4212
4659
  }
4213
4660
  const report = await importRvfCheckpoint(projectRoot, resolve(cwd, src), {});
4214
4661
  if (flags.has('json')) {
4662
+ if (report.error === undefined)
4663
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz vector import');
4215
4664
  write(JSON.stringify(report));
4216
4665
  return report.error !== undefined ? 1 : 0;
4217
4666
  }
@@ -4224,6 +4673,7 @@ async function cmdVector(options, flags, cwd, write) {
4224
4673
  if (report.skippedOrphans > 0) {
4225
4674
  write(' ↳ orphan vectors have no local pattern — import the text first: dz teach --from-json <recall-export.json>, then re-run dz vector import');
4226
4675
  }
4676
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz vector import');
4227
4677
  return 0;
4228
4678
  }
4229
4679
  write('dz vector — semantic (vector) tier of the learned-pattern store');
@@ -5679,6 +6129,18 @@ function cmdPublish(options, flags, cwd, write) {
5679
6129
  return 1;
5680
6130
  }
5681
6131
  }
6132
+ const filterStr = options.get('filter');
6133
+ // SAFETY: trim + drop empty segments (mirrors --select at the top of cmdInit).
6134
+ // Parse before the guard pre-flight so its packed-secret scan uses the SAME scoped package set
6135
+ // that publishPackages receives below; an empty resulting list remains an explicit error.
6136
+ let filter;
6137
+ if (filterStr !== undefined) {
6138
+ filter = filterStr.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
6139
+ if (filter.length === 0) {
6140
+ write('dz publish: --filter requires a non-empty comma-separated list of package-name substrings');
6141
+ return 1;
6142
+ }
6143
+ }
5682
6144
  // dz guard pre-flight (ADR-002 option A): publish is the most dangerous, least-reversible self-mutation, so
5683
6145
  // it ALWAYS runs the declarative guard first. A HARD violation refuses the publish; `--no-guard "<reason>"`
5684
6146
  // is the logged escape hatch (the override lands in .dz/guard-audit.jsonl — visible, never silent).
@@ -5693,7 +6155,7 @@ function cmdPublish(options, flags, cwd, write) {
5693
6155
  write('dz publish: --no-guard requires a reason (it is logged): --no-guard "hotfix, guard re-run after"');
5694
6156
  return 1;
5695
6157
  }
5696
- const guardResult = runGuardEvaluation(guardRoot, 'publish', undefined, noGuard);
6158
+ const guardResult = runGuardEvaluation(guardRoot, 'publish', undefined, noGuard, filter);
5697
6159
  if (guardResult.verdict === 'block' && noGuard === undefined) {
5698
6160
  write('dz publish: ✗ BLOCKED by dz guard (HARD invariant violated):');
5699
6161
  for (const v of guardResult.violations.filter((x) => x.severity === 'hard'))
@@ -5738,21 +6200,6 @@ function cmdPublish(options, flags, cwd, write) {
5738
6200
  }
5739
6201
  const claimCheckOpt = claimCheckRaw ?? 'warn';
5740
6202
  const bumpOnly = flags.has('bump-only');
5741
- const filterStr = options.get('filter');
5742
- // SAFETY: trim + drop empty segments (mirrors --select at the top of cmdInit).
5743
- // Without this, `--filter ""` (e.g. an unset shell var) or a stray comma yields
5744
- // [''] / ['', 'core'], and publishPackages matches with name.includes(''), which
5745
- // is true for EVERY package — silently turning a scoped publish into a
5746
- // whole-monorepo publish. An empty resulting list is an explicit error, never
5747
- // "match all".
5748
- let filter;
5749
- if (filterStr !== undefined) {
5750
- filter = filterStr.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
5751
- if (filter.length === 0) {
5752
- write('dz publish: --filter requires a non-empty comma-separated list of package-name substrings');
5753
- return 1;
5754
- }
5755
- }
5756
6203
  // SAFETY: dry-run is the DEFAULT. A real publish requires an EXPLICIT opt-in
5757
6204
  // via --yes, --confirm, or --no-dry-run. Without one, we never bump or publish.
5758
6205
  const wantsLive = flags.has('yes') || flags.has('confirm') || flags.has('no-dry-run');
@@ -5945,6 +6392,14 @@ function cmdPublish(options, flags, cwd, write) {
5945
6392
  if (pkg.claimCheck && pkg.claimCheck.findings > 0 && pkg.status !== 'error') {
5946
6393
  write(` ⚠ claim-check: ${pkg.claimCheck.findings} finding(s) (${pkg.claimCheck.high} high) in README.md`);
5947
6394
  }
6395
+ // A dry run stops before build/sign/pack, so it says NOTHING about the gates below that line.
6396
+ // Printing what it did not check is what keeps a clean preview from reading as a clean publish
6397
+ // (measured 2026-09-02: a clean dry run preceded a RED real gate).
6398
+ if (pkg.notVerified && pkg.notVerified.length > 0) {
6399
+ write(` ⓘ холостой прогон НЕ проверял (${pkg.notVerified.length}):`);
6400
+ for (const item of pkg.notVerified)
6401
+ write(` · ${item}`);
6402
+ }
5948
6403
  }
5949
6404
  return report.errors > 0 ? 1 : 0;
5950
6405
  }
@@ -7667,7 +8122,19 @@ function cmdAgentsSync(options, flags, cwd, write, writeErr) {
7667
8122
  writeErr(`dz agents-sync: DRIFT — ${drifted.length} stale/missing section(s); ${effect}`);
7668
8123
  for (const finding of drifted)
7669
8124
  writeErr(` ${finding.id}: ${finding.file} (${finding.status})`);
7670
- if (drifted.some((finding) => finding.id === 'dz:policies')) {
8125
+ const unregistered = drifted.filter((finding) => finding.status === 'unregistered-section');
8126
+ if (unregistered.length > 0) {
8127
+ // ПОДСКАЗКА, ВЕДУЩАЯ НЕ ТУДА, ХУЖЕ ОТСУТСТВУЮЩЕЙ. Повторный `dz agents-sync` эту находку
8128
+ // НЕ лечит: реестр POLICY_SOURCES ведётся руками, и секция, не вписанная в него, не
8129
+ // попадёт в проекцию сколько ни синхронизируй. Раньше здесь печаталась общая подсказка —
8130
+ // читатель прогнал бы её и снова увидел ту же ошибку.
8131
+ writeErr('→ heal with: объяви секцию в POLICY_SOURCES (packages/@dzhechkov/harness-core/src/agents-policy.ts):');
8132
+ for (const finding of unregistered) {
8133
+ writeErr(` { id: '${finding.id}', file: '${finding.file}', heading: '…', why: '…', operativeClause: '…' }`);
8134
+ }
8135
+ writeErr(' затем: dz agents-sync');
8136
+ }
8137
+ else if (drifted.some((finding) => finding.id === 'dz:policies')) {
7671
8138
  writeErr('→ heal with: repair duplicate/unmatched dz:policies markers, then run dz agents-sync');
7672
8139
  }
7673
8140
  else {
@@ -7752,7 +8219,9 @@ const DEFAULT_STORE_CAP = 5000;
7752
8219
  * the rule reports nothing for them — a pre-flight must never become a filesystem sweep.
7753
8220
  */
7754
8221
  const MAX_STUB_SCAN_FILES = 400;
7755
- /** Read the optional `.dz/guard.json` `{ rules?: [...], storeCap?: number, stubWaivers?: [...] }`. Missing/broken ⇒ defaults. */
8222
+ /** Maximum packed-file size read by the publish secret scan. */
8223
+ const SECRET_SCAN_MAX_BYTES = 512 * 1024;
8224
+ /** Read the optional `.dz/guard.json` — `{ rules?, storeCap?, stubWaivers?, secretWaivers? }`. Missing/broken ⇒ defaults. */
7756
8225
  function loadGuardConfig(root) {
7757
8226
  const p = join(root, '.dz', 'guard.json');
7758
8227
  if (!existsSync(p))
@@ -7789,6 +8258,54 @@ function gatherReadmeCounts(root) {
7789
8258
  // (target repo without sitedoc — missing-evidence contract). But a file that EXISTS and no longer
7790
8259
  // matches its anchored pattern emits a MISMATCH pair (a: -1) — silent non-extraction is the exact
7791
8260
  // disease this contour cures (AM-1 applies to the guard path too, not only the CI test).
8261
+ // ЗНАЧКИ ПРОТИВ ДЕРЕВА, а не только README против README (бэклог 9cb30764).
8262
+ //
8263
+ // Прежде правило сверяло только числа МЕЖДУ документами: два согласованных документа могли
8264
+ // хором утверждать одно и то же неверное число, и правило молчало. Значок «пакетов: 52» стоял
8265
+ // при 55 публикуемых на диске — ИЗМЕРЕНО 2026-09-03. Меню обещает 32 блюда, официант
8266
+ // перечисляет 30, кухня готовит 38, и никто в ресторане не знает правду.
8267
+ //
8268
+ // Сверяются только числа, ВЫЧИСЛИМЫЕ ИЗ ДЕРЕВА. Значок «опубликовано в npm» сюда НЕ входит и
8269
+ // это сказано вслух: его источник — реестр, а не рабочая копия, и пара, которая делает вид, что
8270
+ // проверила его, была бы хуже отсутствующей.
8271
+ const badge = (s, name) => {
8272
+ const m = s.match(new RegExp(`img\\.shields\\.io/badge/${name}-(\\d+)`));
8273
+ return m && m[1] ? Number(m[1]) : null;
8274
+ };
8275
+ const publishablePackages = (() => {
8276
+ const dir = join(root, 'packages', '@dzhechkov');
8277
+ if (!existsSync(dir))
8278
+ return null;
8279
+ let n = 0;
8280
+ for (const name of readdirSync(dir)) {
8281
+ const pj = join(dir, name, 'package.json');
8282
+ if (!existsSync(pj))
8283
+ continue;
8284
+ try {
8285
+ const j = JSON.parse(readFileSync(pj, 'utf8'));
8286
+ if (j.private !== true)
8287
+ n += 1;
8288
+ }
8289
+ catch { /* нечитаемый манифест — не считается ни в одну сторону */ }
8290
+ }
8291
+ return n;
8292
+ })();
8293
+ const pkgBadge = badge(rootMd, 'packages');
8294
+ if (pkgBadge !== null && publishablePackages !== null) {
8295
+ pairs.push({ label: 'packages (root badge vs publishable package.json on disk)', a: pkgBadge, b: publishablePackages });
8296
+ }
8297
+ const presetBadge = badge(rootMd, 'presets');
8298
+ if (presetBadge !== null) {
8299
+ pairs.push({ label: 'presets (root badge vs PRESET_NAMES in the build)', a: presetBadge, b: PRESET_NAMES.length });
8300
+ }
8301
+ const targetBadge = badge(rootMd, 'targets');
8302
+ if (targetBadge !== null) {
8303
+ pairs.push({ label: 'targets (root badge vs TARGET_NAMES in the build)', a: targetBadge, b: TARGET_NAMES.length });
8304
+ }
8305
+ const cmdBadge = badge(rootMd, 'CLI%20commands');
8306
+ if (cmdBadge !== null && cliAll !== null) {
8307
+ pairs.push({ label: 'commands (root badge vs cli All Commands)', a: cmdBadge, b: cliAll });
8308
+ }
7792
8309
  const sitePair = (rel, re, label) => {
7793
8310
  if (cliAll === null || !existsSync(join(root, rel)))
7794
8311
  return;
@@ -8224,8 +8741,9 @@ function gatherVolumeShadowFacts(root, packages) {
8224
8741
  };
8225
8742
  }
8226
8743
  /** Gather the facts one op needs. All I/O is best-effort — a missing signal skips its rule, never crashes. */
8227
- function gatherGuardFacts(op, root, text, storeCap) {
8744
+ function gatherGuardFacts(op, root, text, storeCap, publishFilter) {
8228
8745
  const facts = { op };
8746
+ const publishPackageRoots = [];
8229
8747
  if (op === 'publish') {
8230
8748
  // Advisory I/O: unreadable telemetry or fed state is absence of evidence, never a fabricated
8231
8749
  // stale finding and never a publish blocker.
@@ -8372,6 +8890,11 @@ function gatherGuardFacts(op, root, text, storeCap) {
8372
8890
  for (const m of manifests)
8373
8891
  if (m.name && typeof m.version === 'string')
8374
8892
  versionByName.set(m.name, m.version);
8893
+ publishPackageRoots.push(...located
8894
+ .filter(({ dir, m }) => m.private !== true && (publishFilter === undefined
8895
+ || publishFilter.length === 0
8896
+ || publishFilter.some((filter) => (m.name ?? '').includes(filter) || dir.includes(filter))))
8897
+ .map(({ dir }) => dir));
8375
8898
  const pnpmWorkspace = existsSync(join(root, 'pnpm-workspace.yaml'));
8376
8899
  const packages = [];
8377
8900
  for (const m of manifests) {
@@ -8386,6 +8909,95 @@ function gatherGuardFacts(op, root, text, storeCap) {
8386
8909
  packages.push({ name: m.name ?? '(unnamed)', deps });
8387
8910
  }
8388
8911
  facts['packages'] = packages;
8912
+ // sibling-dep-protocol: сырые спеки, БЕЗ подстановки версии. Подставленная версия выглядела бы
8913
+ // как обычный диапазон, и правило потеряло бы ровно то, что проверяет.
8914
+ const siblingDeps = [];
8915
+ for (const m of manifests) {
8916
+ if (m.private === true)
8917
+ continue;
8918
+ const fields = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
8919
+ for (const field of fields) {
8920
+ const table = m[field];
8921
+ if (typeof table !== 'object' || table === null)
8922
+ continue;
8923
+ for (const [dep, spec] of Object.entries(table)) {
8924
+ if (!dep.startsWith('@dzhechkov/') || typeof spec !== 'string')
8925
+ continue;
8926
+ siblingDeps.push({ name: m.name ?? '(unnamed)', field, dep, spec });
8927
+ }
8928
+ }
8929
+ }
8930
+ facts['siblingDeps'] = siblingDeps;
8931
+ // plugin-manifest-audit: каждый `.claude-plugin/plugin.json` в дереве. Обход ограничен по
8932
+ // глубине и не заходит в node_modules/dist — чужие манифесты не наши, и краснеть на них
8933
+ // значило бы отчитываться о том, чего мы не публикуем.
8934
+ const pluginManifests = [];
8935
+ const walkPlugins = (dir, depth) => {
8936
+ if (depth > 4)
8937
+ return;
8938
+ let entries;
8939
+ try {
8940
+ entries = readdirSync(dir, { withFileTypes: true });
8941
+ }
8942
+ catch {
8943
+ return;
8944
+ }
8945
+ for (const e of entries) {
8946
+ // `out/` — СГЕНЕРИРОВАННОЕ публичное зеркало: те же манифесты, скопированные. Дефект в нём
8947
+ // есть дефект генератора, и он уже сообщается по источнику; вторая копия только удвоила бы
8948
+ // одну и ту же находку.
8949
+ if (!e.isDirectory() || e.name === 'node_modules' || e.name === 'dist' || e.name === 'out')
8950
+ continue;
8951
+ const full = join(dir, e.name);
8952
+ if (e.name === '.claude-plugin') {
8953
+ const manifest = join(full, 'plugin.json');
8954
+ if (!existsSync(manifest))
8955
+ continue;
8956
+ try {
8957
+ const j = JSON.parse(readFileSync(manifest, 'utf8'));
8958
+ const pick = (k) => (typeof j[k] === 'string' ? j[k] : undefined);
8959
+ // Состав навыков — ОБЕ стороны инвентаризации, и ТОЛЬКО для коробки ОДНОГО ПАКЕТА.
8960
+ //
8961
+ // Корневая витрина сюда НЕ входит, и это не упрощение: её состав собирается из всего
8962
+ // монорепозитория через реестр, «что лежит на складе» для неё — не обход одного дерева,
8963
+ // а весь реестр, и ровно это уже проверяет `marketplace-parity` регенерацией. Первая
8964
+ // редакция этой проверки обошла корень с ограничением глубины и выдала 27 ЛОЖНЫХ
8965
+ // «объявлено, но не найдено» — навыки лежали глубже границы обхода (ИЗМЕРЕНО 2026-09-04,
8966
+ // поймано до коммита прогоном стража на этом же дереве).
8967
+ //
8968
+ // Сравниваются ПУТИ, как их объявил манифест, а не имена: два навыка с одинаковым
8969
+ // именем в разных подкаталогах — законная вещь, и сведение к имени их бы склеило.
8970
+ const boxRoot = dirname(full);
8971
+ const isRepoRoot = resolve(boxRoot) === resolve(root);
8972
+ const declaredSkills = Array.isArray(j['skills']) && !isRepoRoot
8973
+ ? j['skills'].filter((x) => typeof x === 'string')
8974
+ .map((rel) => rel.replace(/^\.\//, '').replace(/\/+$/, '')).filter(Boolean)
8975
+ : undefined;
8976
+ const skillsOnDisk = declaredSkills === undefined ? undefined : findSkillDirs(boxRoot);
8977
+ pluginManifests.push({
8978
+ path: relative(root, manifest),
8979
+ ...(pick('name') !== undefined ? { name: pick('name') } : {}),
8980
+ ...(pick('version') !== undefined ? { version: pick('version') } : {}),
8981
+ ...(pick('description') !== undefined ? { description: pick('description') } : {}),
8982
+ ...(declaredSkills !== undefined ? { declaredSkills } : {}),
8983
+ ...(skillsOnDisk !== undefined ? { skillsOnDisk } : {}),
8984
+ });
8985
+ }
8986
+ catch (error) {
8987
+ pluginManifests.push({
8988
+ path: relative(root, manifest),
8989
+ parseError: (error instanceof Error ? error.message : String(error)).replace(/\s+/g, ' ').slice(0, 200),
8990
+ });
8991
+ }
8992
+ continue;
8993
+ }
8994
+ if (e.name.startsWith('.'))
8995
+ continue;
8996
+ walkPlugins(full, depth + 1);
8997
+ }
8998
+ };
8999
+ walkPlugins(root, 0);
9000
+ facts['pluginManifests'] = pluginManifests;
8389
9001
  facts['volume'] = gatherVolumeShadowFacts(root, located.map(({ dir, m }) => ({
8390
9002
  dir,
8391
9003
  name: m.name ?? dir,
@@ -8420,9 +9032,57 @@ function gatherGuardFacts(op, root, text, storeCap) {
8420
9032
  }
8421
9033
  catch { /* unreadable tree — the rule reports nothing rather than inventing a violation */ }
8422
9034
  try {
8423
- facts['drift'] = sweepSkillDrift(root, { scope: 'installs', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
9035
+ facts['drift'] = sweepSkillDrift(root, { scope: DRIFT_SWEEP_SCOPE, allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
8424
9036
  }
8425
9037
  catch { /* skip */ }
9038
+ // backlog-covers-features: каталоги фич, дата их ПОЯВЛЕНИЯ В ИСТОРИИ (не mtime — его двигает
9039
+ // любой посторонний процесс), оговорки из README фичи и тексты записей бэклога. Базовая дата
9040
+ // делает правило зелёным на приходе: 336 существующих каталогов заведены до правила.
9041
+ // Нечитаемое дерево ⇒ факт НЕ выставляется ⇒ правило молчит, а не выдумывает вердикт.
9042
+ try {
9043
+ const featDir = join(root, 'features');
9044
+ if (existsSync(featDir)) {
9045
+ const slugs = readdirSync(featDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
9046
+ const features = slugs.map((slug) => {
9047
+ let createdIso = '';
9048
+ try {
9049
+ createdIso = execSync(`git log --diff-filter=A --format=%aI -1 -- ${JSON.stringify('features/' + slug)}`, { cwd: root, encoding: 'utf-8' }).trim().split('\n').filter(Boolean).pop() ?? '';
9050
+ }
9051
+ catch { /* нет в истории — функция засчитает как новый, это верный дефолт */ }
9052
+ let waiver;
9053
+ for (const f of ['README.md', '07_code_changes/change_manifest.md']) {
9054
+ try {
9055
+ const m = readFileSync(join(featDir, slug, f), 'utf-8')
9056
+ .match(/^\s*Backlog:\s*не заведено\s*[—-]\s*(.+)$/m);
9057
+ if (m && m[1] && m[1].trim() !== '') {
9058
+ waiver = m[1].trim();
9059
+ break;
9060
+ }
9061
+ }
9062
+ catch { /* нет файла — не оговорка */ }
9063
+ }
9064
+ return { slug, createdIso, waiver };
9065
+ });
9066
+ const backlogTexts = [];
9067
+ try {
9068
+ for (const line of readFileSync(join(root, '.dz', 'backlog', 'ideas.jsonl'), 'utf-8').split('\n')) {
9069
+ if (line.trim() === '')
9070
+ continue;
9071
+ try {
9072
+ const o = JSON.parse(line);
9073
+ if (typeof o.text === 'string')
9074
+ backlogTexts.push(o.text);
9075
+ }
9076
+ catch { /* рваная строка */ }
9077
+ }
9078
+ }
9079
+ catch { /* стора нет */ }
9080
+ if (backlogTexts.length > 0) {
9081
+ facts['featureBacklog'] = { baseline: BACKLOG_COVERAGE_BASELINE, features, backlogTexts };
9082
+ }
9083
+ }
9084
+ }
9085
+ catch { /* нечитаемо — правило молчит */ }
8426
9086
  facts['counts'] = gatherReadmeCounts(root);
8427
9087
  // readme-first: from the WORKING-TREE diff (publishes happen pre-commit here), per package: does the
8428
9088
  // change set contain its package.json (the version-bump signal) without its README.md?
@@ -8617,16 +9277,61 @@ function gatherGuardFacts(op, root, text, storeCap) {
8617
9277
  catch { /* not a git repo — every template rule stays silent (fail-open) */ }
8618
9278
  // no-stubs config waivers: `.dz/guard.json` `stubWaivers: [{path, reason}]` — path-keyed, reason
8619
9279
  // MANDATORY (the feature-adr-setup --guards shape; the pure checker refuses a reasonless entry).
8620
- const stubWaivers = loadGuardConfig(root).stubWaivers;
9280
+ const guardConfig = loadGuardConfig(root);
9281
+ const stubWaivers = guardConfig.stubWaivers;
8621
9282
  if (Array.isArray(stubWaivers))
8622
9283
  facts['stubWaivers'] = stubWaivers;
9284
+ const secretWaivers = guardConfig.secretWaivers;
9285
+ if (Array.isArray(secretWaivers))
9286
+ facts['secretWaivers'] = secretWaivers;
8623
9287
  }
8624
9288
  if (op === 'consolidate') {
8625
9289
  try {
8626
- facts['drift'] = sweepSkillDrift(root, { scope: 'installs', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
9290
+ facts['drift'] = sweepSkillDrift(root, { scope: DRIFT_SWEEP_SCOPE, allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
8627
9291
  }
8628
9292
  catch { /* skip */ }
8629
9293
  }
9294
+ if (op === 'publish') {
9295
+ const secretTargets = [];
9296
+ let skipped = 0;
9297
+ for (const dir of publishPackageRoots) {
9298
+ const packageRoot = join(root, dir);
9299
+ let packed;
9300
+ try {
9301
+ packed = listPackFiles(packageRoot);
9302
+ }
9303
+ catch {
9304
+ skipped++;
9305
+ continue;
9306
+ }
9307
+ for (const rel of packed) {
9308
+ const absolute = join(packageRoot, rel);
9309
+ try {
9310
+ const stat = lstatSync(absolute);
9311
+ if (!stat.isFile() || stat.size > SECRET_SCAN_MAX_BYTES) {
9312
+ skipped++;
9313
+ continue;
9314
+ }
9315
+ const content = readFileSync(absolute);
9316
+ if (content.subarray(0, 8 * 1024).includes(0)) {
9317
+ skipped++;
9318
+ continue;
9319
+ }
9320
+ secretTargets.push({
9321
+ label: relative(root, absolute).split(sep).join('/'),
9322
+ text: content.toString('utf8'),
9323
+ });
9324
+ }
9325
+ catch {
9326
+ skipped++;
9327
+ }
9328
+ }
9329
+ }
9330
+ if (secretTargets.length > 0)
9331
+ facts['secretTargets'] = secretTargets;
9332
+ if (skipped > 0)
9333
+ facts['secretScan'] = { skipped };
9334
+ }
8630
9335
  if (op === 'teach' || op === 'consolidate') {
8631
9336
  if (op === 'teach' && text)
8632
9337
  facts['secretTargets'] = [{ label: 'lesson', text }];
@@ -8646,13 +9351,13 @@ function gatherGuardFacts(op, root, text, storeCap) {
8646
9351
  * shared by `dz guard check` and the `dz publish` pre-flight (ADR-002 option A) so they can never disagree.
8647
9352
  * `overrideReason` (when the caller forces through a block) is logged, never silent.
8648
9353
  */
8649
- function runGuardEvaluation(root, op, text, overrideReason) {
9354
+ function runGuardEvaluation(root, op, text, overrideReason, publishFilter) {
8650
9355
  const cfg = loadGuardConfig(root);
8651
9356
  // Number.isFinite, not just > 0: a config `storeCap: 1e400` parses to Infinity, passes `> 0`, and would
8652
9357
  // silently DISABLE the cap (count <= Infinity always). Non-finite ⇒ fall back to the default.
8653
9358
  const storeCap = typeof cfg.storeCap === 'number' && Number.isFinite(cfg.storeCap) && cfg.storeCap > 0 ? cfg.storeCap : DEFAULT_STORE_CAP;
8654
9359
  const rules = resolveRules(Array.isArray(cfg.rules) ? cfg.rules : undefined);
8655
- const facts = gatherGuardFacts(op, root, text, storeCap);
9360
+ const facts = gatherGuardFacts(op, root, text, storeCap, publishFilter);
8656
9361
  const result = evaluateGuard(facts, rules);
8657
9362
  // audit (append-only). ts is real time here (a CLI, not the sandboxed workflow).
8658
9363
  try {
@@ -9488,17 +10193,57 @@ async function cmdMrRakes(options, flags, cwd, write) {
9488
10193
  * --threshold N drill threshold (default 2 — anti-noise: a first-seen rake accrues, never drills)
9489
10194
  * --no-teach drill only; do NOT write the store (skip the agent side)
9490
10195
  * --project <dir> pin the teach ledger
9491
- * --install-hook print the opt-in SessionEnd hook to add (non-destructive)
10196
+ * --install-hook print the opt-in hook set to add (non-destructive): Stop scan-tail +
10197
+ * PreCompact/SessionEnd full retro (feature narrated-error-must-be-taught)
10198
+ * --scan-tail per-turn Stop-hook mode: incremental admission-debt scan, O(new bytes) —
10199
+ * writes/clears .dz/retro-pending.json; no ledger, no teach, no git subprocess
10200
+ * --transcript <p> the transcript --scan-tail must read. Without it the Stop hook's own stdin
10201
+ * payload (`transcript_path`) is used; with neither, the scan REFUSES
10202
+ * (NOT-ESTABLISHED) rather than guessing the newest file on disk
9492
10203
  */
9493
- async function cmdRetro(options, flags, cwd, write) {
10204
+ async function cmdRetro(options, flags, cwd, write, readStdin = () => '') {
10205
+ if (flags.has('scan-tail')) {
10206
+ // Per-turn primary detector (ADR-001 D2). Cost budget IS the design: no `git rev-parse`
10207
+ // subprocess (hooks run with cwd = project root; CLAUDE_PROJECT_DIR pins it), no store open,
10208
+ // O(new bytes) via the persisted offset. Always exit 0 — a Stop hook must never fail a turn.
10209
+ const root = process.env['CLAUDE_PROJECT_DIR'] ?? cwd;
10210
+ // WHICH transcript. Round 3, P1-3: this used to fall back to `findLatestTranscript(root)`, so with
10211
+ // several sessions and their subagents alive at once it scanned whichever file had the newest
10212
+ // mtime — routinely another session's, advancing that session's offset and never seeing this
10213
+ // turn's admission. The Stop hook hands the exact path on stdin; with no path from any source the
10214
+ // answer is a stated refusal, never a guess. Still exit 0: a Stop hook must never fail a turn.
10215
+ const picked = resolveScanTailTranscript({
10216
+ flag: options.get('transcript'),
10217
+ positional: options.get('_positional_0'),
10218
+ stdin: readStdin(),
10219
+ });
10220
+ if (picked.path === null) {
10221
+ const reason = picked.reason ?? 'no transcript path';
10222
+ if (flags.has('json'))
10223
+ write(JSON.stringify({ status: 'not-established', source: 'none', reason, scannedBytes: 0, offset: 0 }));
10224
+ else
10225
+ write(`retro scan-tail: NOT-ESTABLISHED — ${reason}. Wire the hook as \`dz retro --scan-tail\` (Claude Code pipes the payload on stdin) or pass \`--transcript <path>\`.`);
10226
+ return 0;
10227
+ }
10228
+ const outcome = runRetroTailScan(join(root, '.dz'), picked.path);
10229
+ if (flags.has('json'))
10230
+ write(JSON.stringify({ ...outcome, source: picked.source }));
10231
+ else if (outcome.status === 'pending')
10232
+ write(`retro scan-tail: unpaid admission — .dz/retro-pending.json armed («${(outcome.snippet ?? '').slice(0, 60)}…»)`);
10233
+ return 0;
10234
+ }
9494
10235
  let repoRoot = cwd;
9495
10236
  try {
9496
10237
  repoRoot = execSync('git rev-parse --show-toplevel', { cwd, encoding: 'utf-8' }).trim() || cwd;
9497
10238
  }
9498
10239
  catch { /* not git */ }
9499
10240
  if (flags.has('install-hook')) {
9500
- write('Add this opt-in SessionEnd hook to .claude/settings.json (runs a retro when a session ends):');
9501
- write(JSON.stringify({ hooks: { SessionEnd: [{ hooks: [{ type: 'command', command: 'dz retro' }] }] } }, null, 2));
10241
+ write('Add these opt-in hooks to .claude/settings.json (per-turn debt scan + retro at compaction AND session end — PreCompact covers the crash/disconnect sessions SessionEnd never sees):');
10242
+ write(JSON.stringify({ hooks: {
10243
+ Stop: [{ hooks: [{ type: 'command', command: 'dz retro --scan-tail', timeout: 10000, continueOnError: true }] }],
10244
+ PreCompact: [{ hooks: [{ type: 'command', command: 'dz retro', timeout: 60000, continueOnError: true }] }],
10245
+ SessionEnd: [{ hooks: [{ type: 'command', command: 'dz retro', timeout: 60000, continueOnError: true }] }],
10246
+ } }, null, 2));
9502
10247
  return 0;
9503
10248
  }
9504
10249
  const transcript = options.get('_positional_0') ?? findLatestTranscript(repoRoot);
@@ -9761,6 +10506,50 @@ function cmdChallenge(options, flags, cwd, write) {
9761
10506
  * decide (dz's rule — a false gate kills trust). Exit code is 0 on a clean run regardless of verdict; 2 only on
9762
10507
  * a usage/setup error, so a caller distinguishes "gate ran" from "gate could not run".
9763
10508
  */
10509
+ /**
10510
+ * Есть ли в этом каталоге НЕЗАКОММИЧЕННЫЕ правки. Это и отличает «фича ещё в рабочем дереве»
10511
+ * (тогда `HEAD` — законная предфичевая база) от «фича уже закоммичена» (тогда `HEAD` её содержит).
10512
+ *
10513
+ * Не удалось спросить git — возвращается null, и вызывающий обязан считать положение НЕ
10514
+ * УСТАНОВЛЕННЫМ, а не выбрать удобный ответ.
10515
+ */
10516
+ /**
10517
+ * Каталоги с `SKILL.md` внутри коробки ОДНОГО пакета — то, что РЕАЛЬНО лежит на складе.
10518
+ * Возвращаются ПУТИ относительно коробки, как их объявляет манифест, а не имена.
10519
+ */
10520
+ function findSkillDirs(boxRoot) {
10521
+ const found = new Set();
10522
+ const walk = (dir, depth) => {
10523
+ if (depth > 4)
10524
+ return;
10525
+ let entries;
10526
+ try {
10527
+ entries = readdirSync(dir, { withFileTypes: true });
10528
+ }
10529
+ catch {
10530
+ return;
10531
+ }
10532
+ for (const e of entries) {
10533
+ if (!e.isDirectory() || e.name === 'node_modules' || e.name === 'dist' || e.name.startsWith('.'))
10534
+ continue;
10535
+ const full = join(dir, e.name);
10536
+ if (existsSync(join(full, 'SKILL.md')))
10537
+ found.add(relative(boxRoot, full));
10538
+ walk(full, depth + 1);
10539
+ }
10540
+ };
10541
+ walk(boxRoot, 0);
10542
+ return [...found];
10543
+ }
10544
+ function hasUncommittedChangesIn(repoRoot, dir) {
10545
+ try {
10546
+ const out = execSync(`git status --porcelain -- ${JSON.stringify(dir)}`, { cwd: repoRoot, encoding: 'utf-8' });
10547
+ return out.split('\n').some((line) => line.trim() !== '');
10548
+ }
10549
+ catch {
10550
+ return null;
10551
+ }
10552
+ }
9764
10553
  function cmdDiscriminationCheck(options, flags, cwd, write) {
9765
10554
  let repoRoot = cwd;
9766
10555
  try {
@@ -9774,7 +10563,22 @@ function cmdDiscriminationCheck(options, flags, cwd, write) {
9774
10563
  }
9775
10564
  const nameFilter = options.get('name');
9776
10565
  const propertyTests = testArg.split(',').map((s) => s.trim()).filter(Boolean).map((file) => nameFilter !== undefined && nameFilter.trim() !== '' ? { file, name: nameFilter.trim() } : { file });
9777
- const baseRef = options.get('base') ?? 'HEAD';
10566
+ /**
10567
+ * УМОЛЧАНИЕ БАЗЫ РАЗЛИЧАЕТ ДВА РАЗНЫХ ПОЛОЖЕНИЯ, потому что они и правда разные.
10568
+ *
10569
+ * В штатном ходе конвейера правка Шага 7 ЕЩЁ НЕ ЗАКОММИЧЕНА, и тогда `HEAD` — настоящая
10570
+ * предфичевая база; так конвейер и зовёт гейт (`--base HEAD`, причина записана в его тексте).
10571
+ *
10572
+ * Но если фича УЖЕ ЗАКОММИЧЕНА, `HEAD` её содержит, и гейт сравнивает фичу С САМОЙ СОБОЙ.
10573
+ * ИЗМЕРЕНО 2026-09-04: такой прогон дал уверенное `NON_DISCRIMINATING` с советом «усилить тест»
10574
+ * на тестах, которые дискриминируют; тот же прогон с верной базой дал `DISCRIMINATES_VIA_ERROR`.
10575
+ * Находка выглядела как утверждение О ТЕСТАХ, и автор пошёл бы чинить исправное.
10576
+ *
10577
+ * Различить эти положения можно ДЕТЕРМИНИРОВАННО: есть ли незакоммиченные правки в пакете, чьи
10578
+ * тесты названы. Есть — `HEAD` законен и используется как раньше. Нет — база не установлена, и
10579
+ * гейт ОТКАЗЫВАЕТСЯ (exit 3), вместо того чтобы измерять относительно самого себя.
10580
+ */
10581
+ const explicitBase = options.get('base');
9778
10582
  const runnerOpt = options.get('runner');
9779
10583
  // R11: a hung runner is a loud non-answer, never a pass. Same default + parse shape as mutation-gate.
9780
10584
  const timeoutOpt = Number(options.get('timeout') ?? '300000');
@@ -9819,9 +10623,34 @@ function cmdDiscriminationCheck(options, flags, cwd, write) {
9819
10623
  // The pure half's path sanitation expects a REPO-RELATIVE package dir ('.'-rooted), not an
9820
10624
  // absolute one — an absolute path is refused as unsafe-package-dir by design.
9821
10625
  const packageDirRel = relative(repoRoot, packageDir) || '.';
10626
+ // Умолчание базы решается ЗДЕСЬ, потому что только здесь известен пакет, чьи тесты названы.
10627
+ let baseRef;
10628
+ if (explicitBase !== undefined && explicitBase.trim() !== '') {
10629
+ baseRef = explicitBase.trim();
10630
+ }
10631
+ else {
10632
+ const dirty = hasUncommittedChangesIn(repoRoot, packageDirRel);
10633
+ if (dirty !== true) {
10634
+ write('dz discrimination-check: NOT-ESTABLISHED — предфичевая база не установлена.');
10635
+ write(dirty === null
10636
+ ? ` Не удалось спросить git о состоянии ${packageDirRel}; выбирать удобный ответ вместо этого нельзя.`
10637
+ : ` В ${packageDirRel} нет незакоммиченных правок, значит фича УЖЕ в HEAD, и сравнение шло бы с самой собой.`);
10638
+ write(' Гейт сравнивает поведение ДО и ПОСЛЕ фичи; без базы сравнивать не с чем, а HEAD здесь');
10639
+ write(' дал бы уверенное NON_DISCRIMINATING на исправных тестах (ИЗМЕРЕНО 2026-09-04).');
10640
+ write(' Передайте --base <коммит перед фичей>, например `<sha коммита фичи>^`.');
10641
+ return 3;
10642
+ }
10643
+ // Штатный ход конвейера: правка Шага 7 ещё в рабочем дереве, HEAD — настоящая предфичевая база.
10644
+ baseRef = 'HEAD';
10645
+ write(`dz discrimination-check: база не задана; в ${packageDirRel} есть незакоммиченные правки, беру HEAD как предфичевую базу.`);
10646
+ }
10647
+ // Провенанс базы едет в квитанцию вместе с самой базой: «явно указано» — утверждение о действии
10648
+ // человека, и писать его для HEAD, выбранного инструментом, значит подделывать происхождение
10649
+ // доказательства, на которое сошлются позже.
10650
+ const baseRefSupplied = explicitBase !== undefined && explicitBase.trim() !== '';
9822
10651
  const planInput = runnerOpt !== undefined
9823
- ? { baseRef, propertyTests, runner: runnerOpt, packageTestScript, packageDevDependencies, packageDir: packageDirRel }
9824
- : { baseRef, propertyTests, packageTestScript, packageDevDependencies, packageDir: packageDirRel };
10652
+ ? { baseRef, baseRefSupplied, propertyTests, runner: runnerOpt, packageTestScript, packageDevDependencies, packageDir: packageDirRel }
10653
+ : { baseRef, baseRefSupplied, propertyTests, packageTestScript, packageDevDependencies, packageDir: packageDirRel };
9825
10654
  const plan = planDiscriminationCheck(planInput);
9826
10655
  if (!plan.runnable) {
9827
10656
  // QE-2 (instrument-honesty, MEDIUM): a runner REFUSE used to be reported through the generic
@@ -11804,12 +12633,30 @@ function nameCheckScan(repoRoot) {
11804
12633
  // Command names come from the dispatcher AND from the help block: a name that dispatches but
11805
12634
  // is undocumented is still taken, and so is the reverse.
11806
12635
  if (f.name === 'cli.ts') {
11807
- for (const c of dispatchedCommandsIn(text))
11808
- commands.add(c);
11809
- const help = /^\s{2}dz ([a-z][a-z0-9-]*)/gm;
11810
- for (let m = help.exec(text); m !== null; m = help.exec(text))
11811
- if (m[1] !== undefined)
11812
- commands.add(m[1]);
12636
+ // ONE enumeration, every consumer derives (ADR-001, feature command-count-triad). This
12637
+ // scan's question is "is the name TAKEN?", so taken = dispatched ∪ documented, which is
12638
+ // legitimately LARGER than the canonical command count — but it must be the SAME parse
12639
+ // the layer-1 parity test uses, not a second private regex that agrees by coincidence.
12640
+ // The any-indent `dispatchedCommandsIn` fallback stays for a cli.ts WITHOUT a main
12641
+ // `switch (command)` (none in this workspace today): a partial sweep would answer "free"
12642
+ // about a taken name, and that is the one answer this command may never give.
12643
+ let mainSwitchParsed = false;
12644
+ try {
12645
+ for (const c of dispatchedCommands(text))
12646
+ commands.add(c);
12647
+ for (const c of documentedCommands(text))
12648
+ commands.add(c);
12649
+ mainSwitchParsed = true;
12650
+ }
12651
+ catch { /* no main switch here — fall back to the broad regexes below */ }
12652
+ if (!mainSwitchParsed) {
12653
+ for (const c of dispatchedCommandsIn(text))
12654
+ commands.add(c);
12655
+ const help = /^\s{2}dz ([a-z][a-z0-9-]*)/gm;
12656
+ for (let m = help.exec(text); m !== null; m = help.exec(text))
12657
+ if (m[1] !== undefined)
12658
+ commands.add(m[1]);
12659
+ }
11813
12660
  }
11814
12661
  }
11815
12662
  }
@@ -11824,6 +12671,75 @@ function nameCheckScan(repoRoot) {
11824
12671
  return { commands: new Set(), modules: new Map(), exports: new Map(), scanFailed: true };
11825
12672
  return { commands, modules, exports: exportsFound, scanned: { packages, files, exports: exportsFound.size, commands: commands.size } };
11826
12673
  }
12674
+ /**
12675
+ * `dz brief-check <файл>` — проверить бриф роя на контракт вывода (ADR-001 swarm-brief-output-contract).
12676
+ *
12677
+ * Разбирает объявления брифа как ДАННЫЕ и отказывает поимённо: «бриф неверен» не говорит автору,
12678
+ * что чинить, поэтому каждое нарушение называет ключ и причину.
12679
+ *
12680
+ * ЧЕСТНЫЙ ПРЕДЕЛ печатается ВМЕСТЕ С ЗЕЛЁНЫМ ответом: проверено, что бриф ОБЪЯВИЛ каталог и
12681
+ * единицы, а не что агент им последует. Зелёная проверка, читаемая как гарантия поведения, хуже
12682
+ * её отсутствия.
12683
+ */
12684
+ function cmdBriefCheck(options, flags, cwd, write) {
12685
+ const json = flags.has('json');
12686
+ /**
12687
+ * ВЕТКА «ПРОВЕРИТЬ НЕ УДАЛОСЬ» ТОЖЕ ОБЯЗАНА ОТВЕТИТЬ JSON-ом (находка 11).
12688
+ *
12689
+ * `--json` печатал человеческую строку на несуществующем файле, и потребитель, читающий вывод как
12690
+ * JSON, получал ошибку разбора вместо структурного «не проверено». Признак `checked` — тот же
12691
+ * трихотомический вердикт, что и коды выхода, только для машины: не «бриф плох», а «мы про него
12692
+ * ничего не установили».
12693
+ */
12694
+ const unchecked = (reason, detail) => {
12695
+ if (json)
12696
+ write(JSON.stringify({ ok: false, checked: false, reason, detail }));
12697
+ else
12698
+ write(detail);
12699
+ return 2;
12700
+ };
12701
+ // Только позиционный аргумент: `--file` был необъявленным псевдонимом, и страж дрейфа флагов
12702
+ // справедливо на него указал — лишняя поверхность, которой нет в справке.
12703
+ const file = options.get('_positional_0');
12704
+ if (file === undefined || file.trim() === '') {
12705
+ const code = unchecked('no-file', 'dz brief-check: name the brief file — dz brief-check <file> [--json]');
12706
+ if (!json)
12707
+ write(' A brief must declare: ' + SWARM_BRIEF_CONTRACT.map((c) => c.key).join(', '));
12708
+ return code;
12709
+ }
12710
+ let text;
12711
+ try {
12712
+ text = readFileSync(resolve(cwd, file), 'utf-8');
12713
+ }
12714
+ catch {
12715
+ // Нечитаемый файл — НЕ «бриф плох»: мы про него ничего не установили. Отдельный код выхода,
12716
+ // чтобы отказ прибора не смешивался с отказом брифа.
12717
+ return unchecked('unreadable', `dz brief-check: cannot read ${visibleText(file)}`);
12718
+ }
12719
+ const result = checkSwarmBrief(text);
12720
+ if (json) {
12721
+ // `checked: true` — вторая половина того же различителя: потребитель отличает «проверено и
12722
+ // отвергнуто» от «проверить не удалось» полем, а не отсутствием поля.
12723
+ write(JSON.stringify({ ...result, checked: true }));
12724
+ return result.ok ? 0 : 1;
12725
+ }
12726
+ if (result.ok) {
12727
+ // ЗНАЧЕНИЯ ИЗ БРИФА ОБЕЗВРЕЖИВАЮТСЯ И В ЗЕЛЁНОЙ СТРОКЕ (находка 10). Отказ их уже обезвредил,
12728
+ // но подделывается ровно эта строка: управляющая последовательность в имени каталога стирает
12729
+ // предыдущий вывод и печатает поверх него подделку.
12730
+ write(`dz brief-check: OK — dir ${visibleText(result.outputDir ?? '')}, ${result.units.length} unit(s), assembly "${visibleText(result.assemblyUnit ?? '')}"`);
12731
+ write(' LIMIT: this verifies the brief DECLARED the contract, not that the agent will follow it —');
12732
+ write(' only comparing the directory against the unit list on an orchestrator tick can show that.');
12733
+ write(' A filled-in template and an unedited one both pass: the parse cannot tell them apart.');
12734
+ return 0;
12735
+ }
12736
+ write(`dz brief-check: REFUSED — ${result.violations.length} violation(s)`);
12737
+ // Ядро уже обезвредило значения в причинах; повтор на слое печати — не суеверие, а граница:
12738
+ // печатающий слой не обязан знать, кто именно из его источников уже почистил текст.
12739
+ for (const v of result.violations)
12740
+ write(` ${v.rule}: ${visibleText(v.detail)}`);
12741
+ return 1;
12742
+ }
11827
12743
  function cmdNameCheck(options, flags, cwd, write) {
11828
12744
  const repoRoot = resolve(options.get('project') ?? cwd);
11829
12745
  const json = flags.has('json');
@@ -12754,12 +13670,21 @@ function cmdAmendmentCheck(options, flags, cwd, write) {
12754
13670
  // Paths in an amendment row are repo-relative, so they resolve against the repo root — not
12755
13671
  // against the feature directory, and not against wherever the caller happened to stand.
12756
13672
  const resolutions = resolveAmendments(rows, { readFile: (rel) => readOr(resolve(cwd, rel)) });
13673
+ // A document that opens `## Amendments` twice cannot have its first heading answer for the
13674
+ // rest (Codex round 6, P2). Counted per document and taken at its worst — one contradictory
13675
+ // input is enough to make the run inconclusive.
13676
+ const sectionCount = Math.max(ideation === null ? 0 : amendmentSectionCount(ideation), plan === null ? 0 : amendmentSectionCount(plan));
12757
13677
  const decision = decideAmendmentOutcome({
12758
13678
  sectionPresent,
12759
13679
  rows,
12760
13680
  resolutions,
12761
13681
  planSaysNone: plan !== null && planSaysNoAmendments(plan),
12762
13682
  missingFromPlan,
13683
+ sectionCount,
13684
+ // Fail-closed: measured on the document the rows would have come from (the plan when it has
13685
+ // a section, otherwise the ideation report).
13686
+ ambiguity: (plan !== null ? amendmentDeclarationAmbiguity(plan) : null)
13687
+ ?? (ideation !== null ? amendmentDeclarationAmbiguity(ideation) : null),
12763
13688
  });
12764
13689
  return { slug, decision, resolutions };
12765
13690
  };
@@ -15011,7 +15936,7 @@ function cmdDeliveryCheck(options, flags, cwd, write) {
15011
15936
  /* backlog — the Smart Backlog idea pipeline (feature smart-backlog) */
15012
15937
  /* ------------------------------------------------------------------ */
15013
15938
  /** Thin dispatcher — ALL logic lives in harness-core/src/backlog.ts (05 architecture: handlers stay dumb). */
15014
- async function cmdBacklog(options, flags, cwd, write) {
15939
+ async function cmdBacklog(options, flags, cwd, write, writeErr) {
15015
15940
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
15016
15941
  const json = flags.has('json');
15017
15942
  const sub = options.get('_positional_0');
@@ -15029,6 +15954,8 @@ async function cmdBacklog(options, flags, cwd, write) {
15029
15954
  if (eff.adjusted && !json && eff.note !== undefined)
15030
15955
  write(`dz backlog: ${eff.note}`);
15031
15956
  const dryRun = flags.has('dry-run');
15957
+ if (!dryRun && !allowLearningStoreWrite(projectRoot, flags, writeErr, 'dz backlog add'))
15958
+ return 1;
15032
15959
  // Embed-form migration (register-inflation fix): v1 vectors are FULL-TEXT embeds, v2 queries are
15033
15960
  // bounded excerpts — comparing across the forms is a query-vs-row space split. Re-mirror once
15034
15961
  // (idempotent upsert), before the dedup search. Dry-run writes nothing, so it only WARNS.
@@ -15059,6 +15986,7 @@ async function cmdBacklog(options, flags, cwd, write) {
15059
15986
  const ideas = readIdeas(projectRoot);
15060
15987
  const match = ideas.find((i) => i.id === verdict.matchedId);
15061
15988
  let absorbErr;
15989
+ let didWrite = false;
15062
15990
  if (!dryRun && match !== undefined) {
15063
15991
  const snap = snapshotIdeas(projectRoot, join(projectRoot, '.dz', 'backlog', `ideas.pre-merge-${Date.now()}.jsonl`));
15064
15992
  if (snap.error !== undefined)
@@ -15075,7 +16003,10 @@ async function cmdBacklog(options, flags, cwd, write) {
15075
16003
  }).error;
15076
16004
  match.uses += 1;
15077
16005
  writeIdeas(projectRoot, ideas);
16006
+ didWrite = true;
15078
16007
  }
16008
+ if (didWrite)
16009
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog add');
15079
16010
  if (json)
15080
16011
  write(JSON.stringify({ action: 'duplicate', matchedId: verdict.matchedId, cosine: verdict.cosine, ...(verdict.containment !== undefined ? { containment: verdict.containment } : {}), ...(verdict.subsetMatch === true ? { subsetMatch: true } : {}), ...(topMatch !== undefined ? { topMatch } : {}), ...(eff.note !== undefined ? { effortNote: eff.note } : {}), ...(dryRun ? {} : { absorbedLogged: absorbErr === undefined, ...(absorbErr !== undefined ? { absorbedLogError: absorbErr } : {}) }), exitCode: 0 }, null, 2));
15081
16012
  else {
@@ -15137,6 +16068,7 @@ async function cmdBacklog(options, flags, cwd, write) {
15137
16068
  ideas.push(rec);
15138
16069
  writeIdeas(projectRoot, ideas);
15139
16070
  const mirror = await mirrorIdeaVector(projectRoot, rec); // best-effort — never blocks capture
16071
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog add');
15140
16072
  if (json)
15141
16073
  write(JSON.stringify({ action: verdict.action, idea: rec, related: verdict.relatedIds, ...(verdict.demoted !== undefined ? { demoted: verdict.demoted } : {}), ...(topMatch !== undefined ? { topMatch } : {}), ...(eff.note !== undefined ? { effortNote: eff.note } : {}), gitignore: ignore, exitCode: 0 }, null, 2));
15142
16074
  else {
@@ -15336,8 +16268,18 @@ async function cmdBacklog(options, flags, cwd, write) {
15336
16268
  if (commitId !== undefined) {
15337
16269
  // Validated above (safe id + known id) BEFORE any early return.
15338
16270
  const idx = ideas.findIndex((i) => i.id === commitId);
16271
+ // ОТМЕТКА ВРЕМЕНИ И ЖУРНАЛ ставятся ЗДЕСЬ, а не «где-нибудь потом».
16272
+ // Измерено 2026-09-02: `grep -c statusTs cli.ts` давал НОЛЬ — оба пути смены статуса в этом
16273
+ // файле меняли поле и не отмечали, когда. Отсюда 22 терминальные записи без отметки и
16274
+ // невычислимое «сколько идея пробыла в работе».
16275
+ const spinFrom = ideas[idx].status;
16276
+ const spinTs = new Date().toISOString();
15339
16277
  ideas[idx].status = 'in-progress';
16278
+ ideas[idx].statusTs = spinTs;
15340
16279
  writeIdeas(projectRoot, ideas);
16280
+ if (!appendTransition(projectRoot, { id: commitId, from: spinFrom, to: 'in-progress', ts: spinTs, by: 'backlog roulette --commit' })) {
16281
+ write('dz backlog: переход НЕ записан в журнал — наблюдение потеряно (сам статус изменён)');
16282
+ }
15341
16283
  pick = ideas[idx];
15342
16284
  committed = true;
15343
16285
  }
@@ -15412,6 +16354,7 @@ async function cmdBacklog(options, flags, cwd, write) {
15412
16354
  }
15413
16355
  else
15414
16356
  embed = 'stale';
16357
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog edit');
15415
16358
  }
15416
16359
  if (json) {
15417
16360
  write(JSON.stringify({ verb: 'edit', ...report, embed, exitCode: report.ok ? (embed === 'stale' ? 1 : 0) : 1 }, null, 2));
@@ -15446,9 +16389,15 @@ async function cmdBacklog(options, flags, cwd, write) {
15446
16389
  const goalMap = readGoalMap(projectRoot);
15447
16390
  const related = ideas.filter((i) => rec.relatedIds.includes(i.id));
15448
16391
  const staging = stageEnrichment(projectRoot, rec, related, goalMap);
16392
+ const enrichFrom = rec.status;
16393
+ const enrichTs = new Date().toISOString();
15449
16394
  rec.status = 'enriched';
16395
+ rec.statusTs = enrichTs;
15450
16396
  rec.enrichedPath = `features/${staging.slug}`;
15451
16397
  writeIdeas(projectRoot, ideas);
16398
+ if (!appendTransition(projectRoot, { id: rec.id, from: enrichFrom, to: 'enriched', ts: enrichTs, by: 'backlog enrich' })) {
16399
+ write('dz backlog: переход НЕ записан в журнал — наблюдение потеряно (сам статус изменён)');
16400
+ }
15452
16401
  if (json)
15453
16402
  write(JSON.stringify({ slug: staging.slug, scaffoldPath: staging.scaffoldPath, handoff: 'idea2prd-manual', exitCode: 0 }, null, 2));
15454
16403
  else {
@@ -15493,6 +16442,10 @@ async function cmdBacklog(options, flags, cwd, write) {
15493
16442
  else if (form.action === 'deferred' && !json)
15494
16443
  write(`dz backlog: ⚠ embed-form migration deferred (${form.error ?? 'unknown error'})`);
15495
16444
  const report = await harmonizeBacklog(projectRoot, { apply, ...(thr !== undefined ? { threshold: Number(thr) } : {}) });
16445
+ if (apply) {
16446
+ refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog harmonize --apply');
16447
+ storeGuardResetReminder(projectRoot, writeErr, 'dz backlog harmonize --apply');
16448
+ }
15496
16449
  if (json) {
15497
16450
  write(JSON.stringify({ ...report, exitCode: 0 }, null, 2));
15498
16451
  return 0;
@@ -16357,15 +17310,17 @@ export async function runCli(argv, io = {}) {
16357
17310
  case 'teach':
16358
17311
  return await cmdTeach(options, flags, cwd, write, writeErr, io.interactive ?? process.stdout.isTTY === true, io.teachGuardRunner ?? teachGuard, io.teachReinforceRunner ?? runTeachGuardReinforcement);
16359
17312
  case 'consolidate':
16360
- return await cmdConsolidate(options, flags, cwd, write);
17313
+ return await cmdConsolidate(options, flags, cwd, write, writeErr);
16361
17314
  case 'recall':
16362
17315
  return await cmdRecall(options, flags, cwd, write, writeErr, io.classMatcher);
16363
17316
  case 'vector':
16364
- return await cmdVector(options, flags, cwd, write);
17317
+ return await cmdVector(options, flags, cwd, write, writeErr);
16365
17318
  case 'brain':
16366
17319
  return await cmdBrain(options, flags, cwd, write, readStdin);
16367
17320
  case 'statusline':
16368
- return cmdStatusline(options, flags, cwd, write, readStdin);
17321
+ return cmdStatusline(options, flags, cwd, write, readStdin, writeErr);
17322
+ case 'store-guard':
17323
+ return await cmdStoreGuard(options, flags, cwd, write, writeErr, io.stdin, io.interactive ?? process.stdin.isTTY === true);
16369
17324
  case 'usage':
16370
17325
  return cmdUsage(options, optionLists, flags, cwd, write);
16371
17326
  case 'chain':
@@ -16433,7 +17388,7 @@ export async function runCli(argv, io = {}) {
16433
17388
  case 'mr-rakes':
16434
17389
  return await cmdMrRakes(options, flags, cwd, write);
16435
17390
  case 'retro':
16436
- return await cmdRetro(options, flags, cwd, write);
17391
+ return await cmdRetro(options, flags, cwd, write, readStdin);
16437
17392
  case 'feature-adr-setup':
16438
17393
  return cmdFeatureAdrSetup(options, flags, cwd, write, writeErr);
16439
17394
  case 'challenge':
@@ -16480,6 +17435,8 @@ export async function runCli(argv, io = {}) {
16480
17435
  return cmdTgPost(options, flags, cwd, write);
16481
17436
  case 'name-check':
16482
17437
  return cmdNameCheck(options, flags, cwd, write);
17438
+ case 'brief-check':
17439
+ return cmdBriefCheck(options, flags, cwd, write);
16483
17440
  case 'provenance-check':
16484
17441
  return cmdProvenanceCheck(options, flags, cwd, write);
16485
17442
  case 'feature-adr-record':
@@ -16497,7 +17454,7 @@ export async function runCli(argv, io = {}) {
16497
17454
  case 'qe-bridge':
16498
17455
  return await cmdQeBridge(options, flags, cwd, write);
16499
17456
  case 'backlog':
16500
- return await cmdBacklog(options, flags, cwd, write);
17457
+ return await cmdBacklog(options, flags, cwd, write, writeErr);
16501
17458
  case 'routing':
16502
17459
  return cmdRouting(options, flags, cwd, write);
16503
17460
  case 'bto-optimize':