@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/.dz-manifest.json +42 -22
- package/LICENSE +13 -0
- package/README.md +266 -16
- package/dist/boolean-flags.d.ts.map +1 -1
- package/dist/boolean-flags.js +3 -0
- package/dist/boolean-flags.js.map +1 -1
- package/dist/cli.d.ts +33 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +1041 -84
- package/dist/cli.js.map +1 -1
- package/dist/command-inventory.d.ts +149 -0
- package/dist/command-inventory.d.ts.map +1 -0
- package/dist/command-inventory.js +405 -0
- package/dist/command-inventory.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/known-flags.d.ts.map +1 -1
- package/dist/known-flags.js +5 -0
- package/dist/known-flags.js.map +1 -1
- package/package.json +16 -15
- package/sbom.json +71 -21
- package/src/boolean-flags.ts +3 -0
- package/src/cli.ts +1036 -76
- package/src/command-inventory.ts +342 -0
- package/src/index.ts +8 -0
- package/src/known-flags.ts +5 -0
package/src/cli.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { request as httpsRequest } from 'node:https';
|
|
|
11
11
|
import { KNOWN_CLI_FLAGS } from './known-flags.js';
|
|
12
12
|
import { isBooleanFlag } from './boolean-flags.js';
|
|
13
13
|
import { resolveInstallSpec } from './install-spec.js';
|
|
14
|
+
import { dispatchedCommands, documentedCommands } from './command-inventory.js';
|
|
14
15
|
import { execFile, execFileSync, execSync, spawn, spawnSync, type ChildProcess } from 'node:child_process';
|
|
15
16
|
import { createHash, randomBytes } from 'node:crypto';
|
|
16
17
|
import { homedir, hostname, tmpdir } from 'node:os';
|
|
@@ -146,8 +147,17 @@ import {
|
|
|
146
147
|
reindexVectorStore,
|
|
147
148
|
harmonizeVectorStore,
|
|
148
149
|
importRvfCheckpoint,
|
|
150
|
+
renderFeatureAdrPhaseLine,
|
|
149
151
|
statuslineData,
|
|
152
|
+
countLearningStoreRowsReadonly,
|
|
153
|
+
readStoreMark,
|
|
154
|
+
writeStoreMark,
|
|
155
|
+
resetStoreMark,
|
|
156
|
+
checkStoreHealth,
|
|
157
|
+
storeGuardPath,
|
|
158
|
+
storeSnapshotPath,
|
|
150
159
|
writeFeatureAdrState,
|
|
160
|
+
writeFeatureAdrStateDetailed,
|
|
151
161
|
CHECKPOINT_STAGES,
|
|
152
162
|
estimateEta,
|
|
153
163
|
extractStageSamples,
|
|
@@ -157,6 +167,9 @@ import {
|
|
|
157
167
|
type CheckpointStage,
|
|
158
168
|
type EtaEstimate,
|
|
159
169
|
type FeatureAdrState,
|
|
170
|
+
type StoreHealth,
|
|
171
|
+
type StoreMark,
|
|
172
|
+
type StoreCountSnapshot,
|
|
160
173
|
type RunSegment,
|
|
161
174
|
type StageSample,
|
|
162
175
|
computeUsage,
|
|
@@ -187,6 +200,9 @@ import {
|
|
|
187
200
|
patternRecordId,
|
|
188
201
|
patternIdentityOf,
|
|
189
202
|
mergeLessonMatchedForms,
|
|
203
|
+
SWARM_BRIEF_CONTRACT,
|
|
204
|
+
checkSwarmBrief,
|
|
205
|
+
visibleText,
|
|
190
206
|
loadStoreRecords,
|
|
191
207
|
recordToPattern,
|
|
192
208
|
bundleSkills,
|
|
@@ -219,6 +235,7 @@ import {
|
|
|
219
235
|
resolveTrustRoot,
|
|
220
236
|
decideVerifyPolicy,
|
|
221
237
|
generateSigningKeypair,
|
|
238
|
+
appendTransition,
|
|
222
239
|
evaluateGuard,
|
|
223
240
|
resolveRules,
|
|
224
241
|
auditRecord,
|
|
@@ -259,6 +276,7 @@ import {
|
|
|
259
276
|
isInsideTree,
|
|
260
277
|
signManifest,
|
|
261
278
|
verifyManifest,
|
|
279
|
+
listPackFiles,
|
|
262
280
|
listSignablePackFiles,
|
|
263
281
|
assertKeyOutsideTree,
|
|
264
282
|
decidePublishGate,
|
|
@@ -293,12 +311,14 @@ import {
|
|
|
293
311
|
DEFAULT_RAKE_THRESHOLDS,
|
|
294
312
|
streamSessionEvents,
|
|
295
313
|
findLatestTranscript,
|
|
314
|
+
resolveScanTailTranscript,
|
|
296
315
|
detectProcessRakes,
|
|
297
316
|
buildRetro,
|
|
298
317
|
renderRetro,
|
|
299
318
|
retroLessonText,
|
|
300
319
|
PROCESS_SIGNATURES,
|
|
301
320
|
RETRO_DOMAIN,
|
|
321
|
+
runRetroTailScan,
|
|
302
322
|
scanForSetup,
|
|
303
323
|
buildSetupPlan,
|
|
304
324
|
scaffoldFromSpec,
|
|
@@ -507,6 +527,8 @@ import {
|
|
|
507
527
|
planImport,
|
|
508
528
|
decideCheckpointWrite,
|
|
509
529
|
amendmentSection,
|
|
530
|
+
amendmentSectionCount,
|
|
531
|
+
amendmentDeclarationAmbiguity,
|
|
510
532
|
planSaysNoAmendments,
|
|
511
533
|
parseAmendments,
|
|
512
534
|
resolveAmendments,
|
|
@@ -569,11 +591,36 @@ import type { ProvenanceMode, PackVerdict, ClaudeUsageModel, PatternRecord, Reca
|
|
|
569
591
|
import { getPreset, PRESET_NAMES } from '@dzhechkov/harness-presets';
|
|
570
592
|
import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, ScoutMemory } from '@dzhechkov/scout';
|
|
571
593
|
|
|
594
|
+
/**
|
|
595
|
+
* Область, по которой гейт дрейфа собирает факты. ПОЛНАЯ, а не только корни установки.
|
|
596
|
+
*
|
|
597
|
+
* ПОЧЕМУ. Под областью `installs` сравниваются лишь корни установки (`.claude/skills`,
|
|
598
|
+
* `.agents/skills` и далее). Навык, чьи копии лежат в РАЗНЫХ корнях — канон в `packages/`, живая
|
|
599
|
+
* копия в `.claude/skills` — имеет там ОДНУ копию, а одну копию не с чем сравнивать: она
|
|
600
|
+
* отбрасывается как не дублированная. То есть главный класс расхождения был для гейта невидим.
|
|
601
|
+
*
|
|
602
|
+
* ИЗМЕРЕНО 2026-09-03: `brutal-honesty-review` разошёлся ровно так (канон в skills-qe, копия в
|
|
603
|
+
* бандле p-replicator, живая в .claude/skills), и гейт не мог увидеть это В ПРИНЦИПЕ. Я тогда
|
|
604
|
+
* написал в отчёте «гейт разблокирован» — он никогда не был на этом заблокирован.
|
|
605
|
+
*
|
|
606
|
+
* Узкая область давала 19 дублирующихся навыков, полная даёт 211. Безопасность расширения
|
|
607
|
+
* проверена ДО правки: с полной областью и списком исключений дрейфа сегодня НОЛЬ.
|
|
608
|
+
*/
|
|
609
|
+
const DRIFT_SWEEP_SCOPE = 'all' as const;
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Базовая дата правила `backlog-covers-features`. Каталоги фич, заведённые ДО неё, правило не
|
|
613
|
+
* трогает: они появились раньше самого правила. ИЗМЕРЕНО 2026-09-03 — без базы правило даёт 236
|
|
614
|
+
* нарушений из 336 каталогов, и проверка, изобретающая полсотни нарушений в первый день, учит
|
|
615
|
+
* людей себя игнорировать. Дата = день, когда правило принято владельцем.
|
|
616
|
+
*/
|
|
617
|
+
const BACKLOG_COVERAGE_BASELINE = '2026-09-03';
|
|
618
|
+
|
|
572
619
|
/** Literal command inventory, pinned against the main dispatch switch by a layer-1 test. */
|
|
573
620
|
export const DZ_COMMANDS: readonly string[] = [
|
|
574
621
|
'init', 'verify', 'sync', 'update', 'list', 'create-skill', 'info', 'scout',
|
|
575
622
|
'workflow', 'workflow-lint', 'workflow-trace', 'migrate', 'doctor', 'install',
|
|
576
|
-
'bundle', 'teach', 'consolidate', 'recall', 'vector', 'brain', 'statusline',
|
|
623
|
+
'bundle', 'teach', 'consolidate', 'recall', 'vector', 'brain', 'statusline', 'store-guard',
|
|
577
624
|
'usage', 'claim-check', 'lint', 'sign', 'sbom', 'guard', 'verify-pack', 'setup',
|
|
578
625
|
'pretrain', 'compose', 'diff', 'recommend', 'upgrade', 'auto-canonicalize',
|
|
579
626
|
'publish', 'release', 'parity', 'registry', 'benchmark', 'mcp-scan',
|
|
@@ -582,7 +629,7 @@ export const DZ_COMMANDS: readonly string[] = [
|
|
|
582
629
|
'retro', 'feature-adr-setup', 'challenge', 'discrimination-check',
|
|
583
630
|
'mutation-gate', 'delivery-check', 'skills-verify', 'compounding', 'deadwood',
|
|
584
631
|
'epoch-replay', 'score', 'recap', 'cadence', 'qe-rounds', 'restart-advisor', 'tg-post',
|
|
585
|
-
'name-check', 'provenance-check', 'feature-adr-record', 'amendment-check', 'contract-check',
|
|
632
|
+
'name-check', 'brief-check', 'provenance-check', 'feature-adr-record', 'amendment-check', 'contract-check',
|
|
586
633
|
'feature-adr-checkpoint', 'profile', 'reqe', 'qe-bridge', 'backlog', 'routing',
|
|
587
634
|
'bto-optimize', 'dashboard', 'roam', 'import-ecc', 'chain',
|
|
588
635
|
];
|
|
@@ -633,13 +680,14 @@ Usage:
|
|
|
633
680
|
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)
|
|
634
681
|
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)
|
|
635
682
|
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)
|
|
683
|
+
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)
|
|
636
684
|
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)
|
|
637
685
|
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)
|
|
638
686
|
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)
|
|
639
687
|
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)
|
|
640
688
|
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)
|
|
641
689
|
dz sbom [--pack <name>] [--out <file>] (CycloneDX software bill of materials for the workspace, or for one pack with --pack)
|
|
642
|
-
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)
|
|
690
|
+
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)
|
|
643
691
|
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)
|
|
644
692
|
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)
|
|
645
693
|
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)
|
|
@@ -647,7 +695,7 @@ Usage:
|
|
|
647
695
|
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)
|
|
648
696
|
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)
|
|
649
697
|
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)
|
|
650
|
-
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)
|
|
698
|
+
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)
|
|
651
699
|
dz backlog list [--status <s>] [--goal <id>] [--project <dir>] [--json] (list captured ideas, filterable by status/goal)
|
|
652
700
|
dz backlog show <id> [--project <dir>] [--json] (full record for one idea)
|
|
653
701
|
dz backlog goals [--validate] [--project <dir>] [--json] (list/validate the compass at .dz/backlog/goals.json)
|
|
@@ -661,7 +709,7 @@ Usage:
|
|
|
661
709
|
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)
|
|
662
710
|
dz backlog harmonize [--apply] [--threshold <0-1>] [--project <dir>] [--json] (batch semantic dedup of the backlog ideas; --dry-run default, --apply snapshots first)
|
|
663
711
|
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)
|
|
664
|
-
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)
|
|
712
|
+
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)
|
|
665
713
|
dz teach --from-json <file> [--project <dir>] [--no-mirror] (bulk-import a 'dz recall --all --json' export — share a learned store across machines)
|
|
666
714
|
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)
|
|
667
715
|
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)
|
|
@@ -681,7 +729,8 @@ Usage:
|
|
|
681
729
|
dz brain expand <kuId> [--source <slug>] [--json] (full-content lookup for a citation kuId; --json emits the full KU object)
|
|
682
730
|
dz brain init [--project <dir>] [--k <N>] (wire the grounding hook into .claude/settings.json — opt-in)
|
|
683
731
|
dz statusline [--json] [--install] [--project <dir>] (live self-learning panel for Claude Code's status bar; reads the CC JSON payload from STDIN)
|
|
684
|
-
dz
|
|
732
|
+
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)
|
|
733
|
+
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)
|
|
685
734
|
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)
|
|
686
735
|
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)
|
|
687
736
|
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)
|
|
@@ -709,6 +758,10 @@ Usage:
|
|
|
709
758
|
dz dashboard
|
|
710
759
|
dz roam [--apply] [--slug <slug>]
|
|
711
760
|
dz import-ecc [--local-path <dir>] [--select id,id,...] [--limit N] [--output <dir>] [--force]
|
|
761
|
+
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)
|
|
762
|
+
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)
|
|
763
|
+
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)
|
|
764
|
+
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)
|
|
712
765
|
dz help
|
|
713
766
|
|
|
714
767
|
Global: --version | -v [--json] (prints this CLI's own semver on one line, exit 0; "unknown" + exit 1 when unresolvable)
|
|
@@ -1396,7 +1449,7 @@ async function cmdScout(options: Map<string, string>, flags: Set<string>, cwd: s
|
|
|
1396
1449
|
|
|
1397
1450
|
try {
|
|
1398
1451
|
const scanTopics = topicsArg ? topicsArg.split(',').map((t) => t.trim()) : undefined;
|
|
1399
|
-
const { results: repos, totalBySource } = await scanAllSources({
|
|
1452
|
+
const { results: repos, totalBySource, statusBySource } = await scanAllSources({
|
|
1400
1453
|
token,
|
|
1401
1454
|
topics: scanTopics,
|
|
1402
1455
|
since,
|
|
@@ -1410,10 +1463,16 @@ async function cmdScout(options: Map<string, string>, flags: Set<string>, cwd: s
|
|
|
1410
1463
|
.join(', ');
|
|
1411
1464
|
write(`Sources: ${sourceLines}`);
|
|
1412
1465
|
|
|
1413
|
-
// Memory: diff with previous scan
|
|
1466
|
+
// Memory: diff with previous scan.
|
|
1467
|
+
//
|
|
1468
|
+
// СОСТОЯНИЕ ИСТОЧНИКОВ ПЕРЕДАЁТСЯ ОБЯЗАТЕЛЬНО. Без него разность не выводит исчезновений
|
|
1469
|
+
// вообще — и это правильно: источник, ответивший кодом ошибки, раньше делал ВСЕ свои записи
|
|
1470
|
+
// «пропавшими» на экране, то есть отчёт печатал факт о нашей сети как факт о мире.
|
|
1414
1471
|
if (showDiff || memory.size > 0) {
|
|
1415
|
-
const
|
|
1416
|
-
|
|
1472
|
+
const health: Record<string, string> = {};
|
|
1473
|
+
for (const [source, status] of Object.entries(statusBySource)) health[source] = status.health;
|
|
1474
|
+
const diff = memory.diff(repos, health);
|
|
1475
|
+
if (diff.newRepos.length > 0 || diff.goneRepos.length > 0 || diff.changedScore.length > 0 || diff.goneOmittedReason !== undefined) {
|
|
1417
1476
|
write(memory.diffMarkdown(diff));
|
|
1418
1477
|
} else if (memory.size > 0) {
|
|
1419
1478
|
write(`\nNo changes since last scan (${memory.size} repos tracked).\n`);
|
|
@@ -2216,6 +2275,49 @@ function cmdBundle(options: Map<string, string>, flags: Set<string>, cwd: string
|
|
|
2216
2275
|
return 0;
|
|
2217
2276
|
}
|
|
2218
2277
|
|
|
2278
|
+
/**
|
|
2279
|
+
* Команда npm для установки пакета В ЦЕЛЕВОЙ КАТАЛОГ, а не куда решит npm.
|
|
2280
|
+
*
|
|
2281
|
+
* ЗАЧЕМ `--prefix`. Без него npm при отсутствии `package.json` в текущем каталоге поднимается по
|
|
2282
|
+
* дереву до первого найденного и мутирует ЕГО — а `dz` потом ищет пакет в
|
|
2283
|
+
* `<цель>/node_modules` и не находит. Место установки и место проверки были двумя независимыми
|
|
2284
|
+
* предположениями, и совпадали они только по удаче.
|
|
2285
|
+
*
|
|
2286
|
+
* ИЗМЕРЕНО 2026-09-03 (полевой случай владельца): установка в каталог без `package.json`
|
|
2287
|
+
* записала в `/home`, где лежит ЧУЖОЙ проект; ручной откат вернул `package.json`, а запись
|
|
2288
|
+
* `extraneous` в `/home/package-lock.json` пережила откат.
|
|
2289
|
+
*
|
|
2290
|
+
* ПОЧЕМУ НЕ ОТКАЗ (ADR-001, вариант A отвергнут). Отказ запретил бы законный сценарий: проект
|
|
2291
|
+
* внутри монорепо, намеренно не имеющий своего `package.json` и опирающийся на родительский
|
|
2292
|
+
* воркспейс. `--prefix` согласует установку с проверкой ПО ПОСТРОЕНИЮ и сценарий сохраняет.
|
|
2293
|
+
*
|
|
2294
|
+
* ЧИСТАЯ: ни файловой системы, ни запуска npm — проверяется без обоих. Путь экранируется, потому
|
|
2295
|
+
* что каталоги с пробелом в имени встречаются в наших же тестах.
|
|
2296
|
+
*/
|
|
2297
|
+
export function buildInstallArgs(npmSpec: string, projectRoot: string): readonly string[] {
|
|
2298
|
+
return ['install', npmSpec, '--prefix', projectRoot, '--save-dev', '--no-fund', '--no-audit'];
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
/**
|
|
2302
|
+
* Та же команда СТРОКОЙ — только для показа человеку и для тестового шва.
|
|
2303
|
+
*
|
|
2304
|
+
* НЕ ДЛЯ ИСПОЛНЕНИЯ, и это не стилистическая оговорка. `JSON.stringify` НЕ является экранированием
|
|
2305
|
+
* для оболочки: внутри двойных кавычек оболочка по-прежнему выполняет `$(...)` и обратные кавычки.
|
|
2306
|
+
* ИЗМЕРЕНО 2026-09-03 — `execSync('echo ' + JSON.stringify('pkg$(touch ФАЙЛ)'))` создал файл.
|
|
2307
|
+
* Прежняя редакция этого комментария утверждала «путь экранируется»; это было неверно, и находку
|
|
2308
|
+
* предъявило кросс-семейное ревью (gpt-5.6-sol), а я подтвердил её пробой.
|
|
2309
|
+
*
|
|
2310
|
+
* Боевой путь исполняется через `execFileSync` массивом аргументов — оболочки в цепочке нет вовсе,
|
|
2311
|
+
* поэтому подставлять некуда. Это структурное лечение, а не более хитрое экранирование.
|
|
2312
|
+
*/
|
|
2313
|
+
export function buildInstallCommand(npmSpec: string, projectRoot: string): string {
|
|
2314
|
+
// ЗНАЧЕНИЯ в кавычках, ФЛАГИ без — та же форма, что печаталась до этой фичи, чтобы читатель
|
|
2315
|
+
// (и закреплённые тесты) видели знакомую строку. Кавычки здесь — ЧИТАЕМОСТЬ, а не безопасность:
|
|
2316
|
+
// безопасность даёт отсутствие оболочки на боевом пути.
|
|
2317
|
+
return `npm install ${JSON.stringify(npmSpec)} --prefix ${JSON.stringify(projectRoot)}`
|
|
2318
|
+
+ ' --save-dev --no-fund --no-audit';
|
|
2319
|
+
}
|
|
2320
|
+
|
|
2219
2321
|
async function cmdInstall(
|
|
2220
2322
|
options: Map<string, string>,
|
|
2221
2323
|
flags: Set<string>,
|
|
@@ -2267,14 +2369,36 @@ async function cmdInstall(
|
|
|
2267
2369
|
|
|
2268
2370
|
const projectRoot = resolve(cwd, options.get('project') ?? '.');
|
|
2269
2371
|
|
|
2372
|
+
// ПРЕДПОСЫЛКА НАЗЫВАЕТСЯ ДО ПОБОЧНОГО ЭФФЕКТА, А НЕ ПОСЛЕ (ADR-001, FR-2).
|
|
2373
|
+
//
|
|
2374
|
+
// Проверка стоит ЗДЕСЬ, до развилки installRunner/execSync, и это не стилистика. Поставить её
|
|
2375
|
+
// внутрь ветки execSync значило бы оставить боевой путь непокрытым при зелёных тестах — ровно
|
|
2376
|
+
// то состояние, из которого фича и родилась.
|
|
2377
|
+
const hasOwnManifest = existsSync(join(projectRoot, 'package.json'));
|
|
2378
|
+
if (!hasOwnManifest) {
|
|
2379
|
+
write(`dz install: ${projectRoot} — не npm-проект (нет своего package.json).`);
|
|
2380
|
+
write(` Ставлю ЛОКАЛЬНО в него: npm получит --prefix, package.json и node_modules появятся здесь.`);
|
|
2381
|
+
write(` Без --prefix npm поднялся бы по дереву и записал в ЧУЖОЙ проект выше — измерено 2026-09-03.`);
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2270
2384
|
// Step 1: npm install the package (installRunner is the CliIo test seam — unset in production)
|
|
2271
2385
|
write(`Installing ${specResolution.npmSpec}${specResolution.kind === 'name' ? '' : ` (${specResolution.kind} → node_modules/${specResolution.dirName})`}...`);
|
|
2272
|
-
const installCmd =
|
|
2386
|
+
const installCmd = buildInstallCommand(specResolution.npmSpec, projectRoot);
|
|
2273
2387
|
try {
|
|
2274
2388
|
if (installRunner) installRunner(installCmd, projectRoot);
|
|
2275
|
-
|
|
2389
|
+
// БЕЗ ОБОЛОЧКИ. execFileSync с массивом аргументов не запускает shell, поэтому имя пакета или
|
|
2390
|
+
// путь с `$(...)` подставить нечему. Строка выше — для показа и для тестового шва, не для
|
|
2391
|
+
// исполнения (см. докстринг buildInstallCommand).
|
|
2392
|
+
else execFileSync('npm', [...buildInstallArgs(specResolution.npmSpec, projectRoot)], { cwd: projectRoot, stdio: 'pipe', encoding: 'utf-8' });
|
|
2276
2393
|
} catch (err) {
|
|
2277
2394
|
write(`dz install: npm install failed — ${err instanceof Error ? err.message : String(err)}`);
|
|
2395
|
+
// НЕАТОМАРНЫЙ ОТКАЗ НАЗЫВАЕТСЯ ВСЛУХ (ADR-001, FR-4). Названо кросс-семейной проверкой
|
|
2396
|
+
// 2026-09-03: npm мог успеть изменить package.json, файл замков и node_modules и упасть уже
|
|
2397
|
+
// после этого. Отката у нас нет — и молчать об этом хуже, чем не откатывать: пользователь
|
|
2398
|
+
// считает каталог нетронутым. Полевой случай: ручной откат вернул package.json, а запись
|
|
2399
|
+
// extraneous в файле замков пережила его.
|
|
2400
|
+
write(` npm мог успеть изменить файлы ДО падения — проверьте ${join(projectRoot, 'package.json')},`);
|
|
2401
|
+
write(` ${join(projectRoot, 'package-lock.json')} и ${join(projectRoot, 'node_modules')}: отката dz не делает.`);
|
|
2278
2402
|
return 1;
|
|
2279
2403
|
}
|
|
2280
2404
|
|
|
@@ -2535,7 +2659,7 @@ function cmdStatuslineInstall(options: Map<string, string>, cwd: string, write:
|
|
|
2535
2659
|
* `--kind <feature-adr|loop>` identifies the producer, defaults to `feature-adr`, and rejects any
|
|
2536
2660
|
* other value rather than silently weakening panel arbitration.
|
|
2537
2661
|
*/
|
|
2538
|
-
function cmdStatuslineFaRecord(options: Map<string, string>, cwd: string, write: Write): number {
|
|
2662
|
+
function cmdStatuslineFaRecord(options: Map<string, string>, cwd: string, write: Write, writeErr: WriteErr): number {
|
|
2539
2663
|
const slug = (options.get('slug') ?? '').trim();
|
|
2540
2664
|
const step = (options.get('step') ?? '').trim();
|
|
2541
2665
|
|
|
@@ -2595,19 +2719,42 @@ function cmdStatuslineFaRecord(options: Map<string, string>, cwd: string, write:
|
|
|
2595
2719
|
return 1;
|
|
2596
2720
|
}
|
|
2597
2721
|
|
|
2722
|
+
// fa-phase-statusline (acid A1): --tier drives done/total on the phase line — an invalid tier is
|
|
2723
|
+
// REJECTED before anything is written (nothing slotted, nothing ledgered), never silently dropped.
|
|
2724
|
+
const tierRaw = options.get('tier');
|
|
2725
|
+
const tier = tierRaw?.trim();
|
|
2726
|
+
if (tier !== undefined && tier !== 'S' && tier !== 'M' && tier !== 'L' && tier !== 'XL') {
|
|
2727
|
+
write(`dz statusline --fa-record: --tier must be S, M, L or XL (got "${tierRaw}")`);
|
|
2728
|
+
write(' Example: dz statusline --fa-record --slug add-user-auth --step "Step 7 Code" --tier M');
|
|
2729
|
+
return 1;
|
|
2730
|
+
}
|
|
2731
|
+
|
|
2598
2732
|
const mode = options.get('mode');
|
|
2599
2733
|
const projectRoot = resolve(cwd, options.get('project') ?? '.');
|
|
2600
|
-
const
|
|
2734
|
+
const outcome = writeFeatureAdrStateDetailed(projectRoot, {
|
|
2601
2735
|
kind: kindRaw, slug, step, recalled, stored,
|
|
2602
2736
|
...(reinforced > 0 ? { reinforced } : {}),
|
|
2603
2737
|
...(mode !== undefined && mode.trim() !== '' ? { mode: mode.trim() } : {}),
|
|
2738
|
+
...(tier !== undefined ? { tier } : {}),
|
|
2604
2739
|
});
|
|
2740
|
+
const state = outcome.state;
|
|
2605
2741
|
|
|
2606
2742
|
if (state === undefined) {
|
|
2743
|
+
// [AM-5] A REFUSED slot write is LOUD. A held `fa-phase-slot` lock or an unwritable `.dz` used
|
|
2744
|
+
// to return a bare `undefined`, and a caller reading silence as success is exactly the
|
|
2745
|
+
// "absence of a receipt is not success" class. The reason goes to stderr — diagnosis, not
|
|
2746
|
+
// data — and the EXIT CODE is unchanged for a refusal, because the panel must never break the
|
|
2747
|
+
// pipeline that is only reporting to it.
|
|
2748
|
+
if (outcome.refused !== undefined) {
|
|
2749
|
+
writeErr(`fa-record: slot write refused (${slug}): ${outcome.refused}`);
|
|
2750
|
+
return 0;
|
|
2751
|
+
}
|
|
2607
2752
|
write(`dz statusline --fa-record: could not write learning state under ${projectRoot}/.dz/feature-adr/`);
|
|
2608
2753
|
return 1;
|
|
2609
2754
|
}
|
|
2610
|
-
|
|
2755
|
+
// state.step, not the flag: the monotonic guard may have kept a LATER step against a stale
|
|
2756
|
+
// duplicate record (fa-phase-statusline P1) — print what actually stands in the slot.
|
|
2757
|
+
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`);
|
|
2611
2758
|
return 0;
|
|
2612
2759
|
}
|
|
2613
2760
|
|
|
@@ -2759,8 +2906,12 @@ function statuslineEta(projectRoot: string, state: FeatureAdrState, nowMs: numbe
|
|
|
2759
2906
|
* least a minimal `dz` even on total failure.
|
|
2760
2907
|
*
|
|
2761
2908
|
* Flags: `--install` wires it into settings.json; `--fa-record` records a live `/feature-adr`
|
|
2762
|
-
* learning state (WRITES — see {@link cmdStatuslineFaRecord}); `--json` prints the raw data object
|
|
2763
|
-
*
|
|
2909
|
+
* learning state (WRITES — see {@link cmdStatuslineFaRecord}); `--json` prints the raw data object
|
|
2910
|
+
* (plus `featureAdrLine`, the rendered phase line, when a fresh /feature-adr run is in flight);
|
|
2911
|
+
* default prints the status line, with the 📐 phase panel as its OWN SECOND LINE (format B —
|
|
2912
|
+
* fa-phase-statusline ADR-001 D1; Claude Code renders every stdout line of a statusline command).
|
|
2913
|
+
* The ETA fragment main shipped for that panel rides the SECOND line with it (fa-phase-statusline ADR-001 D1) — the panel
|
|
2914
|
+
* moved, the estimate was not dropped.
|
|
2764
2915
|
*/
|
|
2765
2916
|
function cmdStatusline(
|
|
2766
2917
|
options: Map<string, string>,
|
|
@@ -2768,12 +2919,14 @@ function cmdStatusline(
|
|
|
2768
2919
|
cwd: string,
|
|
2769
2920
|
write: Write,
|
|
2770
2921
|
readStdin: () => string,
|
|
2922
|
+
writeErr: WriteErr,
|
|
2771
2923
|
): number {
|
|
2772
2924
|
if (flags.has('install')) return cmdStatuslineInstall(options, cwd, write);
|
|
2773
|
-
if (flags.has('fa-record')) return cmdStatuslineFaRecord(options, cwd, write);
|
|
2925
|
+
if (flags.has('fa-record')) return cmdStatuslineFaRecord(options, cwd, write, writeErr);
|
|
2774
2926
|
|
|
2775
2927
|
try {
|
|
2776
2928
|
const projectRoot = statuslineProjectRoot(readStdin(), options, cwd);
|
|
2929
|
+
warnLearningStoreRead(projectRoot, writeErr, 'dz statusline');
|
|
2777
2930
|
const data = statuslineData(projectRoot);
|
|
2778
2931
|
const fa = data.featureAdr;
|
|
2779
2932
|
let eta: EtaEstimate | undefined;
|
|
@@ -2789,27 +2942,55 @@ function cmdStatusline(
|
|
|
2789
2942
|
}
|
|
2790
2943
|
}
|
|
2791
2944
|
|
|
2945
|
+
// fa-phase-statusline (ADR-001 D1): the phase line renders from the slot ALONE — a pure
|
|
2946
|
+
// function over data.featureAdr, computed once here for both the plain and --json surfaces.
|
|
2947
|
+
const phaseLine = fa !== undefined ? renderFeatureAdrPhaseLine(fa) : undefined;
|
|
2948
|
+
|
|
2792
2949
|
if (flags.has('json')) {
|
|
2793
|
-
write(JSON.stringify({
|
|
2950
|
+
write(JSON.stringify({
|
|
2951
|
+
...data,
|
|
2952
|
+
...(eta !== undefined ? { eta } : {}),
|
|
2953
|
+
...(phaseLine !== undefined ? { featureAdrLine: phaseLine } : {}),
|
|
2954
|
+
}));
|
|
2794
2955
|
return 0;
|
|
2795
2956
|
}
|
|
2796
2957
|
|
|
2797
|
-
|
|
2958
|
+
const breakdown = data.patternBreakdown;
|
|
2959
|
+
let line = breakdown === undefined
|
|
2960
|
+
? `🎓 dz: ${data.patterns} patterns`
|
|
2961
|
+
: `🎓 dz: ${data.patterns} (${breakdown.active} актив${breakdown.quarantined > 0
|
|
2962
|
+
? ` · ${breakdown.quarantined} карантин${breakdown.attention ? ' ⚠' : ''}`
|
|
2963
|
+
: ''})${breakdown.tierDelta !== undefined ? ` ⚠ тиры Δ${breakdown.tierDelta}` : ''}`;
|
|
2964
|
+
if (data.storeHealth?.verdict === 'collapsed') {
|
|
2965
|
+
line += ` ⛔ ОБВАЛ: было ${data.storeHealth.previousMax ?? '?'} · dz store-guard --reset`;
|
|
2966
|
+
} else if (data.storeHealth?.verdict === 'cold-start-over-existing') {
|
|
2967
|
+
line += ` ⛔ СТОР ПУСТ: было ${data.storeHealth.previousMax ?? '?'} · восстановить из снимков ${data.storeHealth.snapshotPath ?? ''}`.trimEnd();
|
|
2968
|
+
} else if (data.storeHealth?.verdict === 'unreadable') {
|
|
2969
|
+
line += ` ⛔ СТОР НЕЧИТАЕМ${data.storeHealth.unreadableFiles !== undefined && data.storeHealth.unreadableFiles.length > 0
|
|
2970
|
+
? `: ${data.storeHealth.unreadableFiles.join(', ')}` : ''}`;
|
|
2971
|
+
} else if (data.storeHealth?.verdict === 'source-changed') {
|
|
2972
|
+
line += ' ⚠ смена источника хранения';
|
|
2973
|
+
}
|
|
2974
|
+
line += `${data.usedPatterns !== undefined ? ` · ${data.usedPatterns} used` : ''} · 🧠 ${data.brainSources} sources`;
|
|
2798
2975
|
const branch = statuslineGitBranch(projectRoot);
|
|
2799
2976
|
if (branch !== undefined) line += ` · ⎇ ${branch}`;
|
|
2800
2977
|
if (data.consolidatedAgeH !== undefined) line += ` · ⟳ ${data.consolidatedAgeH}h`;
|
|
2801
2978
|
|
|
2802
|
-
// Live
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
} else {
|
|
2808
|
-
line = `📐 feature-adr ${fa.step} · ${etaFragment !== undefined ? `${etaFragment} · ` : ''}🎓 ${fa.pool} pool · ↑${fa.recalled} used · +${fa.stored} new · ↻${fa.reinforced ?? 0} reinforced · ${line}`;
|
|
2809
|
-
}
|
|
2979
|
+
// Live loop run in flight → PREPEND its segment to the base dz line (unchanged). A live
|
|
2980
|
+
// /feature-adr run no longer glues into line 1: its 📐 segment IS the second line (format B) —
|
|
2981
|
+
// Claude Code renders every stdout line of a statusline command (fa-phase-statusline ADR-001 D1).
|
|
2982
|
+
if (fa !== undefined && fa.kind === 'loop') {
|
|
2983
|
+
line = `🔁 loop ${fa.step} · ${line}`;
|
|
2810
2984
|
}
|
|
2811
2985
|
|
|
2812
2986
|
write(line);
|
|
2987
|
+
// fa-phase-statusline ADR-001 D1: the phase panel moved to line 2 and TOOK main's ETA fragment with it. The move is
|
|
2988
|
+
// the point of format B (ADR-001 D1); dropping the estimate would have been a silent
|
|
2989
|
+
// regression of a feature `main` shipped while this branch was stranded, so it rides here
|
|
2990
|
+
// instead. A phase line that renders (fresh, non-terminal, non-loop slot) is the only gate.
|
|
2991
|
+
if (phaseLine !== undefined) {
|
|
2992
|
+
write(`${phaseLine}${etaFragment !== undefined ? ` · ${etaFragment}` : ''}`);
|
|
2993
|
+
}
|
|
2813
2994
|
return 0;
|
|
2814
2995
|
} catch {
|
|
2815
2996
|
// A garbled status bar is worse than a terse one — print SOMETHING minimal, never throw.
|
|
@@ -3432,6 +3613,282 @@ function learningStoreLine(
|
|
|
3432
3613
|
) + (reason ? ' [' + reason + ']' : '');
|
|
3433
3614
|
}
|
|
3434
3615
|
|
|
3616
|
+
function inspectLearningStore(projectRoot: string): {
|
|
3617
|
+
mark: StoreMark | undefined;
|
|
3618
|
+
health: StoreHealth;
|
|
3619
|
+
rows: ReturnType<typeof countLearningStoreRowsReadonly>;
|
|
3620
|
+
} {
|
|
3621
|
+
const mark = readStoreMark(projectRoot);
|
|
3622
|
+
const rows = countLearningStoreRowsReadonly(projectRoot);
|
|
3623
|
+
return { mark, rows, health: checkStoreHealth({ projectRoot, ...rows, mark }) };
|
|
3624
|
+
}
|
|
3625
|
+
|
|
3626
|
+
function shellQuote(value: string): string {
|
|
3627
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
3628
|
+
}
|
|
3629
|
+
|
|
3630
|
+
function storeGuardResetCommand(projectRoot: string): string {
|
|
3631
|
+
return `dz store-guard --reset --project ${shellQuote(projectRoot)}`;
|
|
3632
|
+
}
|
|
3633
|
+
|
|
3634
|
+
function lexicalSourceLines(rows: ReturnType<typeof countLearningStoreRowsReadonly>): string[] {
|
|
3635
|
+
return [
|
|
3636
|
+
` lexical selected: ${rows.lexicalSourcePath} (${rows.lexicalSource}, ${rows.lexicalRows} rows)`,
|
|
3637
|
+
...(rows.lexicalIgnoredSourcePath === undefined ? [] : [
|
|
3638
|
+
` lexical ignored: ${rows.lexicalIgnoredSourcePath} (${rows.lexicalIgnoredRows} rows)`,
|
|
3639
|
+
]),
|
|
3640
|
+
];
|
|
3641
|
+
}
|
|
3642
|
+
|
|
3643
|
+
function storeGuardRecoveryLines(
|
|
3644
|
+
projectRoot: string,
|
|
3645
|
+
mark: StoreMark | undefined,
|
|
3646
|
+
health: StoreHealth,
|
|
3647
|
+
rows?: ReturnType<typeof countLearningStoreRowsReadonly>,
|
|
3648
|
+
): string[] {
|
|
3649
|
+
const snapshots = storeSnapshotPath(projectRoot);
|
|
3650
|
+
const markPath = storeGuardPath(projectRoot);
|
|
3651
|
+
let lexicalSnapshot: 'sqlite' | 'jsonl' | undefined;
|
|
3652
|
+
let vectorSnapshot = false;
|
|
3653
|
+
try {
|
|
3654
|
+
const names = existsSync(snapshots) ? readdirSync(snapshots) : [];
|
|
3655
|
+
const hasSqlite = names.some((name) => /^lexical\..+\.sqlite$/.test(name));
|
|
3656
|
+
const hasJsonl = names.some((name) => /^lexical\..+\.jsonl$/.test(name));
|
|
3657
|
+
const preferred = mark?.lexicalSource === 'sqlite' || mark?.lexicalSource === 'jsonl'
|
|
3658
|
+
? mark.lexicalSource
|
|
3659
|
+
: rows?.lexicalSource;
|
|
3660
|
+
if (preferred === 'jsonl' && hasJsonl) lexicalSnapshot = 'jsonl';
|
|
3661
|
+
else if (preferred === 'sqlite' && hasSqlite) lexicalSnapshot = 'sqlite';
|
|
3662
|
+
else if (hasSqlite) lexicalSnapshot = 'sqlite';
|
|
3663
|
+
else if (hasJsonl) lexicalSnapshot = 'jsonl';
|
|
3664
|
+
vectorSnapshot = names.some((name) => /^vector\..+\.sqlite$/.test(name));
|
|
3665
|
+
} catch {
|
|
3666
|
+
lexicalSnapshot = undefined;
|
|
3667
|
+
vectorSnapshot = false;
|
|
3668
|
+
}
|
|
3669
|
+
const lines = [
|
|
3670
|
+
`dz store guard: REFUSED — ${health.reason}`,
|
|
3671
|
+
` mark: ${markPath}`,
|
|
3672
|
+
...(mark === undefined ? [] : [` recorded rows: lexical=${mark.lexicalMax} (${mark.lexicalSource}), vector=${mark.vectorMax}`]),
|
|
3673
|
+
...(rows === undefined ? [] : lexicalSourceLines(rows)),
|
|
3674
|
+
];
|
|
3675
|
+
if (lexicalSnapshot !== undefined && vectorSnapshot) {
|
|
3676
|
+
const lexicalDestination = lexicalSnapshot === 'sqlite'
|
|
3677
|
+
? join(projectRoot, '.dz', 'memory', 'patterns.sqlite')
|
|
3678
|
+
: join(projectRoot, '.dz', 'patterns.jsonl');
|
|
3679
|
+
lines.push(
|
|
3680
|
+
` snapshots: ${snapshots}/`,
|
|
3681
|
+
` 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'))}`,
|
|
3682
|
+
);
|
|
3683
|
+
} else {
|
|
3684
|
+
lines.push(
|
|
3685
|
+
` snapshots: none found in ${snapshots}/`,
|
|
3686
|
+
` create one manually: scripts/dz-store-snapshot.sh --project ${shellQuote(projectRoot)}`,
|
|
3687
|
+
);
|
|
3688
|
+
}
|
|
3689
|
+
lines.push(
|
|
3690
|
+
` accept current counts: ${storeGuardResetCommand(projectRoot)}`,
|
|
3691
|
+
' continue intentionally: set DZ_ALLOW_COLD_START=1 or pass --allow-cold-start',
|
|
3692
|
+
);
|
|
3693
|
+
return lines;
|
|
3694
|
+
}
|
|
3695
|
+
|
|
3696
|
+
function observedRows(
|
|
3697
|
+
rows: ReturnType<typeof countLearningStoreRowsReadonly>,
|
|
3698
|
+
): StoreCountSnapshot | undefined {
|
|
3699
|
+
return typeof rows.lexicalRows === 'number' && typeof rows.vectorRows === 'number'
|
|
3700
|
+
? { lexicalRows: rows.lexicalRows, vectorRows: rows.vectorRows, lexicalSource: rows.lexicalSource }
|
|
3701
|
+
: undefined;
|
|
3702
|
+
}
|
|
3703
|
+
|
|
3704
|
+
interface MarkRefreshOptions {
|
|
3705
|
+
readonly reader?: boolean;
|
|
3706
|
+
}
|
|
3707
|
+
|
|
3708
|
+
/** Mark maintenance is diagnostic: the store operation already completed and must keep its exit code. */
|
|
3709
|
+
function refreshLearningStoreMark(
|
|
3710
|
+
projectRoot: string,
|
|
3711
|
+
writeErr: WriteErr,
|
|
3712
|
+
command: string,
|
|
3713
|
+
options: MarkRefreshOptions = {},
|
|
3714
|
+
): void {
|
|
3715
|
+
try {
|
|
3716
|
+
const rows = countLearningStoreRowsReadonly(projectRoot);
|
|
3717
|
+
const counts = observedRows(rows);
|
|
3718
|
+
if (counts === undefined) {
|
|
3719
|
+
writeErr(`⚠ dz store guard: ${options.reader ? 'reader observation' : 'store operation'} completed but the external mark was not updated — a store tier is unreadable`);
|
|
3720
|
+
return;
|
|
3721
|
+
}
|
|
3722
|
+
writeStoreMark(projectRoot, {
|
|
3723
|
+
...counts,
|
|
3724
|
+
observedAt: new Date().toISOString(),
|
|
3725
|
+
command,
|
|
3726
|
+
}, options.reader ? { timeoutMs: 0 } : {});
|
|
3727
|
+
} catch (error) {
|
|
3728
|
+
if (options.reader && error instanceof NamedLockTimeoutError) return;
|
|
3729
|
+
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)}`);
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3733
|
+
function storeGuardResetReminder(projectRoot: string, writeErr: WriteErr, command: string): void {
|
|
3734
|
+
try {
|
|
3735
|
+
const rows = countLearningStoreRowsReadonly(projectRoot);
|
|
3736
|
+
const mark = readStoreMark(projectRoot);
|
|
3737
|
+
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)}`);
|
|
3738
|
+
for (const line of lexicalSourceLines(rows)) writeErr(line);
|
|
3739
|
+
} catch (error) {
|
|
3740
|
+
writeErr(`⚠ DZ STORE GUARD — ${command}: store changed; inspect it and reconcile explicitly with ${storeGuardResetCommand(projectRoot)} (${error instanceof Error ? error.message : String(error)})`);
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
|
|
3744
|
+
/** Fail closed for store writers, except for an explicit per-process/per-command override. */
|
|
3745
|
+
function allowLearningStoreWrite(
|
|
3746
|
+
projectRoot: string,
|
|
3747
|
+
flags: Set<string>,
|
|
3748
|
+
writeErr: WriteErr,
|
|
3749
|
+
command: string,
|
|
3750
|
+
): boolean {
|
|
3751
|
+
let inspection: ReturnType<typeof inspectLearningStore>;
|
|
3752
|
+
try {
|
|
3753
|
+
inspection = inspectLearningStore(projectRoot);
|
|
3754
|
+
} catch (error) {
|
|
3755
|
+
const health: StoreHealth = {
|
|
3756
|
+
verdict: 'unreadable',
|
|
3757
|
+
reason: `cannot read the external mark (${error instanceof Error ? error.message : String(error)})`,
|
|
3758
|
+
};
|
|
3759
|
+
for (const line of storeGuardRecoveryLines(projectRoot, undefined, health)) writeErr(line);
|
|
3760
|
+
return false;
|
|
3761
|
+
}
|
|
3762
|
+
if (inspection.health.verdict === 'no-mark' || inspection.health.verdict === 'ok') {
|
|
3763
|
+
// The successful write path records the resulting counts. Refreshing here as
|
|
3764
|
+
// well would emit the same telemetry failure twice when the external mark is
|
|
3765
|
+
// unavailable, and would receipt a source transition before the command's
|
|
3766
|
+
// own row had landed.
|
|
3767
|
+
return true;
|
|
3768
|
+
}
|
|
3769
|
+
if (inspection.health.verdict === 'source-changed') {
|
|
3770
|
+
const counts = observedRows(inspection.rows);
|
|
3771
|
+
if (counts === undefined) return false;
|
|
3772
|
+
writeErr(`⚠ DZ STORE GUARD WARNING — SOURCE CHANGED: ${inspection.health.reason}; ${storeGuardResetCommand(projectRoot)}`);
|
|
3773
|
+
for (const line of lexicalSourceLines(inspection.rows)) writeErr(line);
|
|
3774
|
+
try {
|
|
3775
|
+
// Consume the single migration allowance BEFORE the store write. If the
|
|
3776
|
+
// following command fails, the safe result is a consumed allowance that
|
|
3777
|
+
// requires an explicit reset, never a silently reusable permission.
|
|
3778
|
+
writeStoreMark(projectRoot, { ...counts, observedAt: new Date().toISOString(), command }, {
|
|
3779
|
+
expectedPreviousLexicalSource: inspection.mark?.lexicalSource ?? 'unknown',
|
|
3780
|
+
});
|
|
3781
|
+
return true;
|
|
3782
|
+
} catch (error) {
|
|
3783
|
+
writeErr(`dz store guard: REFUSED — source-change allowance could not be recorded: ${error instanceof Error ? error.message : String(error)}`);
|
|
3784
|
+
return false;
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
|
|
3788
|
+
const allowed = process.env.DZ_ALLOW_COLD_START === '1' || flags.has('allow-cold-start');
|
|
3789
|
+
if (allowed) {
|
|
3790
|
+
const label = inspection.health.verdict.replaceAll('-', ' ').toUpperCase();
|
|
3791
|
+
writeErr(`⚠ DZ STORE GUARD WARNING — ${label}: ${inspection.health.reason}; explicit cold-start override accepted`);
|
|
3792
|
+
return true;
|
|
3793
|
+
}
|
|
3794
|
+
for (const line of storeGuardRecoveryLines(projectRoot, inspection.mark, inspection.health, inspection.rows)) writeErr(line);
|
|
3795
|
+
return false;
|
|
3796
|
+
}
|
|
3797
|
+
|
|
3798
|
+
/** Readers warn on damage and bootstrap/refresh a healthy non-empty store mark. */
|
|
3799
|
+
function warnLearningStoreRead(projectRoot: string, writeErr: WriteErr, command: string): void {
|
|
3800
|
+
try {
|
|
3801
|
+
const { health, rows, mark } = inspectLearningStore(projectRoot);
|
|
3802
|
+
if (health.verdict === 'collapsed' || health.verdict === 'cold-start-over-existing' || health.verdict === 'unreadable'
|
|
3803
|
+
|| health.verdict === 'source-changed') {
|
|
3804
|
+
writeErr(`⚠ DZ STORE GUARD WARNING — ${health.verdict.replaceAll('-', ' ').toUpperCase()}: ${health.reason}`);
|
|
3805
|
+
for (const line of lexicalSourceLines(rows)) writeErr(line);
|
|
3806
|
+
return;
|
|
3807
|
+
}
|
|
3808
|
+
const counts = observedRows(rows);
|
|
3809
|
+
if (counts !== undefined && counts.lexicalRows + counts.vectorRows > 0
|
|
3810
|
+
&& (mark === undefined || mark.lexicalLast !== counts.lexicalRows || mark.vectorLast !== counts.vectorRows
|
|
3811
|
+
|| mark.lexicalSource !== counts.lexicalSource
|
|
3812
|
+
|| mark.lexicalMax < counts.lexicalRows || mark.vectorMax < counts.vectorRows)) {
|
|
3813
|
+
refreshLearningStoreMark(projectRoot, writeErr, command, { reader: true });
|
|
3814
|
+
}
|
|
3815
|
+
} catch (error) {
|
|
3816
|
+
writeErr(`⚠ DZ STORE GUARD WARNING — external mark unreadable: ${error instanceof Error ? error.message : String(error)}`);
|
|
3817
|
+
}
|
|
3818
|
+
}
|
|
3819
|
+
|
|
3820
|
+
async function cmdStoreGuard(
|
|
3821
|
+
options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr,
|
|
3822
|
+
stdinText: string | undefined, interactive: boolean,
|
|
3823
|
+
): Promise<number> {
|
|
3824
|
+
const projectRoot = resolve(cwd, options.get('project') ?? '.');
|
|
3825
|
+
const path = storeGuardPath(projectRoot);
|
|
3826
|
+
const reset = flags.has('reset');
|
|
3827
|
+
const status = flags.has('status') || options.has('status');
|
|
3828
|
+
if (reset && status) {
|
|
3829
|
+
writeErr('dz store-guard: --status and --reset are mutually exclusive');
|
|
3830
|
+
return 2;
|
|
3831
|
+
}
|
|
3832
|
+
if (reset) {
|
|
3833
|
+
const rows = countLearningStoreRowsReadonly(projectRoot);
|
|
3834
|
+
const counts = observedRows(rows);
|
|
3835
|
+
if (counts === undefined) {
|
|
3836
|
+
writeErr(`dz store-guard: REFUSED — cannot reset from an unreadable store; mark: ${path}`);
|
|
3837
|
+
return 1;
|
|
3838
|
+
}
|
|
3839
|
+
try {
|
|
3840
|
+
const previous = readStoreMark(projectRoot);
|
|
3841
|
+
const beforeLexical = previous?.lexicalMax ?? counts.lexicalRows;
|
|
3842
|
+
const beforeVector = previous?.vectorMax ?? counts.vectorRows;
|
|
3843
|
+
writeErr('⚠ dz store-guard --reset: manual operator decision required; this lowers the recorded high-water evidence');
|
|
3844
|
+
writeErr(` old maximum: lexical=${beforeLexical}, vector=${beforeVector}`);
|
|
3845
|
+
writeErr(` new observed: lexical=${counts.lexicalRows} (${counts.lexicalSource}), vector=${counts.vectorRows}`);
|
|
3846
|
+
for (const line of lexicalSourceLines(rows)) writeErr(line);
|
|
3847
|
+
let answer = stdinText?.trim().split(/\r?\n/, 1)[0]?.trim().toLowerCase() ?? '';
|
|
3848
|
+
if (!flags.has('yes') && answer === '' && interactive && process.stdin.isTTY) {
|
|
3849
|
+
const { createInterface } = await import('node:readline/promises');
|
|
3850
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
3851
|
+
try { answer = (await rl.question(' type yes to continue: ')).trim().toLowerCase(); }
|
|
3852
|
+
finally { rl.close(); }
|
|
3853
|
+
}
|
|
3854
|
+
if (!flags.has('yes') && !['y', 'yes', 'да'].includes(answer)) {
|
|
3855
|
+
writeErr(`dz store-guard: REFUSED — reset was not confirmed; re-run with --yes or answer yes`);
|
|
3856
|
+
return 1;
|
|
3857
|
+
}
|
|
3858
|
+
const current = countLearningStoreRowsReadonly(projectRoot);
|
|
3859
|
+
const currentCounts = observedRows(current);
|
|
3860
|
+
if (currentCounts === undefined || !isDeepStrictEqual(currentCounts, counts)) {
|
|
3861
|
+
writeErr('dz store-guard: REFUSED — store counts changed after confirmation; inspect and confirm again');
|
|
3862
|
+
return 1;
|
|
3863
|
+
}
|
|
3864
|
+
const mark = resetStoreMark(projectRoot, {
|
|
3865
|
+
...counts,
|
|
3866
|
+
observedAt: new Date().toISOString(),
|
|
3867
|
+
command: 'dz store-guard --reset',
|
|
3868
|
+
});
|
|
3869
|
+
write(`dz store-guard: RESET — accepted lexical=${mark.lexicalMax}, vector=${mark.vectorMax}`);
|
|
3870
|
+
write(` mark: ${path}`);
|
|
3871
|
+
write(` receipt: ${mark.resetAt?.at} — ${mark.resetAt?.reason}`);
|
|
3872
|
+
return 0;
|
|
3873
|
+
} catch (error) {
|
|
3874
|
+
writeErr(`dz store-guard: reset failed — ${error instanceof Error ? error.message : String(error)}; mark: ${path}`);
|
|
3875
|
+
return 1;
|
|
3876
|
+
}
|
|
3877
|
+
}
|
|
3878
|
+
try {
|
|
3879
|
+
const inspection = inspectLearningStore(projectRoot);
|
|
3880
|
+
write(`dz store-guard: ${inspection.health.verdict.toUpperCase()} — ${inspection.health.reason}`);
|
|
3881
|
+
write(` mark: ${path}`);
|
|
3882
|
+
write(` current rows: lexical=${inspection.rows.lexicalRows}, vector=${inspection.rows.vectorRows}`);
|
|
3883
|
+
for (const line of lexicalSourceLines(inspection.rows)) write(line);
|
|
3884
|
+
write(` recorded: ${inspection.mark === undefined ? 'none' : JSON.stringify(inspection.mark)}`);
|
|
3885
|
+
return 0;
|
|
3886
|
+
} catch (error) {
|
|
3887
|
+
writeErr(`dz store-guard: mark unreadable — ${error instanceof Error ? error.message : String(error)}; mark: ${path}`);
|
|
3888
|
+
return 1;
|
|
3889
|
+
}
|
|
3890
|
+
}
|
|
3891
|
+
|
|
3435
3892
|
async function runTeachGuardReinforcement(
|
|
3436
3893
|
projectRoot: string,
|
|
3437
3894
|
dzId: string,
|
|
@@ -3465,6 +3922,12 @@ async function cmdTeach(
|
|
|
3465
3922
|
// repo's own store holds 361 records written under that behaviour, and every other user's store
|
|
3466
3923
|
// is the same. Only an explicit choice moves it.
|
|
3467
3924
|
const { storeRoot, target: teachTarget } = resolved;
|
|
3925
|
+
const teachWillWrite = flags.has('harmonize')
|
|
3926
|
+
? false
|
|
3927
|
+
: options.has('from-json')
|
|
3928
|
+
|| (options.get('reinforce') ?? '').trim() !== ''
|
|
3929
|
+
|| (options.get('_positional_0') ?? '').trim() !== '';
|
|
3930
|
+
if (teachWillWrite && !allowLearningStoreWrite(storeRoot, flags, writeErr, 'dz teach')) return 1;
|
|
3468
3931
|
// The verb is per OUTCOME, not per command: a harmonize dry-run and a failed --reinforce READ
|
|
3469
3932
|
// the store and change nothing, so saying "written" there is a false claim about what happened
|
|
3470
3933
|
// (cross-family QE round 2, 2026-08-27).
|
|
@@ -3501,10 +3964,11 @@ async function cmdTeach(
|
|
|
3501
3964
|
// Suppressed under --json: this line ahead of the report made stdout unparseable, which is a
|
|
3502
3965
|
// worse defect than the invisibility it was closing (measured live, cross-family QE round 2).
|
|
3503
3966
|
if (!flags.has('json')) write(storeLine(flags.has('apply') ? 'written' : 'read'));
|
|
3504
|
-
|
|
3967
|
+
const code = await runHarmonize(storeRoot, options, flags, write, writeErr, {
|
|
3505
3968
|
store: join(storeRoot, '.dz'),
|
|
3506
3969
|
storeChosenBy: teachTarget.reason,
|
|
3507
3970
|
});
|
|
3971
|
+
return code;
|
|
3508
3972
|
}
|
|
3509
3973
|
|
|
3510
3974
|
// Bulk import: `dz teach --from-json <file>` ingests a `dz recall --all --json`
|
|
@@ -3600,6 +4064,7 @@ async function cmdTeach(
|
|
|
3600
4064
|
const report = await harmonizeVectorStore(storeRoot, {});
|
|
3601
4065
|
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`);
|
|
3602
4066
|
}
|
|
4067
|
+
if (imported > 0) refreshLearningStoreMark(storeRoot, writeErr, 'dz teach --from-json');
|
|
3603
4068
|
return 0;
|
|
3604
4069
|
}
|
|
3605
4070
|
|
|
@@ -3620,6 +4085,7 @@ async function cmdTeach(
|
|
|
3620
4085
|
const clearedQ = clearAgentdbQuarantine(storeRoot, [reinforce]);
|
|
3621
4086
|
if (clearedQ.cleared > 0) write(` ↳ promoted out of quarantine (mirror updated)`);
|
|
3622
4087
|
write(storeLine('written'));
|
|
4088
|
+
refreshLearningStoreMark(storeRoot, writeErr, 'dz teach --reinforce');
|
|
3623
4089
|
return 0;
|
|
3624
4090
|
}
|
|
3625
4091
|
// HIGH-fix: a no-match must NOT auto-teach the raw argument — callers pass dzIds or truncated
|
|
@@ -3667,6 +4133,7 @@ async function cmdTeach(
|
|
|
3667
4133
|
write(`↳ reinforced existing pattern ${verdict.dzId} (cos=${verdict.cosine.toFixed(2)}) — not re-added`);
|
|
3668
4134
|
const clearedQ = clearAgentdbQuarantine(storeRoot, [verdict.dzId]);
|
|
3669
4135
|
if (clearedQ.cleared > 0) write(' ↳ promoted out of quarantine (mirror updated)');
|
|
4136
|
+
refreshLearningStoreMark(storeRoot, writeErr, 'dz teach --guard');
|
|
3670
4137
|
return 0;
|
|
3671
4138
|
}
|
|
3672
4139
|
write(`dz teach --guard: reinforce of ${verdict.dzId} did not flush (backend off or write failure) — teaching the lesson normally instead`);
|
|
@@ -3780,10 +4247,16 @@ async function cmdTeach(
|
|
|
3780
4247
|
}
|
|
3781
4248
|
// The lexical write above is durable — the vector mirror is strictly best-effort (I-3).
|
|
3782
4249
|
await emitMirrorQ(storeRoot, recordsToMirror, 'dz-teach', quarantineOn);
|
|
4250
|
+
if (stored.records.length > 0) {
|
|
4251
|
+
write(` ID: ${stored.records.map((record) => patternRecordId(record)).join(', ')}`);
|
|
4252
|
+
refreshLearningStoreMark(storeRoot, writeErr, 'dz teach');
|
|
4253
|
+
}
|
|
3783
4254
|
return commandFailed ? 1 : 0;
|
|
3784
4255
|
}
|
|
3785
4256
|
|
|
3786
|
-
async function cmdConsolidate(
|
|
4257
|
+
async function cmdConsolidate(
|
|
4258
|
+
options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr,
|
|
4259
|
+
): Promise<number> {
|
|
3787
4260
|
const projectRoot = resolve(cwd, options.get('project') ?? '.');
|
|
3788
4261
|
const sessionsDirOpt = options.get('sessions-dir');
|
|
3789
4262
|
const pruneNoise = flags.has('prune-noise');
|
|
@@ -3802,6 +4275,8 @@ async function cmdConsolidate(options: Map<string, string>, flags: Set<string>,
|
|
|
3802
4275
|
if (res.error !== undefined) { write(`dz consolidate --prune-quarantine: ${res.error}`); return 1; }
|
|
3803
4276
|
write(`dz consolidate --prune-quarantine: removed ${res.removed} expired quarantined lesson(s)`);
|
|
3804
4277
|
if (res.snapshot !== undefined) write(` snapshot: ${res.snapshot}`);
|
|
4278
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz consolidate --prune-quarantine --apply');
|
|
4279
|
+
storeGuardResetReminder(projectRoot, writeErr, 'dz consolidate --prune-quarantine --apply');
|
|
3805
4280
|
return 0;
|
|
3806
4281
|
}
|
|
3807
4282
|
|
|
@@ -3899,6 +4374,10 @@ async function cmdConsolidate(options: Map<string, string>, flags: Set<string>,
|
|
|
3899
4374
|
}
|
|
3900
4375
|
} catch { /* best-effort — the ranking is advisory, never fails the consolidate */ }
|
|
3901
4376
|
|
|
4377
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz consolidate');
|
|
4378
|
+
if (pruneNoise && applyPrune) {
|
|
4379
|
+
storeGuardResetReminder(projectRoot, writeErr, 'dz consolidate --prune-noise --apply');
|
|
4380
|
+
}
|
|
3902
4381
|
return 0;
|
|
3903
4382
|
}
|
|
3904
4383
|
|
|
@@ -4011,6 +4490,7 @@ async function cmdRecallForget(
|
|
|
4011
4490
|
flags: Set<string>,
|
|
4012
4491
|
projectRoot: string,
|
|
4013
4492
|
write: Write,
|
|
4493
|
+
writeErr: WriteErr,
|
|
4014
4494
|
): Promise<number> {
|
|
4015
4495
|
const raw = options.get('forget') ?? '';
|
|
4016
4496
|
const ids = new Set(raw.split(',').map((s) => s.trim()).filter((s) => s !== ''));
|
|
@@ -4039,7 +4519,7 @@ async function cmdRecallForget(
|
|
|
4039
4519
|
return 0;
|
|
4040
4520
|
}
|
|
4041
4521
|
|
|
4042
|
-
const dest = join(projectRoot,
|
|
4522
|
+
const dest = join(storeSnapshotPath(projectRoot), `forget-${Date.now()}.json`);
|
|
4043
4523
|
const snap = snapshotStore(projectRoot, dest);
|
|
4044
4524
|
if (snap.error !== undefined) {
|
|
4045
4525
|
write(`dz recall --forget: snapshot failed (${snap.error}) — nothing removed; the store is not versioned`);
|
|
@@ -4050,6 +4530,8 @@ async function cmdRecallForget(
|
|
|
4050
4530
|
write(` snapshot: ${snap.path} (${snap.count} record(s))`);
|
|
4051
4531
|
if (result.error !== undefined) write(` ⚠ ${result.error}`);
|
|
4052
4532
|
write(' the vector mirror still holds them — run `dz vector reindex` to resync');
|
|
4533
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz recall --forget --apply');
|
|
4534
|
+
storeGuardResetReminder(projectRoot, writeErr, 'dz recall --forget --apply');
|
|
4053
4535
|
return 0;
|
|
4054
4536
|
}
|
|
4055
4537
|
|
|
@@ -4141,10 +4623,15 @@ async function cmdRecall(
|
|
|
4141
4623
|
classMatcher?: RecallPatternsOptions['classMatcher'],
|
|
4142
4624
|
): Promise<number> {
|
|
4143
4625
|
const projectRoot = resolve(cwd, options.get('project') ?? '.');
|
|
4626
|
+
warnLearningStoreRead(projectRoot, writeErr, 'dz recall');
|
|
4627
|
+
const globalRootForGuard = globalStoreRoot();
|
|
4628
|
+
if (!sameStore(projectRoot, globalRootForGuard) && existsSync(join(globalRootForGuard, '.dz', 'memory'))) {
|
|
4629
|
+
warnLearningStoreRead(globalRootForGuard, writeErr, 'dz recall');
|
|
4630
|
+
}
|
|
4144
4631
|
const asJson = flags.has('json');
|
|
4145
4632
|
const all = flags.has('all');
|
|
4146
4633
|
if (flags.has('usage')) return cmdRecallUsage(options, flags, projectRoot, write);
|
|
4147
|
-
if (options.has('forget')) return cmdRecallForget(options, flags, projectRoot, write);
|
|
4634
|
+
if (options.has('forget')) return cmdRecallForget(options, flags, projectRoot, write, writeErr);
|
|
4148
4635
|
if (options.has('promote')) return cmdRecallPromote(options, flags, projectRoot, write);
|
|
4149
4636
|
|
|
4150
4637
|
// --all: dump the entire learned store (backend-agnostic, via loadStorePatternsSync).
|
|
@@ -4706,7 +5193,7 @@ function renderHarmonize(report: HarmonizeReport, write: Write): void {
|
|
|
4706
5193
|
* `--apply` + `--dry-run` together is rejected; `--threshold` must be in `(0, 1]`; no flag ⇒ dry-run.
|
|
4707
5194
|
*/
|
|
4708
5195
|
async function runHarmonize(
|
|
4709
|
-
projectRoot: string, options: Map<string, string>, flags: Set<string>, write: Write,
|
|
5196
|
+
projectRoot: string, options: Map<string, string>, flags: Set<string>, write: Write, writeErr: WriteErr,
|
|
4710
5197
|
/**
|
|
4711
5198
|
* Where this harmonize is pointed and what chose it. Under `--json` the human store line is
|
|
4712
5199
|
* suppressed to keep stdout ONE document, so the destination has to travel INSIDE that document
|
|
@@ -4730,6 +5217,10 @@ async function runHarmonize(
|
|
|
4730
5217
|
}
|
|
4731
5218
|
}
|
|
4732
5219
|
const report = await harmonizeVectorStore(projectRoot, { apply, ...(threshold !== undefined ? { threshold } : {}) });
|
|
5220
|
+
if (apply && report.error === undefined) {
|
|
5221
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz vector harmonize --apply');
|
|
5222
|
+
storeGuardResetReminder(projectRoot, writeErr, 'dz vector harmonize --apply');
|
|
5223
|
+
}
|
|
4733
5224
|
if (flags.has('json')) {
|
|
4734
5225
|
write(JSON.stringify(storeAnnotation !== undefined ? { ...report, ...storeAnnotation } : report));
|
|
4735
5226
|
return report.error !== undefined ? 1 : 0;
|
|
@@ -4738,7 +5229,9 @@ async function runHarmonize(
|
|
|
4738
5229
|
return report.error !== undefined ? 1 : 0;
|
|
4739
5230
|
}
|
|
4740
5231
|
|
|
4741
|
-
async function cmdVector(
|
|
5232
|
+
async function cmdVector(
|
|
5233
|
+
options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr,
|
|
5234
|
+
): Promise<number> {
|
|
4742
5235
|
const projectRoot = resolve(cwd, options.get('project') ?? '.');
|
|
4743
5236
|
const sub = options.get('_positional_0');
|
|
4744
5237
|
|
|
@@ -4793,6 +5286,10 @@ async function cmdVector(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
4793
5286
|
if (sub === 'reindex') {
|
|
4794
5287
|
const report = await reindexVectorStore(projectRoot);
|
|
4795
5288
|
if (flags.has('json')) {
|
|
5289
|
+
if (report.error === undefined) {
|
|
5290
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz vector reindex');
|
|
5291
|
+
storeGuardResetReminder(projectRoot, writeErr, 'dz vector reindex');
|
|
5292
|
+
}
|
|
4796
5293
|
write(JSON.stringify(report));
|
|
4797
5294
|
return report.error !== undefined ? 1 : 0;
|
|
4798
5295
|
}
|
|
@@ -4810,6 +5307,8 @@ async function cmdVector(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
4810
5307
|
write(` ⚠ still in the previous embedding space: ${report.staleTaskTypes.join(', ')}`);
|
|
4811
5308
|
if (report.staleTaskTypes.includes('book-knowledge')) write(' run \`dz brain reindex\` to rebuild the brain\'s book vectors');
|
|
4812
5309
|
}
|
|
5310
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz vector reindex');
|
|
5311
|
+
storeGuardResetReminder(projectRoot, writeErr, 'dz vector reindex');
|
|
4813
5312
|
return 0;
|
|
4814
5313
|
}
|
|
4815
5314
|
|
|
@@ -4866,7 +5365,7 @@ async function cmdVector(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
4866
5365
|
// harmonize (alias: dz teach --harmonize) — SEMANTIC dedup of the learned store, NON-DESTRUCTIVE:
|
|
4867
5366
|
// dry-run by default (previews clusters, writes nothing); --apply drops after a restorable backup.
|
|
4868
5367
|
if (sub === 'harmonize') {
|
|
4869
|
-
return runHarmonize(projectRoot, options, flags, write);
|
|
5368
|
+
return runHarmonize(projectRoot, options, flags, write, writeErr);
|
|
4870
5369
|
}
|
|
4871
5370
|
|
|
4872
5371
|
// import <file.rvf> — the missing HALF of the RVF cycle: UPSERT-BY-dzId, never overwrites.
|
|
@@ -4878,6 +5377,7 @@ async function cmdVector(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
4878
5377
|
}
|
|
4879
5378
|
const report = await importRvfCheckpoint(projectRoot, resolve(cwd, src), {});
|
|
4880
5379
|
if (flags.has('json')) {
|
|
5380
|
+
if (report.error === undefined) refreshLearningStoreMark(projectRoot, writeErr, 'dz vector import');
|
|
4881
5381
|
write(JSON.stringify(report));
|
|
4882
5382
|
return report.error !== undefined ? 1 : 0;
|
|
4883
5383
|
}
|
|
@@ -4890,6 +5390,7 @@ async function cmdVector(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
4890
5390
|
if (report.skippedOrphans > 0) {
|
|
4891
5391
|
write(' ↳ orphan vectors have no local pattern — import the text first: dz teach --from-json <recall-export.json>, then re-run dz vector import');
|
|
4892
5392
|
}
|
|
5393
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz vector import');
|
|
4893
5394
|
return 0;
|
|
4894
5395
|
}
|
|
4895
5396
|
|
|
@@ -6339,6 +6840,19 @@ function cmdPublish(options: Map<string, string>, flags: Set<string>, cwd: strin
|
|
|
6339
6840
|
}
|
|
6340
6841
|
}
|
|
6341
6842
|
|
|
6843
|
+
const filterStr = options.get('filter');
|
|
6844
|
+
// SAFETY: trim + drop empty segments (mirrors --select at the top of cmdInit).
|
|
6845
|
+
// Parse before the guard pre-flight so its packed-secret scan uses the SAME scoped package set
|
|
6846
|
+
// that publishPackages receives below; an empty resulting list remains an explicit error.
|
|
6847
|
+
let filter: string[] | undefined;
|
|
6848
|
+
if (filterStr !== undefined) {
|
|
6849
|
+
filter = filterStr.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
|
|
6850
|
+
if (filter.length === 0) {
|
|
6851
|
+
write('dz publish: --filter requires a non-empty comma-separated list of package-name substrings');
|
|
6852
|
+
return 1;
|
|
6853
|
+
}
|
|
6854
|
+
}
|
|
6855
|
+
|
|
6342
6856
|
// dz guard pre-flight (ADR-002 option A): publish is the most dangerous, least-reversible self-mutation, so
|
|
6343
6857
|
// it ALWAYS runs the declarative guard first. A HARD violation refuses the publish; `--no-guard "<reason>"`
|
|
6344
6858
|
// is the logged escape hatch (the override lands in .dz/guard-audit.jsonl — visible, never silent).
|
|
@@ -6350,7 +6864,7 @@ function cmdPublish(options: Map<string, string>, flags: Set<string>, cwd: strin
|
|
|
6350
6864
|
write('dz publish: --no-guard requires a reason (it is logged): --no-guard "hotfix, guard re-run after"');
|
|
6351
6865
|
return 1;
|
|
6352
6866
|
}
|
|
6353
|
-
const guardResult = runGuardEvaluation(guardRoot, 'publish', undefined, noGuard);
|
|
6867
|
+
const guardResult = runGuardEvaluation(guardRoot, 'publish', undefined, noGuard, filter);
|
|
6354
6868
|
if (guardResult.verdict === 'block' && noGuard === undefined) {
|
|
6355
6869
|
write('dz publish: ✗ BLOCKED by dz guard (HARD invariant violated):');
|
|
6356
6870
|
for (const v of guardResult.violations.filter((x) => x.severity === 'hard')) write(` [BLOCK] ${v.rule}: ${v.detail}`);
|
|
@@ -6391,21 +6905,6 @@ function cmdPublish(options: Map<string, string>, flags: Set<string>, cwd: strin
|
|
|
6391
6905
|
const claimCheckOpt = (claimCheckRaw as 'off' | 'warn' | 'error' | undefined) ?? 'warn';
|
|
6392
6906
|
|
|
6393
6907
|
const bumpOnly = flags.has('bump-only');
|
|
6394
|
-
const filterStr = options.get('filter');
|
|
6395
|
-
// SAFETY: trim + drop empty segments (mirrors --select at the top of cmdInit).
|
|
6396
|
-
// Without this, `--filter ""` (e.g. an unset shell var) or a stray comma yields
|
|
6397
|
-
// [''] / ['', 'core'], and publishPackages matches with name.includes(''), which
|
|
6398
|
-
// is true for EVERY package — silently turning a scoped publish into a
|
|
6399
|
-
// whole-monorepo publish. An empty resulting list is an explicit error, never
|
|
6400
|
-
// "match all".
|
|
6401
|
-
let filter: string[] | undefined;
|
|
6402
|
-
if (filterStr !== undefined) {
|
|
6403
|
-
filter = filterStr.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
|
|
6404
|
-
if (filter.length === 0) {
|
|
6405
|
-
write('dz publish: --filter requires a non-empty comma-separated list of package-name substrings');
|
|
6406
|
-
return 1;
|
|
6407
|
-
}
|
|
6408
|
-
}
|
|
6409
6908
|
|
|
6410
6909
|
// SAFETY: dry-run is the DEFAULT. A real publish requires an EXPLICIT opt-in
|
|
6411
6910
|
// via --yes, --confirm, or --no-dry-run. Without one, we never bump or publish.
|
|
@@ -6599,6 +7098,13 @@ function cmdPublish(options: Map<string, string>, flags: Set<string>, cwd: strin
|
|
|
6599
7098
|
if (pkg.claimCheck && pkg.claimCheck.findings > 0 && pkg.status !== 'error') {
|
|
6600
7099
|
write(` ⚠ claim-check: ${pkg.claimCheck.findings} finding(s) (${pkg.claimCheck.high} high) in README.md`);
|
|
6601
7100
|
}
|
|
7101
|
+
// A dry run stops before build/sign/pack, so it says NOTHING about the gates below that line.
|
|
7102
|
+
// Printing what it did not check is what keeps a clean preview from reading as a clean publish
|
|
7103
|
+
// (measured 2026-09-02: a clean dry run preceded a RED real gate).
|
|
7104
|
+
if (pkg.notVerified && pkg.notVerified.length > 0) {
|
|
7105
|
+
write(` ⓘ холостой прогон НЕ проверял (${pkg.notVerified.length}):`);
|
|
7106
|
+
for (const item of pkg.notVerified) write(` · ${item}`);
|
|
7107
|
+
}
|
|
6602
7108
|
}
|
|
6603
7109
|
return report.errors > 0 ? 1 : 0;
|
|
6604
7110
|
}
|
|
@@ -8357,7 +8863,18 @@ function cmdAgentsSync(
|
|
|
8357
8863
|
const effect = flags.has('check') ? 'AGENTS.md would change' : 'AGENTS.md was not rewritten';
|
|
8358
8864
|
writeErr(`dz agents-sync: DRIFT — ${drifted.length} stale/missing section(s); ${effect}`);
|
|
8359
8865
|
for (const finding of drifted) writeErr(` ${finding.id}: ${finding.file} (${finding.status})`);
|
|
8360
|
-
|
|
8866
|
+
const unregistered = drifted.filter((finding) => finding.status === 'unregistered-section');
|
|
8867
|
+
if (unregistered.length > 0) {
|
|
8868
|
+
// ПОДСКАЗКА, ВЕДУЩАЯ НЕ ТУДА, ХУЖЕ ОТСУТСТВУЮЩЕЙ. Повторный `dz agents-sync` эту находку
|
|
8869
|
+
// НЕ лечит: реестр POLICY_SOURCES ведётся руками, и секция, не вписанная в него, не
|
|
8870
|
+
// попадёт в проекцию сколько ни синхронизируй. Раньше здесь печаталась общая подсказка —
|
|
8871
|
+
// читатель прогнал бы её и снова увидел ту же ошибку.
|
|
8872
|
+
writeErr('→ heal with: объяви секцию в POLICY_SOURCES (packages/@dzhechkov/harness-core/src/agents-policy.ts):');
|
|
8873
|
+
for (const finding of unregistered) {
|
|
8874
|
+
writeErr(` { id: '${finding.id}', file: '${finding.file}', heading: '…', why: '…', operativeClause: '…' }`);
|
|
8875
|
+
}
|
|
8876
|
+
writeErr(' затем: dz agents-sync');
|
|
8877
|
+
} else if (drifted.some((finding) => finding.id === 'dz:policies')) {
|
|
8361
8878
|
writeErr('→ heal with: repair duplicate/unmatched dz:policies markers, then run dz agents-sync');
|
|
8362
8879
|
} else {
|
|
8363
8880
|
writeErr('→ heal with: dz agents-sync');
|
|
@@ -8448,8 +8965,11 @@ const DEFAULT_STORE_CAP = 5000;
|
|
|
8448
8965
|
*/
|
|
8449
8966
|
const MAX_STUB_SCAN_FILES = 400;
|
|
8450
8967
|
|
|
8451
|
-
/**
|
|
8452
|
-
|
|
8968
|
+
/** Maximum packed-file size read by the publish secret scan. */
|
|
8969
|
+
const SECRET_SCAN_MAX_BYTES = 512 * 1024;
|
|
8970
|
+
|
|
8971
|
+
/** Read the optional `.dz/guard.json` — `{ rules?, storeCap?, stubWaivers?, secretWaivers? }`. Missing/broken ⇒ defaults. */
|
|
8972
|
+
function loadGuardConfig(root: string): { rules?: unknown[]; storeCap?: number; stubWaivers?: unknown[]; secretWaivers?: unknown[]; reviewRound?: { minGrade?: unknown } } {
|
|
8453
8973
|
const p = join(root, '.dz', 'guard.json');
|
|
8454
8974
|
if (!existsSync(p)) return {};
|
|
8455
8975
|
try {
|
|
@@ -8475,6 +8995,51 @@ function gatherReadmeCounts(root: string): { label: string; a: number; b: number
|
|
|
8475
8995
|
// (target repo without sitedoc — missing-evidence contract). But a file that EXISTS and no longer
|
|
8476
8996
|
// matches its anchored pattern emits a MISMATCH pair (a: -1) — silent non-extraction is the exact
|
|
8477
8997
|
// disease this contour cures (AM-1 applies to the guard path too, not only the CI test).
|
|
8998
|
+
// ЗНАЧКИ ПРОТИВ ДЕРЕВА, а не только README против README (бэклог 9cb30764).
|
|
8999
|
+
//
|
|
9000
|
+
// Прежде правило сверяло только числа МЕЖДУ документами: два согласованных документа могли
|
|
9001
|
+
// хором утверждать одно и то же неверное число, и правило молчало. Значок «пакетов: 52» стоял
|
|
9002
|
+
// при 55 публикуемых на диске — ИЗМЕРЕНО 2026-09-03. Меню обещает 32 блюда, официант
|
|
9003
|
+
// перечисляет 30, кухня готовит 38, и никто в ресторане не знает правду.
|
|
9004
|
+
//
|
|
9005
|
+
// Сверяются только числа, ВЫЧИСЛИМЫЕ ИЗ ДЕРЕВА. Значок «опубликовано в npm» сюда НЕ входит и
|
|
9006
|
+
// это сказано вслух: его источник — реестр, а не рабочая копия, и пара, которая делает вид, что
|
|
9007
|
+
// проверила его, была бы хуже отсутствующей.
|
|
9008
|
+
const badge = (s: string, name: string): number | null => {
|
|
9009
|
+
const m = s.match(new RegExp(`img\\.shields\\.io/badge/${name}-(\\d+)`));
|
|
9010
|
+
return m && m[1] ? Number(m[1]) : null;
|
|
9011
|
+
};
|
|
9012
|
+
const publishablePackages = ((): number | null => {
|
|
9013
|
+
const dir = join(root, 'packages', '@dzhechkov');
|
|
9014
|
+
if (!existsSync(dir)) return null;
|
|
9015
|
+
let n = 0;
|
|
9016
|
+
for (const name of readdirSync(dir)) {
|
|
9017
|
+
const pj = join(dir, name, 'package.json');
|
|
9018
|
+
if (!existsSync(pj)) continue;
|
|
9019
|
+
try {
|
|
9020
|
+
const j = JSON.parse(readFileSync(pj, 'utf8')) as { private?: unknown };
|
|
9021
|
+
if (j.private !== true) n += 1;
|
|
9022
|
+
} catch { /* нечитаемый манифест — не считается ни в одну сторону */ }
|
|
9023
|
+
}
|
|
9024
|
+
return n;
|
|
9025
|
+
})();
|
|
9026
|
+
const pkgBadge = badge(rootMd, 'packages');
|
|
9027
|
+
if (pkgBadge !== null && publishablePackages !== null) {
|
|
9028
|
+
pairs.push({ label: 'packages (root badge vs publishable package.json on disk)', a: pkgBadge, b: publishablePackages });
|
|
9029
|
+
}
|
|
9030
|
+
const presetBadge = badge(rootMd, 'presets');
|
|
9031
|
+
if (presetBadge !== null) {
|
|
9032
|
+
pairs.push({ label: 'presets (root badge vs PRESET_NAMES in the build)', a: presetBadge, b: PRESET_NAMES.length });
|
|
9033
|
+
}
|
|
9034
|
+
const targetBadge = badge(rootMd, 'targets');
|
|
9035
|
+
if (targetBadge !== null) {
|
|
9036
|
+
pairs.push({ label: 'targets (root badge vs TARGET_NAMES in the build)', a: targetBadge, b: TARGET_NAMES.length });
|
|
9037
|
+
}
|
|
9038
|
+
const cmdBadge = badge(rootMd, 'CLI%20commands');
|
|
9039
|
+
if (cmdBadge !== null && cliAll !== null) {
|
|
9040
|
+
pairs.push({ label: 'commands (root badge vs cli All Commands)', a: cmdBadge, b: cliAll });
|
|
9041
|
+
}
|
|
9042
|
+
|
|
8478
9043
|
const sitePair = (rel: string, re: RegExp, label: string): void => {
|
|
8479
9044
|
if (cliAll === null || !existsSync(join(root, rel))) return;
|
|
8480
9045
|
const found = num(read(rel), re);
|
|
@@ -8880,8 +9445,9 @@ function gatherVolumeShadowFacts(
|
|
|
8880
9445
|
}
|
|
8881
9446
|
|
|
8882
9447
|
/** Gather the facts one op needs. All I/O is best-effort — a missing signal skips its rule, never crashes. */
|
|
8883
|
-
function gatherGuardFacts(op: string, root: string, text: string | undefined, storeCap: number): Record<string, unknown> {
|
|
9448
|
+
function gatherGuardFacts(op: string, root: string, text: string | undefined, storeCap: number, publishFilter?: readonly string[]): Record<string, unknown> {
|
|
8884
9449
|
const facts: Record<string, unknown> = { op };
|
|
9450
|
+
const publishPackageRoots: string[] = [];
|
|
8885
9451
|
if (op === 'publish') {
|
|
8886
9452
|
// Advisory I/O: unreadable telemetry or fed state is absence of evidence, never a fabricated
|
|
8887
9453
|
// stale finding and never a publish blocker.
|
|
@@ -9013,6 +9579,13 @@ function gatherGuardFacts(op: string, root: string, text: string | undefined, st
|
|
|
9013
9579
|
} catch { /* not a git repo */ }
|
|
9014
9580
|
const versionByName = new Map<string, string>();
|
|
9015
9581
|
for (const m of manifests) if (m.name && typeof m.version === 'string') versionByName.set(m.name, m.version);
|
|
9582
|
+
publishPackageRoots.push(...located
|
|
9583
|
+
.filter(({ dir, m }) => m.private !== true && (
|
|
9584
|
+
publishFilter === undefined
|
|
9585
|
+
|| publishFilter.length === 0
|
|
9586
|
+
|| publishFilter.some((filter) => (m.name ?? '').includes(filter) || dir.includes(filter))
|
|
9587
|
+
))
|
|
9588
|
+
.map(({ dir }) => dir));
|
|
9016
9589
|
const pnpmWorkspace = existsSync(join(root, 'pnpm-workspace.yaml'));
|
|
9017
9590
|
const packages: { name: string; deps: Record<string, string> }[] = [];
|
|
9018
9591
|
for (const m of manifests) {
|
|
@@ -9026,6 +9599,82 @@ function gatherGuardFacts(op: string, root: string, text: string | undefined, st
|
|
|
9026
9599
|
packages.push({ name: m.name ?? '(unnamed)', deps });
|
|
9027
9600
|
}
|
|
9028
9601
|
facts['packages'] = packages;
|
|
9602
|
+
// sibling-dep-protocol: сырые спеки, БЕЗ подстановки версии. Подставленная версия выглядела бы
|
|
9603
|
+
// как обычный диапазон, и правило потеряло бы ровно то, что проверяет.
|
|
9604
|
+
const siblingDeps: { name: string; field: string; dep: string; spec: string }[] = [];
|
|
9605
|
+
for (const m of manifests) {
|
|
9606
|
+
if (m.private === true) continue;
|
|
9607
|
+
const fields = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const;
|
|
9608
|
+
for (const field of fields) {
|
|
9609
|
+
const table = (m as unknown as Record<string, unknown>)[field];
|
|
9610
|
+
if (typeof table !== 'object' || table === null) continue;
|
|
9611
|
+
for (const [dep, spec] of Object.entries(table as Record<string, unknown>)) {
|
|
9612
|
+
if (!dep.startsWith('@dzhechkov/') || typeof spec !== 'string') continue;
|
|
9613
|
+
siblingDeps.push({ name: m.name ?? '(unnamed)', field, dep, spec });
|
|
9614
|
+
}
|
|
9615
|
+
}
|
|
9616
|
+
}
|
|
9617
|
+
facts['siblingDeps'] = siblingDeps;
|
|
9618
|
+
// plugin-manifest-audit: каждый `.claude-plugin/plugin.json` в дереве. Обход ограничен по
|
|
9619
|
+
// глубине и не заходит в node_modules/dist — чужие манифесты не наши, и краснеть на них
|
|
9620
|
+
// значило бы отчитываться о том, чего мы не публикуем.
|
|
9621
|
+
const pluginManifests: { path: string; parseError?: string; name?: string; version?: string; description?: string }[] = [];
|
|
9622
|
+
const walkPlugins = (dir: string, depth: number): void => {
|
|
9623
|
+
if (depth > 4) return;
|
|
9624
|
+
let entries: Dirent[];
|
|
9625
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
9626
|
+
for (const e of entries) {
|
|
9627
|
+
// `out/` — СГЕНЕРИРОВАННОЕ публичное зеркало: те же манифесты, скопированные. Дефект в нём
|
|
9628
|
+
// есть дефект генератора, и он уже сообщается по источнику; вторая копия только удвоила бы
|
|
9629
|
+
// одну и ту же находку.
|
|
9630
|
+
if (!e.isDirectory() || e.name === 'node_modules' || e.name === 'dist' || e.name === 'out') continue;
|
|
9631
|
+
const full = join(dir, e.name);
|
|
9632
|
+
if (e.name === '.claude-plugin') {
|
|
9633
|
+
const manifest = join(full, 'plugin.json');
|
|
9634
|
+
if (!existsSync(manifest)) continue;
|
|
9635
|
+
try {
|
|
9636
|
+
const j = JSON.parse(readFileSync(manifest, 'utf8')) as Record<string, unknown>;
|
|
9637
|
+
const pick = (k: string): string | undefined => (typeof j[k] === 'string' ? j[k] as string : undefined);
|
|
9638
|
+
// Состав навыков — ОБЕ стороны инвентаризации, и ТОЛЬКО для коробки ОДНОГО ПАКЕТА.
|
|
9639
|
+
//
|
|
9640
|
+
// Корневая витрина сюда НЕ входит, и это не упрощение: её состав собирается из всего
|
|
9641
|
+
// монорепозитория через реестр, «что лежит на складе» для неё — не обход одного дерева,
|
|
9642
|
+
// а весь реестр, и ровно это уже проверяет `marketplace-parity` регенерацией. Первая
|
|
9643
|
+
// редакция этой проверки обошла корень с ограничением глубины и выдала 27 ЛОЖНЫХ
|
|
9644
|
+
// «объявлено, но не найдено» — навыки лежали глубже границы обхода (ИЗМЕРЕНО 2026-09-04,
|
|
9645
|
+
// поймано до коммита прогоном стража на этом же дереве).
|
|
9646
|
+
//
|
|
9647
|
+
// Сравниваются ПУТИ, как их объявил манифест, а не имена: два навыка с одинаковым
|
|
9648
|
+
// именем в разных подкаталогах — законная вещь, и сведение к имени их бы склеило.
|
|
9649
|
+
const boxRoot = dirname(full);
|
|
9650
|
+
const isRepoRoot = resolve(boxRoot) === resolve(root);
|
|
9651
|
+
const declaredSkills = Array.isArray(j['skills']) && !isRepoRoot
|
|
9652
|
+
? (j['skills'] as unknown[]).filter((x): x is string => typeof x === 'string')
|
|
9653
|
+
.map((rel) => rel.replace(/^\.\//, '').replace(/\/+$/, '')).filter(Boolean)
|
|
9654
|
+
: undefined;
|
|
9655
|
+
const skillsOnDisk = declaredSkills === undefined ? undefined : findSkillDirs(boxRoot);
|
|
9656
|
+
pluginManifests.push({
|
|
9657
|
+
path: relative(root, manifest),
|
|
9658
|
+
...(pick('name') !== undefined ? { name: pick('name')! } : {}),
|
|
9659
|
+
...(pick('version') !== undefined ? { version: pick('version')! } : {}),
|
|
9660
|
+
...(pick('description') !== undefined ? { description: pick('description')! } : {}),
|
|
9661
|
+
...(declaredSkills !== undefined ? { declaredSkills } : {}),
|
|
9662
|
+
...(skillsOnDisk !== undefined ? { skillsOnDisk } : {}),
|
|
9663
|
+
});
|
|
9664
|
+
} catch (error) {
|
|
9665
|
+
pluginManifests.push({
|
|
9666
|
+
path: relative(root, manifest),
|
|
9667
|
+
parseError: (error instanceof Error ? error.message : String(error)).replace(/\s+/g, ' ').slice(0, 200),
|
|
9668
|
+
});
|
|
9669
|
+
}
|
|
9670
|
+
continue;
|
|
9671
|
+
}
|
|
9672
|
+
if (e.name.startsWith('.')) continue;
|
|
9673
|
+
walkPlugins(full, depth + 1);
|
|
9674
|
+
}
|
|
9675
|
+
};
|
|
9676
|
+
walkPlugins(root, 0);
|
|
9677
|
+
facts['pluginManifests'] = pluginManifests;
|
|
9029
9678
|
facts['volume'] = gatherVolumeShadowFacts(root, located.map(({ dir, m }) => ({
|
|
9030
9679
|
dir,
|
|
9031
9680
|
name: m.name ?? dir,
|
|
@@ -9053,7 +9702,43 @@ function gatherGuardFacts(op: string, root: string, text: string | undefined, st
|
|
|
9053
9702
|
}
|
|
9054
9703
|
facts['licenceHold'] = holds;
|
|
9055
9704
|
} catch { /* unreadable tree — the rule reports nothing rather than inventing a violation */ }
|
|
9056
|
-
try { facts['drift'] = sweepSkillDrift(root, { scope:
|
|
9705
|
+
try { facts['drift'] = sweepSkillDrift(root, { scope: DRIFT_SWEEP_SCOPE, allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name); } catch { /* skip */ }
|
|
9706
|
+
// backlog-covers-features: каталоги фич, дата их ПОЯВЛЕНИЯ В ИСТОРИИ (не mtime — его двигает
|
|
9707
|
+
// любой посторонний процесс), оговорки из README фичи и тексты записей бэклога. Базовая дата
|
|
9708
|
+
// делает правило зелёным на приходе: 336 существующих каталогов заведены до правила.
|
|
9709
|
+
// Нечитаемое дерево ⇒ факт НЕ выставляется ⇒ правило молчит, а не выдумывает вердикт.
|
|
9710
|
+
try {
|
|
9711
|
+
const featDir = join(root, 'features');
|
|
9712
|
+
if (existsSync(featDir)) {
|
|
9713
|
+
const slugs = readdirSync(featDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
9714
|
+
const features = slugs.map((slug) => {
|
|
9715
|
+
let createdIso = '';
|
|
9716
|
+
try {
|
|
9717
|
+
createdIso = execSync(`git log --diff-filter=A --format=%aI -1 -- ${JSON.stringify('features/' + slug)}`,
|
|
9718
|
+
{ cwd: root, encoding: 'utf-8' }).trim().split('\n').filter(Boolean).pop() ?? '';
|
|
9719
|
+
} catch { /* нет в истории — функция засчитает как новый, это верный дефолт */ }
|
|
9720
|
+
let waiver: string | undefined;
|
|
9721
|
+
for (const f of ['README.md', '07_code_changes/change_manifest.md']) {
|
|
9722
|
+
try {
|
|
9723
|
+
const m = readFileSync(join(featDir, slug, f), 'utf-8')
|
|
9724
|
+
.match(/^\s*Backlog:\s*не заведено\s*[—-]\s*(.+)$/m);
|
|
9725
|
+
if (m && m[1] && m[1].trim() !== '') { waiver = m[1].trim(); break; }
|
|
9726
|
+
} catch { /* нет файла — не оговорка */ }
|
|
9727
|
+
}
|
|
9728
|
+
return { slug, createdIso, waiver };
|
|
9729
|
+
});
|
|
9730
|
+
const backlogTexts: string[] = [];
|
|
9731
|
+
try {
|
|
9732
|
+
for (const line of readFileSync(join(root, '.dz', 'backlog', 'ideas.jsonl'), 'utf-8').split('\n')) {
|
|
9733
|
+
if (line.trim() === '') continue;
|
|
9734
|
+
try { const o = JSON.parse(line) as { text?: unknown }; if (typeof o.text === 'string') backlogTexts.push(o.text); } catch { /* рваная строка */ }
|
|
9735
|
+
}
|
|
9736
|
+
} catch { /* стора нет */ }
|
|
9737
|
+
if (backlogTexts.length > 0) {
|
|
9738
|
+
facts['featureBacklog'] = { baseline: BACKLOG_COVERAGE_BASELINE, features, backlogTexts };
|
|
9739
|
+
}
|
|
9740
|
+
}
|
|
9741
|
+
} catch { /* нечитаемо — правило молчит */ }
|
|
9057
9742
|
facts['counts'] = gatherReadmeCounts(root);
|
|
9058
9743
|
// readme-first: from the WORKING-TREE diff (publishes happen pre-commit here), per package: does the
|
|
9059
9744
|
// change set contain its package.json (the version-bump signal) without its README.md?
|
|
@@ -9213,11 +9898,39 @@ function gatherGuardFacts(op: string, root: string, text: string | undefined, st
|
|
|
9213
9898
|
|
|
9214
9899
|
// no-stubs config waivers: `.dz/guard.json` `stubWaivers: [{path, reason}]` — path-keyed, reason
|
|
9215
9900
|
// MANDATORY (the feature-adr-setup --guards shape; the pure checker refuses a reasonless entry).
|
|
9216
|
-
const
|
|
9901
|
+
const guardConfig = loadGuardConfig(root);
|
|
9902
|
+
const stubWaivers = guardConfig.stubWaivers;
|
|
9217
9903
|
if (Array.isArray(stubWaivers)) facts['stubWaivers'] = stubWaivers;
|
|
9904
|
+
const secretWaivers = guardConfig.secretWaivers;
|
|
9905
|
+
if (Array.isArray(secretWaivers)) facts['secretWaivers'] = secretWaivers;
|
|
9218
9906
|
}
|
|
9219
9907
|
if (op === 'consolidate') {
|
|
9220
|
-
try { facts['drift'] = sweepSkillDrift(root, { scope:
|
|
9908
|
+
try { facts['drift'] = sweepSkillDrift(root, { scope: DRIFT_SWEEP_SCOPE, allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name); } catch { /* skip */ }
|
|
9909
|
+
}
|
|
9910
|
+
if (op === 'publish') {
|
|
9911
|
+
const secretTargets: { label: string; text: string }[] = [];
|
|
9912
|
+
let skipped = 0;
|
|
9913
|
+
for (const dir of publishPackageRoots) {
|
|
9914
|
+
const packageRoot = join(root, dir);
|
|
9915
|
+
let packed: string[];
|
|
9916
|
+
try { packed = listPackFiles(packageRoot); }
|
|
9917
|
+
catch { skipped++; continue; }
|
|
9918
|
+
for (const rel of packed) {
|
|
9919
|
+
const absolute = join(packageRoot, rel);
|
|
9920
|
+
try {
|
|
9921
|
+
const stat = lstatSync(absolute);
|
|
9922
|
+
if (!stat.isFile() || stat.size > SECRET_SCAN_MAX_BYTES) { skipped++; continue; }
|
|
9923
|
+
const content = readFileSync(absolute);
|
|
9924
|
+
if (content.subarray(0, 8 * 1024).includes(0)) { skipped++; continue; }
|
|
9925
|
+
secretTargets.push({
|
|
9926
|
+
label: relative(root, absolute).split(sep).join('/'),
|
|
9927
|
+
text: content.toString('utf8'),
|
|
9928
|
+
});
|
|
9929
|
+
} catch { skipped++; }
|
|
9930
|
+
}
|
|
9931
|
+
}
|
|
9932
|
+
if (secretTargets.length > 0) facts['secretTargets'] = secretTargets;
|
|
9933
|
+
if (skipped > 0) facts['secretScan'] = { skipped };
|
|
9221
9934
|
}
|
|
9222
9935
|
if (op === 'teach' || op === 'consolidate') {
|
|
9223
9936
|
if (op === 'teach' && text) facts['secretTargets'] = [{ label: 'lesson', text }];
|
|
@@ -9233,13 +9946,13 @@ function gatherGuardFacts(op: string, root: string, text: string | undefined, st
|
|
|
9233
9946
|
* shared by `dz guard check` and the `dz publish` pre-flight (ADR-002 option A) so they can never disagree.
|
|
9234
9947
|
* `overrideReason` (when the caller forces through a block) is logged, never silent.
|
|
9235
9948
|
*/
|
|
9236
|
-
function runGuardEvaluation(root: string, op: string, text: string | undefined, overrideReason: string | undefined): ReturnType<typeof evaluateGuard> {
|
|
9949
|
+
function runGuardEvaluation(root: string, op: string, text: string | undefined, overrideReason: string | undefined, publishFilter?: readonly string[]): ReturnType<typeof evaluateGuard> {
|
|
9237
9950
|
const cfg = loadGuardConfig(root);
|
|
9238
9951
|
// Number.isFinite, not just > 0: a config `storeCap: 1e400` parses to Infinity, passes `> 0`, and would
|
|
9239
9952
|
// silently DISABLE the cap (count <= Infinity always). Non-finite ⇒ fall back to the default.
|
|
9240
9953
|
const storeCap = typeof cfg.storeCap === 'number' && Number.isFinite(cfg.storeCap) && cfg.storeCap > 0 ? cfg.storeCap : DEFAULT_STORE_CAP;
|
|
9241
9954
|
const rules = resolveRules(Array.isArray(cfg.rules) ? (cfg.rules as never[]) : undefined);
|
|
9242
|
-
const facts = gatherGuardFacts(op, root, text, storeCap);
|
|
9955
|
+
const facts = gatherGuardFacts(op, root, text, storeCap, publishFilter);
|
|
9243
9956
|
const result = evaluateGuard(facts as never, rules);
|
|
9244
9957
|
// audit (append-only). ts is real time here (a CLI, not the sandboxed workflow).
|
|
9245
9958
|
try {
|
|
@@ -10038,15 +10751,52 @@ async function cmdMrRakes(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
10038
10751
|
* --threshold N drill threshold (default 2 — anti-noise: a first-seen rake accrues, never drills)
|
|
10039
10752
|
* --no-teach drill only; do NOT write the store (skip the agent side)
|
|
10040
10753
|
* --project <dir> pin the teach ledger
|
|
10041
|
-
* --install-hook print the opt-in
|
|
10754
|
+
* --install-hook print the opt-in hook set to add (non-destructive): Stop scan-tail +
|
|
10755
|
+
* PreCompact/SessionEnd full retro (feature narrated-error-must-be-taught)
|
|
10756
|
+
* --scan-tail per-turn Stop-hook mode: incremental admission-debt scan, O(new bytes) —
|
|
10757
|
+
* writes/clears .dz/retro-pending.json; no ledger, no teach, no git subprocess
|
|
10758
|
+
* --transcript <p> the transcript --scan-tail must read. Without it the Stop hook's own stdin
|
|
10759
|
+
* payload (`transcript_path`) is used; with neither, the scan REFUSES
|
|
10760
|
+
* (NOT-ESTABLISHED) rather than guessing the newest file on disk
|
|
10042
10761
|
*/
|
|
10043
|
-
async function cmdRetro(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): Promise<number> {
|
|
10762
|
+
async function cmdRetro(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, readStdin: () => string = () => ''): Promise<number> {
|
|
10763
|
+
if (flags.has('scan-tail')) {
|
|
10764
|
+
// Per-turn primary detector (ADR-001 D2). Cost budget IS the design: no `git rev-parse`
|
|
10765
|
+
// subprocess (hooks run with cwd = project root; CLAUDE_PROJECT_DIR pins it), no store open,
|
|
10766
|
+
// O(new bytes) via the persisted offset. Always exit 0 — a Stop hook must never fail a turn.
|
|
10767
|
+
const root = process.env['CLAUDE_PROJECT_DIR'] ?? cwd;
|
|
10768
|
+
// WHICH transcript. Round 3, P1-3: this used to fall back to `findLatestTranscript(root)`, so with
|
|
10769
|
+
// several sessions and their subagents alive at once it scanned whichever file had the newest
|
|
10770
|
+
// mtime — routinely another session's, advancing that session's offset and never seeing this
|
|
10771
|
+
// turn's admission. The Stop hook hands the exact path on stdin; with no path from any source the
|
|
10772
|
+
// answer is a stated refusal, never a guess. Still exit 0: a Stop hook must never fail a turn.
|
|
10773
|
+
const picked = resolveScanTailTranscript({
|
|
10774
|
+
flag: options.get('transcript'),
|
|
10775
|
+
positional: options.get('_positional_0'),
|
|
10776
|
+
stdin: readStdin(),
|
|
10777
|
+
});
|
|
10778
|
+
if (picked.path === null) {
|
|
10779
|
+
const reason = picked.reason ?? 'no transcript path';
|
|
10780
|
+
if (flags.has('json')) write(JSON.stringify({ status: 'not-established', source: 'none', reason, scannedBytes: 0, offset: 0 }));
|
|
10781
|
+
else 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>\`.`);
|
|
10782
|
+
return 0;
|
|
10783
|
+
}
|
|
10784
|
+
const outcome = runRetroTailScan(join(root, '.dz'), picked.path);
|
|
10785
|
+
if (flags.has('json')) write(JSON.stringify({ ...outcome, source: picked.source }));
|
|
10786
|
+
else if (outcome.status === 'pending') write(`retro scan-tail: unpaid admission — .dz/retro-pending.json armed («${(outcome.snippet ?? '').slice(0, 60)}…»)`);
|
|
10787
|
+
return 0;
|
|
10788
|
+
}
|
|
10789
|
+
|
|
10044
10790
|
let repoRoot = cwd;
|
|
10045
10791
|
try { repoRoot = execSync('git rev-parse --show-toplevel', { cwd, encoding: 'utf-8' }).trim() || cwd; } catch { /* not git */ }
|
|
10046
10792
|
|
|
10047
10793
|
if (flags.has('install-hook')) {
|
|
10048
|
-
write('Add
|
|
10049
|
-
write(JSON.stringify({ hooks: {
|
|
10794
|
+
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):');
|
|
10795
|
+
write(JSON.stringify({ hooks: {
|
|
10796
|
+
Stop: [{ hooks: [{ type: 'command', command: 'dz retro --scan-tail', timeout: 10000, continueOnError: true }] }],
|
|
10797
|
+
PreCompact: [{ hooks: [{ type: 'command', command: 'dz retro', timeout: 60000, continueOnError: true }] }],
|
|
10798
|
+
SessionEnd: [{ hooks: [{ type: 'command', command: 'dz retro', timeout: 60000, continueOnError: true }] }],
|
|
10799
|
+
} }, null, 2));
|
|
10050
10800
|
return 0;
|
|
10051
10801
|
}
|
|
10052
10802
|
|
|
@@ -10283,6 +11033,43 @@ function cmdChallenge(options: Map<string, string>, flags: Set<string>, cwd: str
|
|
|
10283
11033
|
* decide (dz's rule — a false gate kills trust). Exit code is 0 on a clean run regardless of verdict; 2 only on
|
|
10284
11034
|
* a usage/setup error, so a caller distinguishes "gate ran" from "gate could not run".
|
|
10285
11035
|
*/
|
|
11036
|
+
/**
|
|
11037
|
+
* Есть ли в этом каталоге НЕЗАКОММИЧЕННЫЕ правки. Это и отличает «фича ещё в рабочем дереве»
|
|
11038
|
+
* (тогда `HEAD` — законная предфичевая база) от «фича уже закоммичена» (тогда `HEAD` её содержит).
|
|
11039
|
+
*
|
|
11040
|
+
* Не удалось спросить git — возвращается null, и вызывающий обязан считать положение НЕ
|
|
11041
|
+
* УСТАНОВЛЕННЫМ, а не выбрать удобный ответ.
|
|
11042
|
+
*/
|
|
11043
|
+
/**
|
|
11044
|
+
* Каталоги с `SKILL.md` внутри коробки ОДНОГО пакета — то, что РЕАЛЬНО лежит на складе.
|
|
11045
|
+
* Возвращаются ПУТИ относительно коробки, как их объявляет манифест, а не имена.
|
|
11046
|
+
*/
|
|
11047
|
+
function findSkillDirs(boxRoot: string): string[] {
|
|
11048
|
+
const found = new Set<string>();
|
|
11049
|
+
const walk = (dir: string, depth: number): void => {
|
|
11050
|
+
if (depth > 4) return;
|
|
11051
|
+
let entries: Dirent[];
|
|
11052
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
11053
|
+
for (const e of entries) {
|
|
11054
|
+
if (!e.isDirectory() || e.name === 'node_modules' || e.name === 'dist' || e.name.startsWith('.')) continue;
|
|
11055
|
+
const full = join(dir, e.name);
|
|
11056
|
+
if (existsSync(join(full, 'SKILL.md'))) found.add(relative(boxRoot, full));
|
|
11057
|
+
walk(full, depth + 1);
|
|
11058
|
+
}
|
|
11059
|
+
};
|
|
11060
|
+
walk(boxRoot, 0);
|
|
11061
|
+
return [...found];
|
|
11062
|
+
}
|
|
11063
|
+
|
|
11064
|
+
function hasUncommittedChangesIn(repoRoot: string, dir: string): boolean | null {
|
|
11065
|
+
try {
|
|
11066
|
+
const out = execSync(`git status --porcelain -- ${JSON.stringify(dir)}`, { cwd: repoRoot, encoding: 'utf-8' });
|
|
11067
|
+
return out.split('\n').some((line) => line.trim() !== '');
|
|
11068
|
+
} catch {
|
|
11069
|
+
return null;
|
|
11070
|
+
}
|
|
11071
|
+
}
|
|
11072
|
+
|
|
10286
11073
|
function cmdDiscriminationCheck(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
|
|
10287
11074
|
let repoRoot = cwd;
|
|
10288
11075
|
try { repoRoot = execSync('git rev-parse --show-toplevel', { cwd, encoding: 'utf-8' }).trim() || cwd; } catch { /* not git */ }
|
|
@@ -10295,7 +11082,22 @@ function cmdDiscriminationCheck(options: Map<string, string>, flags: Set<string>
|
|
|
10295
11082
|
const nameFilter = options.get('name');
|
|
10296
11083
|
const propertyTests = testArg.split(',').map((s) => s.trim()).filter(Boolean).map((file) =>
|
|
10297
11084
|
nameFilter !== undefined && nameFilter.trim() !== '' ? { file, name: nameFilter.trim() } : { file });
|
|
10298
|
-
|
|
11085
|
+
/**
|
|
11086
|
+
* УМОЛЧАНИЕ БАЗЫ РАЗЛИЧАЕТ ДВА РАЗНЫХ ПОЛОЖЕНИЯ, потому что они и правда разные.
|
|
11087
|
+
*
|
|
11088
|
+
* В штатном ходе конвейера правка Шага 7 ЕЩЁ НЕ ЗАКОММИЧЕНА, и тогда `HEAD` — настоящая
|
|
11089
|
+
* предфичевая база; так конвейер и зовёт гейт (`--base HEAD`, причина записана в его тексте).
|
|
11090
|
+
*
|
|
11091
|
+
* Но если фича УЖЕ ЗАКОММИЧЕНА, `HEAD` её содержит, и гейт сравнивает фичу С САМОЙ СОБОЙ.
|
|
11092
|
+
* ИЗМЕРЕНО 2026-09-04: такой прогон дал уверенное `NON_DISCRIMINATING` с советом «усилить тест»
|
|
11093
|
+
* на тестах, которые дискриминируют; тот же прогон с верной базой дал `DISCRIMINATES_VIA_ERROR`.
|
|
11094
|
+
* Находка выглядела как утверждение О ТЕСТАХ, и автор пошёл бы чинить исправное.
|
|
11095
|
+
*
|
|
11096
|
+
* Различить эти положения можно ДЕТЕРМИНИРОВАННО: есть ли незакоммиченные правки в пакете, чьи
|
|
11097
|
+
* тесты названы. Есть — `HEAD` законен и используется как раньше. Нет — база не установлена, и
|
|
11098
|
+
* гейт ОТКАЗЫВАЕТСЯ (exit 3), вместо того чтобы измерять относительно самого себя.
|
|
11099
|
+
*/
|
|
11100
|
+
const explicitBase = options.get('base');
|
|
10299
11101
|
const runnerOpt = options.get('runner');
|
|
10300
11102
|
// R11: a hung runner is a loud non-answer, never a pass. Same default + parse shape as mutation-gate.
|
|
10301
11103
|
const timeoutOpt = Number(options.get('timeout') ?? '300000');
|
|
@@ -10338,9 +11140,35 @@ function cmdDiscriminationCheck(options: Map<string, string>, flags: Set<string>
|
|
|
10338
11140
|
// The pure half's path sanitation expects a REPO-RELATIVE package dir ('.'-rooted), not an
|
|
10339
11141
|
// absolute one — an absolute path is refused as unsafe-package-dir by design.
|
|
10340
11142
|
const packageDirRel = relative(repoRoot, packageDir) || '.';
|
|
11143
|
+
|
|
11144
|
+
// Умолчание базы решается ЗДЕСЬ, потому что только здесь известен пакет, чьи тесты названы.
|
|
11145
|
+
let baseRef: string;
|
|
11146
|
+
if (explicitBase !== undefined && explicitBase.trim() !== '') {
|
|
11147
|
+
baseRef = explicitBase.trim();
|
|
11148
|
+
} else {
|
|
11149
|
+
const dirty = hasUncommittedChangesIn(repoRoot, packageDirRel);
|
|
11150
|
+
if (dirty !== true) {
|
|
11151
|
+
write('dz discrimination-check: NOT-ESTABLISHED — предфичевая база не установлена.');
|
|
11152
|
+
write(dirty === null
|
|
11153
|
+
? ` Не удалось спросить git о состоянии ${packageDirRel}; выбирать удобный ответ вместо этого нельзя.`
|
|
11154
|
+
: ` В ${packageDirRel} нет незакоммиченных правок, значит фича УЖЕ в HEAD, и сравнение шло бы с самой собой.`);
|
|
11155
|
+
write(' Гейт сравнивает поведение ДО и ПОСЛЕ фичи; без базы сравнивать не с чем, а HEAD здесь');
|
|
11156
|
+
write(' дал бы уверенное NON_DISCRIMINATING на исправных тестах (ИЗМЕРЕНО 2026-09-04).');
|
|
11157
|
+
write(' Передайте --base <коммит перед фичей>, например `<sha коммита фичи>^`.');
|
|
11158
|
+
return 3;
|
|
11159
|
+
}
|
|
11160
|
+
// Штатный ход конвейера: правка Шага 7 ещё в рабочем дереве, HEAD — настоящая предфичевая база.
|
|
11161
|
+
baseRef = 'HEAD';
|
|
11162
|
+
write(`dz discrimination-check: база не задана; в ${packageDirRel} есть незакоммиченные правки, беру HEAD как предфичевую базу.`);
|
|
11163
|
+
}
|
|
11164
|
+
|
|
11165
|
+
// Провенанс базы едет в квитанцию вместе с самой базой: «явно указано» — утверждение о действии
|
|
11166
|
+
// человека, и писать его для HEAD, выбранного инструментом, значит подделывать происхождение
|
|
11167
|
+
// доказательства, на которое сошлются позже.
|
|
11168
|
+
const baseRefSupplied = explicitBase !== undefined && explicitBase.trim() !== '';
|
|
10341
11169
|
const planInput = runnerOpt !== undefined
|
|
10342
|
-
? { baseRef, propertyTests, runner: runnerOpt, packageTestScript, packageDevDependencies, packageDir: packageDirRel }
|
|
10343
|
-
: { baseRef, propertyTests, packageTestScript, packageDevDependencies, packageDir: packageDirRel };
|
|
11170
|
+
? { baseRef, baseRefSupplied, propertyTests, runner: runnerOpt, packageTestScript, packageDevDependencies, packageDir: packageDirRel }
|
|
11171
|
+
: { baseRef, baseRefSupplied, propertyTests, packageTestScript, packageDevDependencies, packageDir: packageDirRel };
|
|
10344
11172
|
const plan = planDiscriminationCheck(planInput);
|
|
10345
11173
|
|
|
10346
11174
|
if (!plan.runnable) {
|
|
@@ -12242,9 +13070,24 @@ function nameCheckScan(repoRoot: string): NameFacts {
|
|
|
12242
13070
|
// Command names come from the dispatcher AND from the help block: a name that dispatches but
|
|
12243
13071
|
// is undocumented is still taken, and so is the reverse.
|
|
12244
13072
|
if (f.name === 'cli.ts') {
|
|
12245
|
-
|
|
12246
|
-
|
|
12247
|
-
|
|
13073
|
+
// ONE enumeration, every consumer derives (ADR-001, feature command-count-triad). This
|
|
13074
|
+
// scan's question is "is the name TAKEN?", so taken = dispatched ∪ documented, which is
|
|
13075
|
+
// legitimately LARGER than the canonical command count — but it must be the SAME parse
|
|
13076
|
+
// the layer-1 parity test uses, not a second private regex that agrees by coincidence.
|
|
13077
|
+
// The any-indent `dispatchedCommandsIn` fallback stays for a cli.ts WITHOUT a main
|
|
13078
|
+
// `switch (command)` (none in this workspace today): a partial sweep would answer "free"
|
|
13079
|
+
// about a taken name, and that is the one answer this command may never give.
|
|
13080
|
+
let mainSwitchParsed = false;
|
|
13081
|
+
try {
|
|
13082
|
+
for (const c of dispatchedCommands(text)) commands.add(c);
|
|
13083
|
+
for (const c of documentedCommands(text)) commands.add(c);
|
|
13084
|
+
mainSwitchParsed = true;
|
|
13085
|
+
} catch { /* no main switch here — fall back to the broad regexes below */ }
|
|
13086
|
+
if (!mainSwitchParsed) {
|
|
13087
|
+
for (const c of dispatchedCommandsIn(text)) commands.add(c);
|
|
13088
|
+
const help = /^\s{2}dz ([a-z][a-z0-9-]*)/gm;
|
|
13089
|
+
for (let m = help.exec(text); m !== null; m = help.exec(text)) if (m[1] !== undefined) commands.add(m[1]);
|
|
13090
|
+
}
|
|
12248
13091
|
}
|
|
12249
13092
|
}
|
|
12250
13093
|
}
|
|
@@ -12258,6 +13101,71 @@ function nameCheckScan(repoRoot: string): NameFacts {
|
|
|
12258
13101
|
return { commands, modules, exports: exportsFound, scanned: { packages, files, exports: exportsFound.size, commands: commands.size } };
|
|
12259
13102
|
}
|
|
12260
13103
|
|
|
13104
|
+
/**
|
|
13105
|
+
* `dz brief-check <файл>` — проверить бриф роя на контракт вывода (ADR-001 swarm-brief-output-contract).
|
|
13106
|
+
*
|
|
13107
|
+
* Разбирает объявления брифа как ДАННЫЕ и отказывает поимённо: «бриф неверен» не говорит автору,
|
|
13108
|
+
* что чинить, поэтому каждое нарушение называет ключ и причину.
|
|
13109
|
+
*
|
|
13110
|
+
* ЧЕСТНЫЙ ПРЕДЕЛ печатается ВМЕСТЕ С ЗЕЛЁНЫМ ответом: проверено, что бриф ОБЪЯВИЛ каталог и
|
|
13111
|
+
* единицы, а не что агент им последует. Зелёная проверка, читаемая как гарантия поведения, хуже
|
|
13112
|
+
* её отсутствия.
|
|
13113
|
+
*/
|
|
13114
|
+
function cmdBriefCheck(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
|
|
13115
|
+
const json = flags.has('json');
|
|
13116
|
+
/**
|
|
13117
|
+
* ВЕТКА «ПРОВЕРИТЬ НЕ УДАЛОСЬ» ТОЖЕ ОБЯЗАНА ОТВЕТИТЬ JSON-ом (находка 11).
|
|
13118
|
+
*
|
|
13119
|
+
* `--json` печатал человеческую строку на несуществующем файле, и потребитель, читающий вывод как
|
|
13120
|
+
* JSON, получал ошибку разбора вместо структурного «не проверено». Признак `checked` — тот же
|
|
13121
|
+
* трихотомический вердикт, что и коды выхода, только для машины: не «бриф плох», а «мы про него
|
|
13122
|
+
* ничего не установили».
|
|
13123
|
+
*/
|
|
13124
|
+
const unchecked = (reason: string, detail: string): number => {
|
|
13125
|
+
if (json) write(JSON.stringify({ ok: false, checked: false, reason, detail }));
|
|
13126
|
+
else write(detail);
|
|
13127
|
+
return 2;
|
|
13128
|
+
};
|
|
13129
|
+
// Только позиционный аргумент: `--file` был необъявленным псевдонимом, и страж дрейфа флагов
|
|
13130
|
+
// справедливо на него указал — лишняя поверхность, которой нет в справке.
|
|
13131
|
+
const file = options.get('_positional_0');
|
|
13132
|
+
if (file === undefined || file.trim() === '') {
|
|
13133
|
+
const code = unchecked('no-file', 'dz brief-check: name the brief file — dz brief-check <file> [--json]');
|
|
13134
|
+
if (!json) write(' A brief must declare: ' + SWARM_BRIEF_CONTRACT.map((c: { key: string }) => c.key).join(', '));
|
|
13135
|
+
return code;
|
|
13136
|
+
}
|
|
13137
|
+
let text: string;
|
|
13138
|
+
try {
|
|
13139
|
+
text = readFileSync(resolve(cwd, file), 'utf-8');
|
|
13140
|
+
} catch {
|
|
13141
|
+
// Нечитаемый файл — НЕ «бриф плох»: мы про него ничего не установили. Отдельный код выхода,
|
|
13142
|
+
// чтобы отказ прибора не смешивался с отказом брифа.
|
|
13143
|
+
return unchecked('unreadable', `dz brief-check: cannot read ${visibleText(file)}`);
|
|
13144
|
+
}
|
|
13145
|
+
const result = checkSwarmBrief(text);
|
|
13146
|
+
if (json) {
|
|
13147
|
+
// `checked: true` — вторая половина того же различителя: потребитель отличает «проверено и
|
|
13148
|
+
// отвергнуто» от «проверить не удалось» полем, а не отсутствием поля.
|
|
13149
|
+
write(JSON.stringify({ ...result, checked: true }));
|
|
13150
|
+
return result.ok ? 0 : 1;
|
|
13151
|
+
}
|
|
13152
|
+
if (result.ok) {
|
|
13153
|
+
// ЗНАЧЕНИЯ ИЗ БРИФА ОБЕЗВРЕЖИВАЮТСЯ И В ЗЕЛЁНОЙ СТРОКЕ (находка 10). Отказ их уже обезвредил,
|
|
13154
|
+
// но подделывается ровно эта строка: управляющая последовательность в имени каталога стирает
|
|
13155
|
+
// предыдущий вывод и печатает поверх него подделку.
|
|
13156
|
+
write(`dz brief-check: OK — dir ${visibleText(result.outputDir ?? '')}, ${result.units.length} unit(s), assembly "${visibleText(result.assemblyUnit ?? '')}"`);
|
|
13157
|
+
write(' LIMIT: this verifies the brief DECLARED the contract, not that the agent will follow it —');
|
|
13158
|
+
write(' only comparing the directory against the unit list on an orchestrator tick can show that.');
|
|
13159
|
+
write(' A filled-in template and an unedited one both pass: the parse cannot tell them apart.');
|
|
13160
|
+
return 0;
|
|
13161
|
+
}
|
|
13162
|
+
write(`dz brief-check: REFUSED — ${result.violations.length} violation(s)`);
|
|
13163
|
+
// Ядро уже обезвредило значения в причинах; повтор на слое печати — не суеверие, а граница:
|
|
13164
|
+
// печатающий слой не обязан знать, кто именно из его источников уже почистил текст.
|
|
13165
|
+
for (const v of result.violations) write(` ${v.rule}: ${visibleText(v.detail)}`);
|
|
13166
|
+
return 1;
|
|
13167
|
+
}
|
|
13168
|
+
|
|
12261
13169
|
function cmdNameCheck(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
|
|
12262
13170
|
const repoRoot = resolve(options.get('project') ?? cwd);
|
|
12263
13171
|
const json = flags.has('json');
|
|
@@ -13141,12 +14049,24 @@ function cmdAmendmentCheck(options: Map<string, string>, flags: Set<string>, cwd
|
|
|
13141
14049
|
// Paths in an amendment row are repo-relative, so they resolve against the repo root — not
|
|
13142
14050
|
// against the feature directory, and not against wherever the caller happened to stand.
|
|
13143
14051
|
const resolutions = resolveAmendments(rows, { readFile: (rel) => readOr(resolve(cwd, rel)) });
|
|
14052
|
+
// A document that opens `## Amendments` twice cannot have its first heading answer for the
|
|
14053
|
+
// rest (Codex round 6, P2). Counted per document and taken at its worst — one contradictory
|
|
14054
|
+
// input is enough to make the run inconclusive.
|
|
14055
|
+
const sectionCount = Math.max(
|
|
14056
|
+
ideation === null ? 0 : amendmentSectionCount(ideation),
|
|
14057
|
+
plan === null ? 0 : amendmentSectionCount(plan),
|
|
14058
|
+
);
|
|
13144
14059
|
const decision = decideAmendmentOutcome({
|
|
13145
14060
|
sectionPresent,
|
|
13146
14061
|
rows,
|
|
13147
14062
|
resolutions,
|
|
13148
14063
|
planSaysNone: plan !== null && planSaysNoAmendments(plan),
|
|
13149
14064
|
missingFromPlan,
|
|
14065
|
+
sectionCount,
|
|
14066
|
+
// Fail-closed: measured on the document the rows would have come from (the plan when it has
|
|
14067
|
+
// a section, otherwise the ideation report).
|
|
14068
|
+
ambiguity: (plan !== null ? amendmentDeclarationAmbiguity(plan) : null)
|
|
14069
|
+
?? (ideation !== null ? amendmentDeclarationAmbiguity(ideation) : null),
|
|
13150
14070
|
});
|
|
13151
14071
|
return { slug, decision, resolutions };
|
|
13152
14072
|
};
|
|
@@ -15459,7 +16379,9 @@ function cmdDeliveryCheck(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15459
16379
|
/* ------------------------------------------------------------------ */
|
|
15460
16380
|
|
|
15461
16381
|
/** Thin dispatcher — ALL logic lives in harness-core/src/backlog.ts (05 architecture: handlers stay dumb). */
|
|
15462
|
-
async function cmdBacklog(
|
|
16382
|
+
async function cmdBacklog(
|
|
16383
|
+
options: Map<string, string>, flags: Set<string>, cwd: string, write: Write, writeErr: WriteErr,
|
|
16384
|
+
): Promise<number> {
|
|
15463
16385
|
const projectRoot = resolve(cwd, options.get('project') ?? '.');
|
|
15464
16386
|
const json = flags.has('json');
|
|
15465
16387
|
const sub = options.get('_positional_0');
|
|
@@ -15477,6 +16399,7 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15477
16399
|
const eff = parseEffort(options.get('effort'), cfg.roulette.defaultEffort);
|
|
15478
16400
|
if (eff.adjusted && !json && eff.note !== undefined) write(`dz backlog: ${eff.note}`);
|
|
15479
16401
|
const dryRun = flags.has('dry-run');
|
|
16402
|
+
if (!dryRun && !allowLearningStoreWrite(projectRoot, flags, writeErr, 'dz backlog add')) return 1;
|
|
15480
16403
|
// Embed-form migration (register-inflation fix): v1 vectors are FULL-TEXT embeds, v2 queries are
|
|
15481
16404
|
// bounded excerpts — comparing across the forms is a query-vs-row space split. Re-mirror once
|
|
15482
16405
|
// (idempotent upsert), before the dedup search. Dry-run writes nothing, so it only WARNS.
|
|
@@ -15505,6 +16428,7 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15505
16428
|
const ideas = readIdeas(projectRoot);
|
|
15506
16429
|
const match = ideas.find((i) => i.id === verdict.matchedId);
|
|
15507
16430
|
let absorbErr: string | undefined;
|
|
16431
|
+
let didWrite = false;
|
|
15508
16432
|
if (!dryRun && match !== undefined) {
|
|
15509
16433
|
const snap = snapshotIdeas(projectRoot, join(projectRoot, '.dz', 'backlog', `ideas.pre-merge-${Date.now()}.jsonl`));
|
|
15510
16434
|
if (snap.error !== undefined) return emitErr(snap.error);
|
|
@@ -15520,7 +16444,9 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15520
16444
|
}).error;
|
|
15521
16445
|
match.uses += 1;
|
|
15522
16446
|
writeIdeas(projectRoot, ideas);
|
|
16447
|
+
didWrite = true;
|
|
15523
16448
|
}
|
|
16449
|
+
if (didWrite) refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog add');
|
|
15524
16450
|
if (json) 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));
|
|
15525
16451
|
else {
|
|
15526
16452
|
const via = verdict.subsetMatch === true
|
|
@@ -15576,6 +16502,7 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15576
16502
|
ideas.push(rec);
|
|
15577
16503
|
writeIdeas(projectRoot, ideas);
|
|
15578
16504
|
const mirror = await mirrorIdeaVector(projectRoot, rec); // best-effort — never blocks capture
|
|
16505
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog add');
|
|
15579
16506
|
if (json) 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));
|
|
15580
16507
|
else {
|
|
15581
16508
|
write(`dz backlog: ${verdict.action.toUpperCase()} — captured ${rec.id}`);
|
|
@@ -15742,8 +16669,18 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15742
16669
|
if (commitId !== undefined) {
|
|
15743
16670
|
// Validated above (safe id + known id) BEFORE any early return.
|
|
15744
16671
|
const idx = ideas.findIndex((i) => i.id === commitId);
|
|
16672
|
+
// ОТМЕТКА ВРЕМЕНИ И ЖУРНАЛ ставятся ЗДЕСЬ, а не «где-нибудь потом».
|
|
16673
|
+
// Измерено 2026-09-02: `grep -c statusTs cli.ts` давал НОЛЬ — оба пути смены статуса в этом
|
|
16674
|
+
// файле меняли поле и не отмечали, когда. Отсюда 22 терминальные записи без отметки и
|
|
16675
|
+
// невычислимое «сколько идея пробыла в работе».
|
|
16676
|
+
const spinFrom = ideas[idx]!.status;
|
|
16677
|
+
const spinTs = new Date().toISOString();
|
|
15745
16678
|
ideas[idx]!.status = 'in-progress';
|
|
16679
|
+
ideas[idx]!.statusTs = spinTs;
|
|
15746
16680
|
writeIdeas(projectRoot, ideas);
|
|
16681
|
+
if (!appendTransition(projectRoot, { id: commitId, from: spinFrom, to: 'in-progress', ts: spinTs, by: 'backlog roulette --commit' })) {
|
|
16682
|
+
write('dz backlog: переход НЕ записан в журнал — наблюдение потеряно (сам статус изменён)');
|
|
16683
|
+
}
|
|
15747
16684
|
pick = ideas[idx]!;
|
|
15748
16685
|
committed = true;
|
|
15749
16686
|
}
|
|
@@ -15807,6 +16744,7 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15807
16744
|
if (mirror.mirrored > 0 && mirror.error === undefined && clearEmbedStale(projectRoot, report.id)) embed = 'ok';
|
|
15808
16745
|
else embed = 'stale';
|
|
15809
16746
|
} else embed = 'stale';
|
|
16747
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog edit');
|
|
15810
16748
|
}
|
|
15811
16749
|
if (json) {
|
|
15812
16750
|
write(JSON.stringify({ verb: 'edit', ...report, embed, exitCode: report.ok ? (embed === 'stale' ? 1 : 0) : 1 }, null, 2));
|
|
@@ -15834,9 +16772,15 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15834
16772
|
const goalMap = readGoalMap(projectRoot);
|
|
15835
16773
|
const related = ideas.filter((i) => rec.relatedIds.includes(i.id));
|
|
15836
16774
|
const staging = stageEnrichment(projectRoot, rec, related, goalMap);
|
|
16775
|
+
const enrichFrom = rec.status;
|
|
16776
|
+
const enrichTs = new Date().toISOString();
|
|
15837
16777
|
rec.status = 'enriched';
|
|
16778
|
+
rec.statusTs = enrichTs;
|
|
15838
16779
|
rec.enrichedPath = `features/${staging.slug}`;
|
|
15839
16780
|
writeIdeas(projectRoot, ideas);
|
|
16781
|
+
if (!appendTransition(projectRoot, { id: rec.id, from: enrichFrom, to: 'enriched', ts: enrichTs, by: 'backlog enrich' })) {
|
|
16782
|
+
write('dz backlog: переход НЕ записан в журнал — наблюдение потеряно (сам статус изменён)');
|
|
16783
|
+
}
|
|
15840
16784
|
if (json) write(JSON.stringify({ slug: staging.slug, scaffoldPath: staging.scaffoldPath, handoff: 'idea2prd-manual', exitCode: 0 }, null, 2));
|
|
15841
16785
|
else {
|
|
15842
16786
|
write(`dz backlog enrich: staged ${rec.id} → ${staging.scaffoldPath}`);
|
|
@@ -15876,6 +16820,10 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
15876
16820
|
if (form.action === 'migrated' && !json) write(`dz backlog: re-embedded ${form.remirrored} idea vector(s) into the bounded dedup embed form (v${form.version})`);
|
|
15877
16821
|
else if (form.action === 'deferred' && !json) write(`dz backlog: ⚠ embed-form migration deferred (${form.error ?? 'unknown error'})`);
|
|
15878
16822
|
const report = await harmonizeBacklog(projectRoot, { apply, ...(thr !== undefined ? { threshold: Number(thr) } : {}) });
|
|
16823
|
+
if (apply) {
|
|
16824
|
+
refreshLearningStoreMark(projectRoot, writeErr, 'dz backlog harmonize --apply');
|
|
16825
|
+
storeGuardResetReminder(projectRoot, writeErr, 'dz backlog harmonize --apply');
|
|
16826
|
+
}
|
|
15879
16827
|
if (json) {
|
|
15880
16828
|
write(JSON.stringify({ ...report, exitCode: 0 }, null, 2));
|
|
15881
16829
|
return 0;
|
|
@@ -16693,15 +17641,25 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
16693
17641
|
io.teachReinforceRunner ?? runTeachGuardReinforcement,
|
|
16694
17642
|
);
|
|
16695
17643
|
case 'consolidate':
|
|
16696
|
-
return await cmdConsolidate(options, flags, cwd, write);
|
|
17644
|
+
return await cmdConsolidate(options, flags, cwd, write, writeErr);
|
|
16697
17645
|
case 'recall':
|
|
16698
17646
|
return await cmdRecall(options, flags, cwd, write, writeErr, io.classMatcher);
|
|
16699
17647
|
case 'vector':
|
|
16700
|
-
return await cmdVector(options, flags, cwd, write);
|
|
17648
|
+
return await cmdVector(options, flags, cwd, write, writeErr);
|
|
16701
17649
|
case 'brain':
|
|
16702
17650
|
return await cmdBrain(options, flags, cwd, write, readStdin);
|
|
16703
17651
|
case 'statusline':
|
|
16704
|
-
return cmdStatusline(options, flags, cwd, write, readStdin);
|
|
17652
|
+
return cmdStatusline(options, flags, cwd, write, readStdin, writeErr);
|
|
17653
|
+
case 'store-guard':
|
|
17654
|
+
return await cmdStoreGuard(
|
|
17655
|
+
options,
|
|
17656
|
+
flags,
|
|
17657
|
+
cwd,
|
|
17658
|
+
write,
|
|
17659
|
+
writeErr,
|
|
17660
|
+
io.stdin,
|
|
17661
|
+
io.interactive ?? process.stdin.isTTY === true,
|
|
17662
|
+
);
|
|
16705
17663
|
case 'usage':
|
|
16706
17664
|
return cmdUsage(options, optionLists, flags, cwd, write);
|
|
16707
17665
|
case 'chain':
|
|
@@ -16769,7 +17727,7 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
16769
17727
|
case 'mr-rakes':
|
|
16770
17728
|
return await cmdMrRakes(options, flags, cwd, write);
|
|
16771
17729
|
case 'retro':
|
|
16772
|
-
return await cmdRetro(options, flags, cwd, write);
|
|
17730
|
+
return await cmdRetro(options, flags, cwd, write, readStdin);
|
|
16773
17731
|
case 'feature-adr-setup':
|
|
16774
17732
|
return cmdFeatureAdrSetup(options, flags, cwd, write, writeErr);
|
|
16775
17733
|
case 'challenge':
|
|
@@ -16814,6 +17772,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
16814
17772
|
return cmdTgPost(options, flags, cwd, write);
|
|
16815
17773
|
case 'name-check':
|
|
16816
17774
|
return cmdNameCheck(options, flags, cwd, write);
|
|
17775
|
+
case 'brief-check':
|
|
17776
|
+
return cmdBriefCheck(options, flags, cwd, write);
|
|
16817
17777
|
case 'provenance-check':
|
|
16818
17778
|
return cmdProvenanceCheck(options, flags, cwd, write);
|
|
16819
17779
|
case 'feature-adr-record':
|
|
@@ -16831,7 +17791,7 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
16831
17791
|
case 'qe-bridge':
|
|
16832
17792
|
return await cmdQeBridge(options, flags, cwd, write);
|
|
16833
17793
|
case 'backlog':
|
|
16834
|
-
return await cmdBacklog(options, flags, cwd, write);
|
|
17794
|
+
return await cmdBacklog(options, flags, cwd, write, writeErr);
|
|
16835
17795
|
case 'routing':
|
|
16836
17796
|
return cmdRouting(options, flags, cwd, write);
|
|
16837
17797
|
case 'bto-optimize':
|