/** * The `dz` CLI — argv parsing + dispatch over `@dzhechkov/harness-core`. * * @packageDocumentation */ import { appendFileSync, chmodSync, closeSync, cpSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'; import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { request as httpsRequest } from 'node:https'; import { KNOWN_CLI_FLAGS } from './known-flags.js'; import { isBooleanFlag } from './boolean-flags.js'; import { resolveInstallSpec } from './install-spec.js'; import { execFile, execFileSync, execSync, spawn, spawnSync, type ChildProcess } from 'node:child_process'; import { createHash, randomBytes } from 'node:crypto'; import { homedir, tmpdir } from 'node:os'; import { createRequire } from 'node:module'; import { createSkill, getSkillInfo, listSkillsDetailed, formatSkillLoadFailures, formatSkillApplyFailures, resolveTargetName, formatTargetProblem, formatTargetAliasNote, TARGET_NAMES_SORTED, runDoctor, runInit, resolvePackageSkillRoots, PACKAGE_SKILL_LAYOUTS, benchmarkSkill, benchmarkSkills, scanMcp, reconcileCapabilities, RECONCILE_BANNER, buildRegistry, discoverSkillPackDirs, discoverVerifiablePackDirs, checkUpstream, compareSkills, checkAllUpstream, sweepSkillDrift, syncCanonicalSkill, checkUpgrades, discoverPackages, discoverSourcePackages, fetchAllDownloads, filterByCategory, pretrain, recommend, generatePlugin, publishPackages, runSetup, runMigrate, searchRegistry, runSync, runVerify, runInitAgentsMd, runInitGeminiMd, runSyncAgentsPolicy, runSyncCodexHooks, resolveCodexHome, withNamedLockSync, // dz workflow run (feature dz-workflow-run): the pure scheduler + the dispatch adapters. TRACE_RUNID_RE, WF_RUN_OWNER_HOST, preflight, runWorkflow, makeClaudePDispatcher, makeCodexExecDispatcher, type ChildRunner, type Dispatcher, type DispatchResult, type RunStore, type RunnerInputs, type SchedulerDeps, type WfRunState, NamedLockTimeoutError, NamedLockCompromisedError, type CodexHooksSyncReport, type ParityCell, type ParityFeature, type ParityReportCell, type RuntimeCapability, POLICY_SOURCES, detectPolicyDrift, hasPolicyFence, TARGET_NAMES, buildParityMatrix, downgradeForStaleEvidence, findStaleTranscriptEvidence, TARGET_CAPABILITIES, TARGET_SHORT_LABELS, WORKFLOW_TEMPLATES_RETIRED_MESSAGE, parsePlan, isParseErrors, validatePlan, normalizePlan, planDigest, toTraceProjection, renderPlan, mergeRender, lint, lintExitCode, LOOP_BLOBS, parseTrace, assembleTimeline, runInvariants, deriveAttestation, stampAttestation, corroborate, NOT_WITNESSED, renderTimelineHtml, importEcc, recordPattern, resolveLearningBackend, storeStats, consolidateSessions, pruneNoisePatterns, lessonDeltaReport, removePatternsByIds, snapshotStore, recallHybrid, teachGuard, mirrorPatternsToVector, mirrorEntriesToVector, patternVectorEntry, readMemoryLearningConfig, promotePatterns, quarantineExpiryCandidates, pruneQuarantinePatterns, clearAgentdbQuarantine, vectorMirrorEnabled, vectorTierStatus, resolveVectorEngine, reindexVectorStore, harmonizeVectorStore, importRvfCheckpoint, statuslineData, writeFeatureAdrState, computeUsage, deriveCostLedger, planLedgerBackfill, listCostLedgerRuns, resolveLedgerRunId, AMBIGUOUS, stampCheckpointLine, LEDGER_FILL_SOURCE, renderCostLedger, verifyCostLedgerReport, writeCostLedgerJsonl, COST_LEDGER_SCOPE, deriveUsageCalibration, normalizeClaudeUsageModelKey, readUsageLimits, parseWeeklyResetAnchor, claimCheck, summarize, queryBookKnowledge, loadStorePatternsSync, patternRecordId, loadStoreRecords, recordToPattern, bundleSkills, brainHome, listBrain, bookKbPath, promoteProjectToBrain, updateBrainSource, queryBrain, groundPrompt, expandKu, reindexBrainVectors, buildPrimer, exportBrainSlice, importBrainSlice, registerKusToBrain, RECALL_USAGE_LOG_RELATIVE, RECALL_USAGE_LOG_MAX_BYTES, parseRecallUsageLog, buildRecallUsageReport, EVENT_CHAIN_TAIL_BYTES, EMPTY_LOG_TAIL, readTailInfo, appendChainedLines, verifyEventChainText, buildManifest, buildSbom, resolveTrustRoot, decideVerifyPolicy, generateSigningKeypair, evaluateGuard, resolveRules, auditRecord, guardExitCode, DEFAULT_RULES, parsePnpmLockImporters, scannableStubPath, // guard-promotion (feature guard-promotion, scout idea #1) assembleCandidates, renderPromotionReport, renderPromotionAdr, normalizePromotionState, nextPromotionState, globMatch, promotionAdrRelPath, DEFAULT_WINDOW_DAYS, DEFAULT_PERIODS, MAX_CONTENT_FETCHES, BUILTIN_COVERAGE, type ChangeSet, type ExistingRuleView, type PromotionReport, decideProvenance, isInsideTree, signManifest, verifyManifest, listSignablePackFiles, assertKeyOutsideTree, decidePublishGate, collectPackageFacts, planReleaseGates, selectAffectedPackages, classifyGateExecutions, buildFailureIssue, buildReleaseNotes, releaseTagName, firstOutputLine, formatPublishError, MANIFEST_NAME, SBOM_NAME, buildArchitectureMap, renderMapHuman, findArchitectureDrift, renderDriftReport, scanWorkspacePackages, loadSubsystemManifest, loadProductVision, checkFeatureAgainstArchitecture, renderArchCheck, planProjectSkills, guidanceForStage, renderInjectionReport, analyzeCorpus, renderRakeReport, renderCriticSection, rakeAsLesson, rakeReward, DEFAULT_RAKE_THRESHOLDS, streamSessionEvents, findLatestTranscript, detectProcessRakes, buildRetro, renderRetro, retroLessonText, PROCESS_SIGNATURES, RETRO_DOMAIN, scanForSetup, buildSetupPlan, scaffoldFromSpec, renderScaffoldPreview, readExistingForScaffold, assembleChallengeContext, buildChallengeBrief, planDiscriminationCheck, classifyDiscrimination, classifyExecutionEvidence, pickAdversaryModel, CHALLENGE_QUESTIONS, loadOutcomes, renderOutcomes, statsForKey, selectAutoCost, recordProvisional, finalizeOutcome, harvestStageOutcomes, recommendModels, planFeed, GRADE_SUCCESS_FLOOR, COST_LADDER, splitScenarios, budgetPlan, selectWinner, proseScopeOk, renderProseDiff, readScenarioIds, DEFAULT_MAX_JUDGE_RUNS, collectDeliveryFacts, planDeliveryCheck, renderDeliveryBrief, classifyDelivery, isUsablePlaneResult, renderDeliveryReview, scanSkillsLayout, declaredPluginSurface, parseInitFacts, verifyRegistration, buildContentProbePrompt, classifyContentProbe, renderContentProbe, findNonRegistrableSkillDirs, assembleCompoundingReport, // Cold-vs-warm EPOCH RUNNER (feature epoch-replay) — orchestrates + scores, never calls a model. replayableInstances, buildWorkOrder, buildJudgePrompts, unblindJudgments, verifyWorkOrder, isValidMargin, DIGEST_HONEST_SCOPE, scoreEpochReplay, generateMockOutcomes, renderEpochReplayResult, renderWorkOrderSummary, renderJudgePromptsSummary, WORK_ORDER_KIND, DEFAULT_MOCK_N, DEFAULT_MOCK_SEED, type WorkOrder, type EpochOutcome, scoreRun, readQeGrade, recapWindow, decideHorizon, withinWindow, buildRecap, renderRecap, parseSourceManifest, tgPostHtmlIssues, tgVisibleLength, decideTgSend, TG_TEXT_LIMIT, countRecallEventsForRun, unknownFlagNotice, mirrorWriterExplanation, appendRecallUsage, closenessLine, anyAboveFloor, decideNameCheck, renderNameCheck, exportedNamesIn, dispatchedCommandsIn, type NameFacts, type NameQuery, decideSourceProvenance, renderSourceProvenance, REFUSED_HORIZONS, type RecapHorizon, type RecapWindow, type Delivery, type Publish, type GuardRun, type ReuseFacts, renderScorecard, renderCompoundingReport, readReinforcementState, readQuarantineState, registrationExitCode, renderRegistrationReport, // Smart Backlog (feature smart-backlog) — goal-directed idea pipeline over the Brain vector engine. readBacklogConfig, readIdeas, writeIdeas, ideaId, dedupIdea, readGoalMap, readGoalMapDetailed, parseEffort, ensureBacklogGitignored, isSafeId, alignIdea, mirrorIdeaVector, ensureBacklogEmbedForm, readBacklogEmbedFormVersion, recordAbsorption, DEDUP_EMBED_FORM_VERSION, snapshotIdeas, spinRoulette, rankRoulette, seededRng, eligibleIdeas, stageEnrichment, buildJiraDraft, resolveJiraAdapter, makeBacklogIO, harmonizeBacklog, transitionIdeas, editIdea, clearEmbedStale, BACKLOG_BACKENDS, applyDomainBoost, DZ_OWNED_TASK_TYPES, applyExportHoldout, DEFAULT_HELD_OUT_DOMAINS, canonicalDomainKey, readAgentdbRowsByTaskType, heldOutAfterOptIn, renderHoldoutNote, renderSharedStoreAdvice, decideVectorExport, countDisplacedByCut, renderDomainBoostNote, renderDomainCutNote, parseReqeDebt, // qe-bridge (feature qe-bridge-claude, ADR-001): the pure half of the reverse QE bridge. KNOWN_CLAUDE, isSafeClaudeId, claudeProbeArgs, claudeReviewArgs, interpretClaudeProbe, modelFamily, buildBridgePrompt, parseBridgeOutput, buildBridgeFailureRecord, buildBridgeSignoffRecord, renderBridgeReport, isSafeSlug, hasUnsafePathChars, hasDotDotSegment, type BridgeFamily, type BridgeFailureReason, type NamedExtract, buildReqeBrief, settleReqeDebt, renderReqeList, REQE_SCOPE, // Mutation gate (feature ha-mutation-gate) — break each named protection, run the suite, require red. parseMutationRegistry, applyMutationToText, countFailingTests, classifyBaseline, classifyRunFailure, classifyMutationOutcome, mutationGateExitCode, summarizeMutationResults, renderMutationReport, TRACE_BUNDLE_LEDGER_PATH, TRACE_BUNDLE_SCHEMA, TRACE_BUNDLE_RUN_META_FILE, buildBundle, serializeBundle, parseBundle, planImport, decideCheckpointWrite, amendmentSection, planSaysNoAmendments, parseAmendments, resolveAmendments, decideAmendmentOutcome, amendmentVerdictLine, amendmentsMissingFromPlan, AMENDMENT_VACUITY_NOTE, decideSignableSet, signableSetLine, decideRecordWrite, decideReadBack, recordVerdictLine, buildCadenceReport, tgVisibleSha256, CADENCE_WINDOW_DAYS, } from '@dzhechkov/harness-core'; import type { RecordKind, RecordDecision } from '@dzhechkov/harness-core'; import type { CadenceWindow } from '@dzhechkov/harness-core'; import type { MutationEntryResult, MutationObservation, MutationRegistryEntry } from '@dzhechkov/harness-core'; import type { SkillApplyFailure, SkillLoadFailure } from '@dzhechkov/harness-core'; import type { ReqeDebt } from '@dzhechkov/harness-core'; import type { ClassifyResultRow, ExecutionEvidence } from '@dzhechkov/harness-core'; import type { IdeaRecord, IdeaStatus } from '@dzhechkov/harness-core'; import type { Family, ModelRung, Candidate as BtoCandidate, DimScores } from '@dzhechkov/harness-core'; import type { SetupSpec } from '@dzhechkov/harness-core'; import type { LogTail } from '@dzhechkov/harness-core'; import type { ProvenanceMode, PackVerdict, ClaudeUsageModel, PatternRecord, TargetName, BookKU, HarmonizeReport, UsageCalibrationPlan, ClaimFinding, RecallUsagePatternRow, GateExecution, GateStep } from '@dzhechkov/harness-core'; import { getPreset, PRESET_NAMES } from '@dzhechkov/harness-presets'; import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, ScoutMemory } from '@dzhechkov/scout'; const USAGE = `dz - DZ cross-platform harness CLI Usage: dz init --target [--skills-dir ] [--project ] [--preset ] [--select id,id,...] [--force] [--enrich] [--no-hooks] [--no-verify] (--target codex ALSO installs the user-global dz veto+recall hooks and LIVE-verifies them (ADR-001 §8); --no-hooks = skills only; --no-verify skips the live probe and can never report ready) dz verify [--skills-dir ] [--target ] dz sync [--canonical ] [--project ] [--dry-run] [--force] dz update (alias of sync) dz list [--skills-dir ] dz info [--skills-dir ] dz migrate [--project ] dz create-skill --name [--description ] [--skills-dir ] [--tier <1-3>] [--with-references] [--no-evals] [--bto] dz scout [--topics ] [--since ] [--deep] [--output ] [--diff] [--report] dz workflow init --name [--pattern pipeline|barrier|fanout|gate] [--o ] (scaffold a loop-plan/1 plan) dz workflow validate [--json] (schema + INV-1..8 checks; CI-runnable, non-zero on failure) dz workflow render --o [--check] [--force] (plan → region-delimited loop script; USER regions preserved) dz workflow blobs [--check] (list/self-check the subsystem blob registry) dz workflow-lint [--plan ] [--require-plan|--legacy] [--json] (layer-1 gate; exit 0/1/3 — inconclusive is never a pass) dz workflow-trace |--run > [--invariants ] [--corroborate ] [--html ] [--json] (timeline + SEQ invariant runner; ALWAYS reports who attested the trace — instrument|agent|unknown — and --corroborate checks the Claude host's own records for the half they can witness) dz workflow-trace export --o [--include-pairs --yes] [--strict] (one run's telemetry as ONE movable file: events, not aggregates; degradation is typed and LOUD, --strict fails closed) dz workflow-trace import --into [--force] [--with-pairs] (reconstruct that run under an explicit root; FAIL-CLOSED — never writes over a run that already has content) dz install [--target ] [--project ] [--force] dz bundle [--preset | --select id,id,...] [--out ] [--skills-dir ] [--force] (portable self-contained skill bundles for a generic/LangGraph consumer) dz doctor [--project ] [--pubkey ] [--require-signing] (health + signature check of installed packs) dz upgrade [--target ] [--pubkey ] [--require-signing] (a TAMPERED pack aborts the upgrade) dz sign --pack --key (Ed25519 manifest + CycloneDX SBOM for a pack) dz verify-pack --pack [--pubkey ] (signature check; fail-closed; key from the repo, never the pack) dz publish [--filter ] [--bump-only] [--claim-check ] [--require-signing] [--provenance|--no-provenance] (dry-run by default; pass --yes/--confirm/--no-dry-run to go live; claim-check gate default warn — surfaces README claim findings, never blocks; error fails an offending package) dz release [--filter ] [--tag] [--publish] [--json] [--dry-run] [--no-issue] (VERIFIED release: 4 HARD gates in FRONT of dz publish — full package test suites, audit >=high, node --check of every dist/bin file, bin smoke-boot via "node --help" — any red gate STOPS the release (exit 1) + best-effort gh issue; all green ⇒ re-sign reminder, then prints the ready dz publish command (or chains with --publish); never duplicates publish's own gates) dz parity [--target ] [--json] (the honest feature×target map, COMPUTED from the capability model — which harness feature is full / manual / absent on each of the ${TARGET_NAMES.length} targets, and via which form) dz delivery-check --slug [--context-only] [--findings ] [--strict] [--author ] [--json] (portable Step-10 Delivery Gate: prints the 4-plane review brief + artifact probes; --findings classifies a fed-back review into a fail-closed ready|blocked hand-off and writes features//10_delivery_review.md; --strict exits 1 on blocked) dz challenge --plan [--author ] (the deterministic cartridge behind the challenge-panel adversarial plan-gate (R6): assembles the wide brief — plan + architecture/vision.md + testing.md + map.json + degradations.md — and prints the C1-C8 adversary prompt naming the cross-family reviewer to dispatch. exit 0 brief printed / 1 plan missing or empty) dz skills-verify [--dir ] [--expect a,b] [--static] [--strict] [--json] (does .claude/skills/ actually REGISTER? --static = instant layout scan for CI; default reads the authoritative system/init listing from a real session. exit 0 pass / 1 fail / 2 inconclusive — never a false pass) dz compounding [--project ] [--json] (honest learning-loop payoff report: pool write-only ratio, guard repeat-violation trajectory, cold-vs-warm replay readiness, instrumentation health — a gate without enough data says INSUFFICIENT_DATA, never a fake verdict) dz epoch-replay --mock [--n ] [--effect <-1..1>] [--tie-rate <0..1>] [--seed ] [--slice ] [--json] ($0 synthetic run — exercises the verdict math, NOT evidence) dz epoch-replay --emit [--project ] [--limit ] [--seed ] [--out ] (cold-vs-warm work order: instances + PRE-REGISTERED blind A/B assignment; the runner never calls a model) dz epoch-replay --judge [--out ] (blind judge prompts from the filled plans) dz epoch-replay --score --work-order [--slice ] [--json] (un-blind against the pre-registered assignment → SUPPORTED only when the two 95% Wilson CIs are DISJOINT, else FALSIFIED / INCONCLUSIVE) dz score --slug [--project ] [--json] (process scorecard for ONE feature-adr run, from its artifacts: ADR confirmation, discrimination, cross-model QE grade, live verification, README-first, learning loop, amendments — descriptive-only, a low score exits 0) dz recap [--day|--week|--month] [--at ] [--project ] [--json] (what was done over a window, from records only: deliveries with the grade an independent review STATED — a report naming two grades is reported ambiguous, never guessed — registry publishes, gate verdicts, knowledge reuse. --quarter/--half-year/--year are RECOGNISED and REFUSED with the real span in days: there is one complete quarter and the longest record is 174 days. Every section carries its own data-start date, and "the source was not read" never prints as zero. Contaminated measures — commit count, lines, tokens, learning-event volume, inventory counts, lesson count — are not computed, and the report says so. exit 0 reported / 2 refused) dz cadence [--window day|week|month|quarter|halfyear|year] [--json] (the WHAT-SHIPPED aggregator: graded-shipment cadence by ISO week + npm-publish cadence (recap cache) + guard repeat decay on the FIXED rule set + recall reuse; a window deeper than 2× the record is REFUSED with the depth named (ADR: a cadence from one point is scale forgery); exit 0 report / 2 refused-window / 1 usage) dz tg-post --draft [--manifest ] [--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) dz name-check [--command ] [--module ] [--export ] [--project ] [--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) dz provenance-check --manifest [--project ] [--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 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) dz amendment-check --slug | --feature-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) dz feature-adr-record --kind ledger|training-pair --stage [--slug ] [--row|--pair ] [--mark ] [--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) dz feature-adr-checkpoint (--slug | --feature-dir ) --stage --input-hash --result [--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) dz reqe [--slug [--done --report ]] [--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) dz qe-bridge --family claude --slug [--coder-family codex|claude] [--model ] [--files a,b] [--out ] [--timeout ] [--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 18 NAMED failures with an audit record under features//.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//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) dz mutation-gate [--package ] [--registry ] [--test-cmd ""] [--only ] [--timeout ] [--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) dz backlog add "" [--effort 1-5] [--proposal ] [--dry-run] [--project ] [--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) dz backlog list [--status ] [--goal ] [--project ] [--json] (list captured ideas, filterable by status/goal) dz backlog show [--project ] [--json] (full record for one idea) dz backlog goals [--validate] [--project ] [--json] (list/validate the compass at .dz/backlog/goals.json) dz backlog roulette [--pick ] [--seed ] [--commit] [--project ] [--json] (WEIGHTED draw over eligible ideas: alignment^alpha * recencyDecay * 1/effort, seeded; --pick N = ranked shortlist; --commit flips the pick to in-progress) dz backlog ship […] [--reason ] [--dry-run] [--project ] [--json] (mark work DONE: new|enriched|in-progress → shipped, removing it from the roulette pool — run it after finishing a task; short id prefixes ok, ambiguous = loud error) dz backlog drop […] [--reason ] [--dry-run] [--project ] [--json] (retire an idea: new|enriched|in-progress → dropped) dz backlog edit --text "" | --append "" [--dry-run] [--project ] [--json] (rewrite ONE idea's text, preserving every other field; re-embeds the dedup vector, and on a failed re-embed MARKS the record embedStale so dedup refuses to trust it — previous text preserved in .dz/backlog/edits.jsonl) dz routing recommend [--tier ] [--apply] [--json] (per-stage args.models suggestion from REAL telemetry — harness records + imported run-meta sidecars — printed WITH its basis: n runs, window, the grade-floor rule, skip reasons; qe is FORCED cross-family of code; --apply feeds .dz/routing-outcomes.json idempotently by runId) dz backlog reopen […] [--reason ] [--dry-run] [--project ] [--json] (back to the pool: shipped|dropped|in-progress → new) dz backlog enrich [--project ] [--json] (stage the idea2prd input scaffold in features// and hand off to the idea2prd-manual skill — the CLI never fabricates a PRD) dz backlog jira [--project ] [--json] (draft a Jira issue via the configurable adapter (backlog.jira.adapter: jira-mcp|copilot-mcp|none); none writes an auditable jira-outbox/.json stub) dz backlog harmonize [--apply] [--threshold <0-1>] [--project ] [--json] (batch semantic dedup of the backlog ideas; --dry-run default, --apply snapshots first) dz setup --target [--preset ] [--select id,id,...] [--skills-dir ] [--project ] [--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) dz teach "" [--reward <0-1>] [--domain ] [--type rule|success-pattern|lesson-learned] [--project ] [--no-mirror] (--project pins the learned store to /.dz, not the cwd — pin to a canonical brain) dz teach --from-json [--project ] [--no-mirror] (bulk-import a 'dz recall --all --json' export — share a learned store across machines) dz consolidate [--sessions-dir ] [--project ] [--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) dz recall "" [--limit ] [--domain ] [--semantic | --no-semantic] [--books [--book ]] [--project ] | dz recall --all [--json] | dz recall --usage [--json] | dz recall --forget [,] [--apply] | dz recall --promote [,] [--apply] (--domain 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) dz vector status [--project ] [--json] (semantic tier: engine, mirrored vs lexical counts, pending queue) dz vector reindex [--project ] [--json] (snapshot, re-embed learned-pattern vectors, stamp current model) dz vector export [--project ] (portable VECTOR form (.rvf, opt-in RVF engine); patterns ship via recall --all --json) dz vector import [--project ] (import a checkpoint's patterns by dzId — non-destructive upsert, orphan dzIds skipped) dz vector harmonize [--apply] [--threshold <0-1>] [--project ] (semantic dedup of near-duplicate patterns; --dry-run default, --apply writes a restorable backup) dz brain list [--json] (the durable cross-project knowledge brain) dz brain query "" [--source ] [--limit ] [--any] [--rerank] [--json] (cross-source recall; --any = OR match; --rerank reorders top-K) dz brain add [--source ] [--project ] [--from-slice |--from-pack

|--from-kus --slug ] [--kind ] [--license ] [--json] (grow the brain: promote this project, or import a slice/pack/KU-array) dz brain update [--project

] [--json] (non-destructive refresh: re-mirror a re-ingested source into the brain) dz brain reindex [--json] (snapshot, re-embed book-KU brain vectors, stamp current model) dz brain primer [--json] (print a source's capability card — KU-type histogram + top decision moments) dz brain export --source --out (export ONE source as a portable, lexical-only books.sqlite slice) dz brain ground [] [--k ] [--source ] [--text] [--budget ] [--full] (UserPromptSubmit hook; --budget inlines top-K KUs within ~N tokens; --full = ~8000) dz brain expand [--source ] [--json] (full-content lookup for a citation kuId; --json emits the full KU object) dz brain init [--project ] [--k ] (wire the grounding hook into .claude/settings.json — opt-in) dz statusline [--json] [--install] [--project ] (live self-learning panel for Claude Code's status bar; reads the CC JSON payload from STDIN) dz statusline --fa-record --slug --step "