@dzhechkov/harness-cli 0.7.4 → 0.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -6,8 +6,11 @@
6
6
  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';
7
7
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
+ import { request as httpsRequest } from 'node:https';
9
10
  import { KNOWN_CLI_FLAGS } from './known-flags.js';
10
- import { execFileSync, execSync, spawn, spawnSync } from 'node:child_process';
11
+ import { isBooleanFlag } from './boolean-flags.js';
12
+ import { resolveInstallSpec } from './install-spec.js';
13
+ import { execFile, execFileSync, execSync, spawn, spawnSync } from 'node:child_process';
11
14
  import { createHash, randomBytes } from 'node:crypto';
12
15
  import { homedir, tmpdir } from 'node:os';
13
16
  import { createRequire } from 'node:module';
@@ -17,13 +20,13 @@ TRACE_RUNID_RE, WF_RUN_OWNER_HOST, preflight, runWorkflow, makeClaudePDispatcher
17
20
  // guard-promotion (feature guard-promotion, scout idea #1)
18
21
  assembleCandidates, renderPromotionReport, renderPromotionAdr, normalizePromotionState, nextPromotionState, globMatch, promotionAdrRelPath, DEFAULT_WINDOW_DAYS, DEFAULT_PERIODS, MAX_CONTENT_FETCHES, BUILTIN_COVERAGE, decideProvenance, isInsideTree, signManifest, verifyManifest, listSignablePackFiles, assertKeyOutsideTree, decidePublishGate, collectPackageFacts, planReleaseGates, selectAffectedPackages, classifyGateExecutions, buildFailureIssue, buildReleaseNotes, releaseTagName, firstOutputLine, formatPublishError, MANIFEST_NAME, SBOM_NAME, buildArchitectureMap, renderMapHuman, findArchitectureDrift, renderDriftReport, scanWorkspacePackages, loadSubsystemManifest, loadProductVision, checkFeatureAgainstArchitecture, renderArchCheck, planProjectSkills, guidanceForStage, renderInjectionReport, analyzeCorpus, renderRakeReport, renderCriticSection, rakeAsLesson, rakeReward, DEFAULT_RAKE_THRESHOLDS, streamSessionEvents, findLatestTranscript, detectProcessRakes, buildRetro, renderRetro, retroLessonText, PROCESS_SIGNATURES, RETRO_DOMAIN, scanForSetup, buildSetupPlan, scaffoldFromSpec, renderScaffoldPreview, readExistingForScaffold, assembleChallengeContext, buildChallengeBrief, planDiscriminationCheck, classifyDiscrimination, classifyExecutionEvidence, pickAdversaryModel, CHALLENGE_QUESTIONS, loadOutcomes, renderOutcomes, statsForKey, selectAutoCost, recordProvisional, finalizeOutcome, harvestStageOutcomes, recommendModels, planFeed, GRADE_SUCCESS_FLOOR, COST_LADDER, splitScenarios, budgetPlan, selectWinner, proseScopeOk, renderProseDiff, readScenarioIds, DEFAULT_MAX_JUDGE_RUNS, collectDeliveryFacts, planDeliveryCheck, renderDeliveryBrief, classifyDelivery, isUsablePlaneResult, renderDeliveryReview, scanSkillsLayout, declaredPluginSurface, parseInitFacts, verifyRegistration, buildContentProbePrompt, classifyContentProbe, renderContentProbe, findNonRegistrableSkillDirs, assembleCompoundingReport,
19
22
  // Cold-vs-warm EPOCH RUNNER (feature epoch-replay) — orchestrates + scores, never calls a model.
20
- replayableInstances, buildWorkOrder, buildJudgePrompts, unblindJudgments, verifyWorkOrder, isValidMargin, DIGEST_HONEST_SCOPE, scoreEpochReplay, generateMockOutcomes, renderEpochReplayResult, renderWorkOrderSummary, renderJudgePromptsSummary, WORK_ORDER_KIND, DEFAULT_MOCK_N, DEFAULT_MOCK_SEED, scoreRun, readQeGrade, recapWindow, decideHorizon, withinWindow, buildRecap, renderRecap, parseSourceManifest, unknownFlagNotice, mirrorWriterExplanation, appendRecallUsage, closenessLine, anyAboveFloor, decideNameCheck, renderNameCheck, exportedNamesIn, dispatchedCommandsIn, decideSourceProvenance, renderSourceProvenance, REFUSED_HORIZONS, renderScorecard, renderCompoundingReport, readReinforcementState, readQuarantineState, registrationExitCode, renderRegistrationReport,
23
+ replayableInstances, buildWorkOrder, buildJudgePrompts, unblindJudgments, verifyWorkOrder, isValidMargin, DIGEST_HONEST_SCOPE, scoreEpochReplay, generateMockOutcomes, renderEpochReplayResult, renderWorkOrderSummary, renderJudgePromptsSummary, WORK_ORDER_KIND, DEFAULT_MOCK_N, DEFAULT_MOCK_SEED, scoreRun, readQeGrade, recapWindow, decideHorizon, withinWindow, buildRecap, renderRecap, parseSourceManifest, tgPostHtmlIssues, tgVisibleLength, decideTgSend, TG_TEXT_LIMIT, countRecallEventsForRun, unknownFlagNotice, mirrorWriterExplanation, appendRecallUsage, closenessLine, anyAboveFloor, decideNameCheck, renderNameCheck, exportedNamesIn, dispatchedCommandsIn, decideSourceProvenance, renderSourceProvenance, REFUSED_HORIZONS, renderScorecard, renderCompoundingReport, readReinforcementState, readQuarantineState, registrationExitCode, renderRegistrationReport,
21
24
  // Smart Backlog (feature smart-backlog) — goal-directed idea pipeline over the Brain vector engine.
22
25
  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,
23
26
  // qe-bridge (feature qe-bridge-claude, ADR-001): the pure half of the reverse QE bridge.
24
27
  KNOWN_CLAUDE, isSafeClaudeId, claudeProbeArgs, claudeReviewArgs, interpretClaudeProbe, modelFamily, buildBridgePrompt, parseBridgeOutput, buildBridgeFailureRecord, buildBridgeSignoffRecord, renderBridgeReport, isSafeSlug, hasUnsafePathChars, hasDotDotSegment, buildReqeBrief, settleReqeDebt, renderReqeList, REQE_SCOPE,
25
28
  // Mutation gate (feature ha-mutation-gate) — break each named protection, run the suite, require red.
26
- 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, } from '@dzhechkov/harness-core';
29
+ 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';
27
30
  import { getPreset, PRESET_NAMES } from '@dzhechkov/harness-presets';
28
31
  import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, ScoutMemory } from '@dzhechkov/scout';
29
32
  const USAGE = `dz - DZ cross-platform harness CLI
@@ -56,6 +59,7 @@ Usage:
56
59
  dz release [--filter <name>] [--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 <bin> --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)
57
60
  dz parity [--target <name>] [--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)
58
61
  dz delivery-check --slug <slug> [--context-only] [--findings <f.json>] [--strict] [--author <model>] [--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/<slug>/10_delivery_review.md; --strict exits 1 on blocked)
62
+ dz challenge --plan <plan.md> [--author <model>] (the deterministic cartridge behind the challenge-panel adversarial plan-gate (R6): assembles the wide brief — plan + architecture/vision.md + testing.md + map.json + degradations.md — and prints the C1-C8 adversary prompt naming the cross-family reviewer to dispatch. exit 0 brief printed / 1 plan missing or empty)
59
63
  dz skills-verify [--dir <project>] [--expect a,b] [--static] [--strict] [--json] (does .claude/skills/ actually REGISTER? --static = instant layout scan for CI; default reads the authoritative system/init listing from a real session. exit 0 pass / 1 fail / 2 inconclusive — never a false pass)
60
64
  dz compounding [--project <dir>] [--json] (honest learning-loop payoff report: pool write-only ratio, guard repeat-violation trajectory, cold-vs-warm replay readiness, instrumentation health — a gate without enough data says INSUFFICIENT_DATA, never a fake verdict)
61
65
  dz epoch-replay --mock [--n <N>] [--effect <-1..1>] [--tie-rate <0..1>] [--seed <N>] [--slice <name>] [--json] ($0 synthetic run — exercises the verdict math, NOT evidence)
@@ -64,6 +68,8 @@ Usage:
64
68
  dz epoch-replay --score <judgments.json> --work-order <file> [--slice <name>] [--json] (un-blind against the pre-registered assignment → SUPPORTED only when the two 95% Wilson CIs are DISJOINT, else FALSIFIED / INCONCLUSIVE)
65
69
  dz score --slug <feature> [--project <dir>] [--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)
66
70
  dz recap [--day|--week|--month] [--at <ISO date>] [--project <dir>] [--json] (what was done over a window, from records only: deliveries with the grade an independent review STATED — a report naming two grades is reported ambiguous, never guessed — registry publishes, gate verdicts, knowledge reuse. --quarter/--half-year/--year are RECOGNISED and REFUSED with the real span in days: there is one complete quarter and the longest record is 174 days. Every section carries its own data-start date, and "the source was not read" never prints as zero. Contaminated measures — commit count, lines, tokens, learning-event volume, inventory counts, lesson count — are not computed, and the report says so. exit 0 reported / 2 refused)
71
+ 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)
72
+ 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)
67
73
  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)
68
74
  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)
69
75
  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)
@@ -157,10 +163,24 @@ function parseArgs(argv) {
157
163
  const optionLists = new Map();
158
164
  const flags = new Set();
159
165
  const positional = [];
166
+ // The command decides `--force`'s arity (valued only under `dz guard`); it is always the first
167
+ // token when present — a leading `--flag` means there is no command at all.
168
+ const command = (argv[0] ?? '').startsWith('--') ? '' : argv[0] ?? '';
160
169
  for (let index = 0; index < argv.length; index += 1) {
161
170
  const arg = argv[index] ?? '';
162
- if (arg.startsWith('--')) {
171
+ // A token that BEGINS with -- but contains whitespace cannot be a flag — no real flag carries a
172
+ // space (values arrive as separate argv tokens). It is quoted TEXT that happens to open with
173
+ // dashes: `dz backlog add "--semantic идея…"` was rejected twice with «an idea text is
174
+ // required» while the text sat right there, eaten as an option (f18fc89e).
175
+ if (arg.startsWith('--') && !/\s/.test(arg)) {
163
176
  const key = arg.slice(2);
177
+ // A DECLARED boolean flag never swallows the next token (backlog 247ddcfa: `dz sync
178
+ // --dry-run .` used to disarm the safety flag silently and then WRITE). The declaration is
179
+ // data with a two-way drift test — see src/boolean-flags.ts.
180
+ if (isBooleanFlag(key, command)) {
181
+ flags.add(key);
182
+ continue;
183
+ }
164
184
  const next = argv[index + 1];
165
185
  if (next !== undefined && !next.startsWith('--')) {
166
186
  options.set(key, next);
@@ -401,7 +421,15 @@ async function cmdSync(options, flags, cwd, write, writeErr) {
401
421
  // Auto-discover all skills-* packs, or use explicit --canonical
402
422
  let canonicalDirs;
403
423
  if (canonicalArg !== undefined) {
404
- canonicalDirs = [resolve(cwd, canonicalArg)];
424
+ const dir = resolve(cwd, canonicalArg);
425
+ if (!existsSync(dir)) {
426
+ // MEASURED 2026-08-24: a TYPO here used to print `0/0 in sync` and exit 0 — green exactly
427
+ // when nothing was compared, and in CI that reads as "all skills healthy". An explicit path
428
+ // that does not exist is an answer about the INVOCATION, not about the skills.
429
+ write(`dz sync: --canonical ${dir} does not exist — nothing was compared, and nothing-compared is not a clean sync`);
430
+ return 3;
431
+ }
432
+ canonicalDirs = [dir];
405
433
  }
406
434
  else {
407
435
  const baseDir = join(projectRoot, 'packages', '@dzhechkov');
@@ -418,7 +446,18 @@ async function cmdSync(options, flags, cwd, write, writeErr) {
418
446
  force: flags.has('force'),
419
447
  });
420
448
  const { total, inSync, missing, drift } = report.summary;
421
- write(`dz sync${report.dryRun ? ' --dry-run' : ''}: ${inSync}/${total} in sync, ${missing} missing, ${drift} drift`);
449
+ // The DONE half, beside the SEEN half: a run that wrote its fixes used to print only what it had
450
+ // seen before writing, and exit 1 — "returns 0 when it did nothing and 1 when it worked". Status
451
+ // counts describe the tree as found; `wrote` describes what this run changed about it.
452
+ const wrote = report.skills.filter((skill) => skill.written.length > 0);
453
+ write(`dz sync${report.dryRun ? ' --dry-run' : ''}: ${inSync}/${total} in sync, ${missing} missing, ${drift} drift${wrote.length > 0 ? ` — wrote ${wrote.length} skill(s)` : ''}`);
454
+ if (total === 0) {
455
+ // Nothing was compared. Exit 3, the house not-established convention (`dz workflow-lint`,
456
+ // `check-plan-completeness`) — never 0: a gate that is green when it never ran is the defect
457
+ // this repo keeps finding elsewhere (the publish gate, the scout 401, the recall log).
458
+ write(`dz sync: 0 canonical skill(s) found under ${canonicalDirs.join(', ')} — nothing was compared, and nothing-compared is not a clean sync`);
459
+ return 3;
460
+ }
422
461
  // Skip-and-collect (D1): the broken canonical skills are NAMED on stderr, and their
423
462
  // presence keeps the exit code non-zero — a partial sync is not a clean sync.
424
463
  if (report.failures.length > 0) {
@@ -428,7 +467,10 @@ async function cmdSync(options, flags, cwd, write, writeErr) {
428
467
  writeErr(line);
429
468
  return 1;
430
469
  }
431
- return missing === 0 && drift === 0 ? 0 : 1;
470
+ // The exit reflects the OUTCOME: a missing/drift skill this run wrote is resolved, not pending.
471
+ // A dry run writes nothing, so its exit keeps the CI meaning — 1 whenever work exists.
472
+ const unresolved = report.skills.filter((skill) => skill.status !== 'in-sync' && skill.written.length === 0);
473
+ return unresolved.length === 0 ? 0 : 1;
432
474
  }
433
475
  function cmdCreateSkill(options, flags, cwd, write) {
434
476
  const name = options.get('name');
@@ -1410,6 +1452,47 @@ async function cmdInstall(options, flags, cwd, write, writeErr, installRunner) {
1410
1452
  write('dz install: package name required (e.g., dz install @dzhechkov/skills-devops)');
1411
1453
  return 1;
1412
1454
  }
1455
+ // install-spec-honesty (43a52cf2 + c999786b): resolve the spec to {npmSpec, dirName} BEFORE any
1456
+ // npm process runs — the versioned form used to npm-install SUCCESSFULLY (mutating the project's
1457
+ // package.json) and then die on an invented node_modules path.
1458
+ const specResolution = resolveInstallSpec(pkg, (p) => resolve(cwd, p), {
1459
+ isFile: (p) => { try {
1460
+ return statSync(p).isFile();
1461
+ }
1462
+ catch {
1463
+ return false;
1464
+ } },
1465
+ isDir: (p) => { try {
1466
+ return statSync(p).isDirectory();
1467
+ }
1468
+ catch {
1469
+ return false;
1470
+ } },
1471
+ readTarballName: (p) => {
1472
+ try {
1473
+ const out = execSync(`tar -xzOf ${JSON.stringify(p)} package/package.json`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
1474
+ const name = JSON.parse(out).name;
1475
+ return typeof name === 'string' && name !== '' ? name : null;
1476
+ }
1477
+ catch {
1478
+ return null;
1479
+ }
1480
+ },
1481
+ readDirName: (p) => {
1482
+ try {
1483
+ const name = JSON.parse(readFileSync(join(p, 'package.json'), 'utf-8')).name;
1484
+ return typeof name === 'string' && name !== '' ? name : null;
1485
+ }
1486
+ catch {
1487
+ return null;
1488
+ }
1489
+ },
1490
+ });
1491
+ if (specResolution.kind === 'refused') {
1492
+ write(`dz install: ${specResolution.reason}`);
1493
+ write(` ${specResolution.hint}`);
1494
+ return 1;
1495
+ }
1413
1496
  const targetOpt = options.get('target') ?? 'claude-code';
1414
1497
  const targetResolution = resolveTargetName(targetOpt);
1415
1498
  if (targetResolution.kind === 'unknown') {
@@ -1422,8 +1505,8 @@ async function cmdInstall(options, flags, cwd, write, writeErr, installRunner) {
1422
1505
  writeErr(formatTargetAliasNote('dz install', targetOpt, target));
1423
1506
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
1424
1507
  // Step 1: npm install the package (installRunner is the CliIo test seam — unset in production)
1425
- write(`Installing ${pkg}...`);
1426
- const installCmd = `npm install ${pkg} --save-dev --no-fund --no-audit`;
1508
+ write(`Installing ${specResolution.npmSpec}${specResolution.kind === 'name' ? '' : ` (${specResolution.kind} → node_modules/${specResolution.dirName})`}...`);
1509
+ const installCmd = `npm install ${JSON.stringify(specResolution.npmSpec)} --save-dev --no-fund --no-audit`;
1427
1510
  try {
1428
1511
  if (installRunner)
1429
1512
  installRunner(installCmd, projectRoot);
@@ -1434,8 +1517,9 @@ async function cmdInstall(options, flags, cwd, write, writeErr, installRunner) {
1434
1517
  write(`dz install: npm install failed — ${err instanceof Error ? err.message : String(err)}`);
1435
1518
  return 1;
1436
1519
  }
1437
- // Step 2: Find SKILL.md files in the installed package
1438
- const pkgDir = join(projectRoot, 'node_modules', pkg);
1520
+ // Step 2: Find SKILL.md files in the installed package — under the RESOLVED dir name, never the
1521
+ // raw spec (path.join concatenates an absolute segment; a version suffix invents a dir).
1522
+ const pkgDir = join(projectRoot, 'node_modules', specResolution.dirName);
1439
1523
  if (!existsSync(pkgDir)) {
1440
1524
  write(`dz install: package not found at ${pkgDir}`);
1441
1525
  return 1;
@@ -1684,6 +1768,30 @@ function cmdStatuslineInstall(options, cwd, write) {
1684
1768
  function cmdStatuslineFaRecord(options, cwd, write) {
1685
1769
  const slug = (options.get('slug') ?? '').trim();
1686
1770
  const step = (options.get('step') ?? '').trim();
1771
+ // `--recalled auto` derives the count from the recall-usage log for `--run <id>`, replacing the
1772
+ // pipeline's hardcoded `--recalled 3` (a literal at three call sites — the fallback writer that
1773
+ // lights the panel had nowhere to get a real number until `dz recall` began recording itself).
1774
+ if ((options.get('recalled') ?? '').trim() === 'auto') {
1775
+ const runKey = (options.get('run') ?? '').trim();
1776
+ if (runKey === '') {
1777
+ write('dz statusline --fa-record: --recalled auto needs --run <id> — without a run key there is nothing to count');
1778
+ return 2;
1779
+ }
1780
+ // The COUNT's source and the PANEL's home are two different addresses. The pipeline records
1781
+ // recalls in the canonical BRAIN store while the panel state lives in the project — with a
1782
+ // separate `args.brain` the count read from `--project` would be a silent zero over the wrong
1783
+ // log (the dz sync 0/0 class, again). `--count-project` names the log's home explicitly and
1784
+ // defaults to `--project` for the common single-root case.
1785
+ const countRoot = resolve((options.get('count-project') ?? options.get('project') ?? cwd).trim() || cwd);
1786
+ const derived = countRecallEventsForRun(countRoot, runKey);
1787
+ if (derived === null) {
1788
+ // An unreadable log is not zero. Refusing keeps the panel's PREVIOUS state, which is the
1789
+ // honest outcome: no new claim, rather than a wrong one (the dz sync 0/0 class).
1790
+ write('dz statusline --fa-record: the recall-usage log could not be read — recording nothing rather than a wrong number');
1791
+ return 2;
1792
+ }
1793
+ options.set('recalled', String(derived));
1794
+ }
1687
1795
  if (slug === '' || step === '') {
1688
1796
  write('dz statusline --fa-record: --slug and --step are both required');
1689
1797
  write(' Example: dz statusline --fa-record --slug add-user-auth --step "Step 0" --recalled 5 --stored 2');
@@ -1823,6 +1931,9 @@ function applyUsageCalibrationToConfig(config, plan) {
1823
1931
  if (plan.changes.length > 0) {
1824
1932
  usage['calibratedAt'] = plan.after.calibratedAt;
1825
1933
  usage['source'] = plan.after.source;
1934
+ // A fresh calibration re-arms routing for THIS account and clears the legacy free-text switch:
1935
+ // the calibration is the very act the disable-note demanded.
1936
+ usage['calibrationAccount'] = plan.after.calibrationAccount ?? null;
1826
1937
  }
1827
1938
  memory['usage'] = usage;
1828
1939
  next['memory'] = memory;
@@ -1989,6 +2100,43 @@ function cmdUsageByStage(options, flags, write) {
1989
2100
  * non-zero exit. `--project <dir>` scopes ONLY the `.dz/config.json` read/write; measurement is
1990
2101
  * account-wide (all projects).
1991
2102
  */
2103
+ function cmdCadence(options, flags, cwd, write) {
2104
+ const root = resolve(cwd, options.get('project') ?? '.');
2105
+ const windowRaw = (options.get('window') ?? 'week').trim();
2106
+ if (!(windowRaw in CADENCE_WINDOW_DAYS)) {
2107
+ write('dz cadence: --window must be one of ' + Object.keys(CADENCE_WINDOW_DAYS).join('|'));
2108
+ return 1;
2109
+ }
2110
+ const r = buildCadenceReport(root, windowRaw);
2111
+ if (flags.has('json')) {
2112
+ write(JSON.stringify(r));
2113
+ return r.decision.ok ? 0 : 2;
2114
+ }
2115
+ write('dz cadence — window ' + r.window + ', record depth ' + r.depthDays + ' day(s)');
2116
+ if (!r.decision.ok) {
2117
+ write(' ' + r.decision.reason);
2118
+ if (r.decision.largestAllowed)
2119
+ write(' cure: dz cadence --window ' + r.decision.largestAllowed);
2120
+ return 2;
2121
+ }
2122
+ const weeks = [...new Set([...Object.keys(r.shipments.graded), ...Object.keys(r.npmPublishes.weekly), ...Object.keys(r.recalls.weekly)])].sort();
2123
+ write(' week shipped(graded) npm-publishes recalls');
2124
+ for (const w of weeks) {
2125
+ write(' ' + w.padEnd(12) + String(r.shipments.graded[w] ?? 0).padStart(15) + String(r.npmPublishes.weekly[w] ?? 0).padStart(15) + String(r.recalls.weekly[w] ?? 0).padStart(9));
2126
+ }
2127
+ write(' graded ' + r.shipments.gradedTotal + ' (' + Object.entries(r.shipments.byGrade).sort().map(([g, n]) => g + '×' + n).join(', ') + ') · UNGRADED ' + r.shipments.ungraded + ' (named, not hidden)');
2128
+ if (r.guard.decay.length > 0) {
2129
+ write(' guard repeat decay (FIXED set — rules with pre-window history only):');
2130
+ for (const d of r.guard.decay.slice(0, 8))
2131
+ write(' ' + d.rule.padEnd(28) + 'before×' + d.before + ' → in-window×' + d.inWindow);
2132
+ }
2133
+ if (r.guard.excludedNewborn.length > 0)
2134
+ write(' excluded newborn rule(s) (no pre-window history — a zero here would be youth, not virtue): ' + r.guard.excludedNewborn.join(', '));
2135
+ for (const dgr of [r.npmPublishes.degraded, r.guard.degraded, r.recalls.degraded])
2136
+ if (dgr)
2137
+ write(' DEGRADED: ' + dgr);
2138
+ return 0;
2139
+ }
1992
2140
  function cmdUsage(options, optionLists, flags, cwd, write) {
1993
2141
  const projectRoot = resolve(cwd, options.get('project') ?? '.');
1994
2142
  const nullContract = () => JSON.stringify({
@@ -2022,6 +2170,12 @@ function cmdUsage(options, optionLists, flags, cwd, write) {
2022
2170
  limits: limitsPayload,
2023
2171
  estimated: true,
2024
2172
  };
2173
+ // ADR-001 usage-honesty: a consumer that reads null pcts deserves the WHY (closed reason
2174
+ // set), and a human deserves the raw estimates when POLICY (not measurement) nulled them.
2175
+ if (u.notEstablished.length > 0)
2176
+ payload.notEstablished = u.notEstablished;
2177
+ if (u.estimatesNotForRouting !== undefined)
2178
+ payload.estimatesNotForRouting = u.estimatesNotForRouting;
2025
2179
  if (hasModelLimits && u.weeklyByModel !== undefined)
2026
2180
  payload.weeklyByModel = u.weeklyByModel;
2027
2181
  // re-QE debt surfacing (backlog 6b40e667 — QE #9: the json contract must carry the debt too,
@@ -2036,6 +2190,25 @@ function cmdUsage(options, optionLists, flags, cwd, write) {
2036
2190
  write(JSON.stringify(payload));
2037
2191
  return 0;
2038
2192
  }
2193
+ if (u.sessionPct === null && u.weeklyPct === null && u.notEstablished.length > 0) {
2194
+ // Limits may be fully configured and the pcts STILL null — that is the honesty, not a config
2195
+ // gap. Say why, and show the human the raw estimates when only policy nulled them.
2196
+ write('usage: not established — ' + u.notEstablished.join(', '));
2197
+ if (u.estimatesNotForRouting !== undefined) {
2198
+ const e = u.estimatesNotForRouting;
2199
+ write(' estimates (NOT for routing): session ~' + (e.sessionPct ?? '?') + '% · week ~' + (e.weeklyPct ?? '?') + '% — recalibrate on THIS account: dz usage --calibrate --session <pct> --weekly <pct>');
2200
+ }
2201
+ else {
2202
+ write(' the scan established nothing (' + u.sessionTokens + ' session / ' + u.weeklyTokens + ' weekly tokens counted) — a percentage would be a guess, and routing must not eat guesses');
2203
+ }
2204
+ try {
2205
+ const reqe = scanReqeDebts(resolve(cwd, options.get('project') ?? '.'));
2206
+ if (reqe.debts.length > 0)
2207
+ write('re-QE due: ' + reqe.debts.length + ' usage-switched run(s) kept same-family QE — run `dz reqe` for the cross-family pass');
2208
+ }
2209
+ catch { /* advisory only */ }
2210
+ return 0;
2211
+ }
2039
2212
  if (u.sessionPct === null && u.weeklyPct === null) {
2040
2213
  write('usage: unconfigured — set memory.usage.sessionTokenLimit / weeklyTokenLimit in .dz/config.json (percentages are ESTIMATES calibrated from observed exhaustion)');
2041
2214
  try {
@@ -2781,14 +2954,39 @@ async function cmdRecall(options, flags, cwd, write) {
2781
2954
  limit,
2782
2955
  ...(bookFilter !== undefined ? { book: bookFilter } : {}),
2783
2956
  });
2784
- const { hits, error } = asJson ? await withForeignStdoutOnStderr(runBooks) : await runBooks();
2957
+ let booksResult;
2958
+ try {
2959
+ booksResult = asJson ? await withForeignStdoutOnStderr(runBooks) : await runBooks();
2960
+ }
2961
+ catch (err) {
2962
+ // A corrupted store used to surface as a bare top-level `dz: file is not a database` — exit 1
2963
+ // (honest) but with no path and no cure (a2a574a9/c7aec002). Name both.
2964
+ const msg = err instanceof Error ? err.message : String(err);
2965
+ write(`dz recall --books: the book store is unreadable — ${msg}`);
2966
+ write(` store: ${join(projectRoot, '.dz', 'memory', 'books.sqlite')}`);
2967
+ write(' cure: restore it from a backup, or delete the file and re-digitize (dz brain add --from-slice / book-digitizer) — deleting loses only this project\'s local shelf, the machine-wide brain is separate');
2968
+ return 1;
2969
+ }
2970
+ const { hits, error } = booksResult;
2971
+ // f1451a6a: an EXPLICIT --semantic request whose vector instrument did not run must not read as
2972
+ // a clean 0-hit search. error!==undefined here means the INSTRUMENT failed (embedder/sqlite
2973
+ // unavailable), not that the shelf is empty — house convention exit 3 = not-established.
2974
+ const semanticNotEstablished = flags.has('semantic') && error !== undefined;
2785
2975
  if (asJson) {
2976
+ if (semanticNotEstablished) {
2977
+ write(JSON.stringify({ hits, notEstablished: error }));
2978
+ return 3;
2979
+ }
2786
2980
  write(JSON.stringify(hits));
2787
2981
  return 0;
2788
2982
  }
2789
2983
  write(`dz recall "${query}" --books${bookFilter !== undefined ? ` --book ${bookFilter}` : ''} — ${hits.length} KU hit(s)`);
2790
2984
  if (error !== undefined)
2791
2985
  write(` (${error})`);
2986
+ if (semanticNotEstablished) {
2987
+ write(' --semantic was EXPLICIT and the vector instrument did not run — nothing was established (exit 3, not a clean 0)');
2988
+ return 3;
2989
+ }
2792
2990
  for (const h of hits) {
2793
2991
  const src = h.chapter !== undefined ? ` [${h.book} гл.${h.chapter}${h.pages ? ` с.${h.pages[0]}-${h.pages[1]}` : ''}]` : ` [${h.book}]`;
2794
2992
  write(` (${h.type}) ${h.name}${src}`);
@@ -2903,6 +3101,12 @@ async function cmdRecall(options, flags, cwd, write) {
2903
3101
  write(JSON.stringify(hits.map((h) => ({
2904
3102
  ...h.pattern,
2905
3103
  relevance: boost === null && 'score' in h && typeof h.score === 'number' ? h.score : null,
3104
+ // The TRUE cosine, as a second companion key — the design named it and the first ship missed
3105
+ // it, so a scripted consumer STILL could not threshold (found while recalibrating the floors:
3106
+ // every probe returned "no similarity" through --json while the human output showed sim=).
3107
+ // Unlike `relevance` it SURVIVES a domain boost: closeness is order-independent (ADR-001 of
3108
+ // recall-true-closeness), and null means "not measured for this hit", never zero.
3109
+ similarity: 'similarity' in h && typeof h.similarity === 'number' ? h.similarity : null,
2906
3110
  }))));
2907
3111
  // The honesty notes go to STDERR here rather than being skipped: the JSON branch
2908
3112
  // used to return before them, so a scripted caller was told nothing about a boost
@@ -2988,9 +3192,13 @@ async function cmdRecall(options, flags, cwd, write) {
2988
3192
  if (vectorOn && hits.length > 0) {
2989
3193
  const measured = hits.filter((h) => typeof h.similarity === 'number' && Number.isFinite(h.similarity));
2990
3194
  if (measured.length > 0) {
3195
+ const runId = (options.get('run') ?? '').trim();
2991
3196
  appendRecallUsage({
2992
3197
  projectRoot: projectRoot,
2993
3198
  query: shownQuery,
3199
+ // `--run` threads a caller's run key into the log, so a later `--recalled auto` can count
3200
+ // THIS run's events instead of asserting a literal (the /feature-adr panel's `--recalled 3`).
3201
+ ...(runId === '' ? {} : { runId }),
2994
3202
  hits: measured.map((h) => ({ dzId: patternRecordId(h.pattern), score: h.similarity })),
2995
3203
  });
2996
3204
  }
@@ -6501,7 +6709,7 @@ function gatherGuardFacts(op, root, text, storeCap) {
6501
6709
  }
6502
6710
  catch { /* unreadable tree — the rule reports nothing rather than inventing a violation */ }
6503
6711
  try {
6504
- facts['drift'] = sweepSkillDrift(root, { scope: 'packages', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
6712
+ facts['drift'] = sweepSkillDrift(root, { scope: 'installs', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
6505
6713
  }
6506
6714
  catch { /* skip */ }
6507
6715
  facts['counts'] = gatherReadmeCounts(root);
@@ -6704,7 +6912,7 @@ function gatherGuardFacts(op, root, text, storeCap) {
6704
6912
  }
6705
6913
  if (op === 'consolidate') {
6706
6914
  try {
6707
- facts['drift'] = sweepSkillDrift(root, { scope: 'packages', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
6915
+ facts['drift'] = sweepSkillDrift(root, { scope: 'installs', allowlist: readDriftAllowlist(root) }).drifted.map((d) => d.name);
6708
6916
  }
6709
6917
  catch { /* skip */ }
6710
6918
  }
@@ -9144,6 +9352,30 @@ function packNpmName(packDir) {
9144
9352
  return undefined;
9145
9353
  }
9146
9354
  }
9355
+ /**
9356
+ * Parse `pnpm pack --json` STDOUT robustly: a package with a `prepack` script echoes lifecycle
9357
+ * banners first, and the banner text itself may contain '[' or '{' (skills-feature-adr's guard
9358
+ * does) — so candidates are tried from the LAST line-start opener backwards; pnpm's JSON is the
9359
+ * final thing on stdout. MEASURED 2026-08-25: byte-0 parse failed on the banner, first-opener
9360
+ * parse failed on the banner's own array literal.
9361
+ */
9362
+ function parsePnpmPackJson(out) {
9363
+ const starts = [];
9364
+ for (let li = 0; li < out.length; li = out.indexOf('\n', li) + 1) {
9365
+ const ch = out[li];
9366
+ if (ch === '{' || ch === '[')
9367
+ starts.push(li);
9368
+ if (out.indexOf('\n', li) === -1)
9369
+ break;
9370
+ }
9371
+ for (let ci = starts.length - 1; ci >= 0; ci--) {
9372
+ try {
9373
+ return JSON.parse(out.slice(starts[ci]));
9374
+ }
9375
+ catch { /* try an earlier candidate */ }
9376
+ }
9377
+ throw new Error('pnpm pack emitted no parseable JSON');
9378
+ }
9147
9379
  function npmPackedPaths(packDir) {
9148
9380
  // `pnpm`, not `npm`: the PUBLISHER is `pnpm publish` (see `publishArgv`), and the two packers do not
9149
9381
  // agree. MEASURED 2026-08-21 on `skills-news`: `npm pack` emits a 1051-byte package.json identical
@@ -9155,7 +9387,7 @@ function npmPackedPaths(packDir) {
9155
9387
  encoding: 'utf-8',
9156
9388
  maxBuffer: 64 * 1024 * 1024,
9157
9389
  });
9158
- const parsed = JSON.parse(out);
9390
+ const parsed = parsePnpmPackJson(out);
9159
9391
  const entry = Array.isArray(parsed) ? parsed[0] : parsed;
9160
9392
  const files = entry?.files ?? [];
9161
9393
  return files.map((f) => f.path.replace(/^package\//, '')).sort();
@@ -9187,7 +9419,7 @@ function extractIntoTempDir(packDir, tmp) {
9187
9419
  encoding: 'utf-8',
9188
9420
  maxBuffer: 64 * 1024 * 1024,
9189
9421
  });
9190
- const parsed = JSON.parse(out);
9422
+ const parsed = parsePnpmPackJson(out);
9191
9423
  const entry = Array.isArray(parsed) ? parsed[0] : parsed;
9192
9424
  const tgz = entry?.filename;
9193
9425
  if (tgz === undefined)
@@ -9367,7 +9599,12 @@ function recapPublishes(repo) {
9367
9599
  }
9368
9600
  }
9369
9601
  const sorted = items.map((i) => i.iso).sort();
9370
- return { dataStart: sorted.length > 0 ? sorted[0].slice(0, 10) : null, items };
9602
+ return {
9603
+ dataStart: sorted.length > 0 ? sorted[0].slice(0, 10) : null,
9604
+ items,
9605
+ ...(typeof raw.fetchedAt === 'string' ? { fetchedAt: raw.fetchedAt } : {}),
9606
+ ...(Array.isArray(raw.failed) && raw.failed.length > 0 ? { failed: raw.failed.filter((f) => typeof f === 'string') } : {}),
9607
+ };
9371
9608
  }
9372
9609
  catch {
9373
9610
  return null;
@@ -9681,9 +9918,354 @@ function cmdNameCheck(options, flags, cwd, write) {
9681
9918
  write(line);
9682
9919
  return decision.exit;
9683
9920
  }
9684
- function cmdRecap(options, flags, cwd, write) {
9921
+ // ── recap publish-times cache (feature recap-publish-cache) ──────────────────
9922
+ //
9923
+ // The Publishes section is the one recap section whose timestamps a third party holds — and the one
9924
+ // that was always `unavailable`, because nothing ever filled its cache. The fetch lives HERE, behind
9925
+ // an explicit flag, never inside the report: 51 packages cost 18.3s sequentially (measured in the
9926
+ // recap design), and a report that does network I/O is a report that fails when the network does.
9927
+ const RECAP_NPM_CACHE_REL = '.dz/recap/npm-times.json';
9928
+ /**
9929
+ * Ask the registry when every non-private workspace package's versions were published.
9930
+ *
9931
+ * Genuinely parallel in batches of 8 (`execFile`, not `spawnSync` — a sync call in a loop stays
9932
+ * sequential whatever the batch size claims, which is exactly the kind of false label this pipeline
9933
+ * keeps removing): measured in the recap design at 5.7s against 18.3s sequential over 51 packages.
9934
+ * A package whose lookup fails lands in `failed`, never silently absent — the same class as the
9935
+ * scout 401 that printed `github: 0` and read as "nothing new exists".
9936
+ */
9937
+ async function fetchNpmPublishTimes(repoRoot, write) {
9938
+ const pkgsRoot = join(repoRoot, 'packages', '@dzhechkov');
9939
+ const names = [];
9940
+ if (existsSync(pkgsRoot)) {
9941
+ for (const e of readdirSync(pkgsRoot, { withFileTypes: true })) {
9942
+ if (!e.isDirectory())
9943
+ continue;
9944
+ const pj = join(pkgsRoot, e.name, 'package.json');
9945
+ if (!existsSync(pj))
9946
+ continue;
9947
+ try {
9948
+ const meta = JSON.parse(readFileSync(pj, 'utf-8'));
9949
+ if (meta.private === true || typeof meta.name !== 'string' || meta.name === '')
9950
+ continue;
9951
+ // Deduplicated: two workspace directories can declare one npm name, and a failure would
9952
+ // then count twice — "2 FAILED" about one distinct package (review round 2).
9953
+ if (!names.includes(meta.name))
9954
+ names.push(meta.name);
9955
+ }
9956
+ catch { /* an unreadable package.json is not a publishable package */ }
9957
+ }
9958
+ }
9959
+ const packages = {};
9960
+ const failed = [];
9961
+ const one = (name) => new Promise((done) => {
9962
+ execFile('npm', ['view', name, 'time', '--json'], { timeout: 30_000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout) => {
9963
+ if (err !== null) {
9964
+ failed.push(name);
9965
+ done();
9966
+ return;
9967
+ }
9968
+ try {
9969
+ const times = JSON.parse(stdout);
9970
+ const versions = {};
9971
+ for (const [k, v] of Object.entries(times)) {
9972
+ if (k === 'created' || k === 'modified' || typeof v !== 'string')
9973
+ continue;
9974
+ versions[k] = v;
9975
+ }
9976
+ // A published package has at least one version by construction — npm will not host an
9977
+ // empty one. Valid-but-empty JSON is therefore an ANOMALY, not a zero: recording it as a
9978
+ // success would let the report read "0 publishes" about a package whose answer was broken
9979
+ // (cross-family review, codex gpt-5.6-sol, 2026-08-24, grade B).
9980
+ if (Object.keys(versions).length === 0)
9981
+ failed.push(name);
9982
+ else
9983
+ packages[name] = { versions };
9984
+ }
9985
+ catch {
9986
+ failed.push(name);
9987
+ }
9988
+ done();
9989
+ });
9990
+ });
9991
+ const BATCH = 8;
9992
+ for (let i = 0; i < names.length; i += BATCH) {
9993
+ await Promise.all(names.slice(i, i + BATCH).map(one));
9994
+ write(`dz recap: registry queried ${Math.min(i + BATCH, names.length)}/${names.length}…`);
9995
+ }
9996
+ // `failed` sorted so the cache is deterministic for a given outcome set.
9997
+ return { version: 1, fetchedAt: new Date().toISOString(), packages, failed: [...failed].sort() };
9998
+ }
9999
+ // ── `dz tg-post` (feature genai-tweets-channel, стадия 0→1) ──────────────────
10000
+ //
10001
+ // The sender for an APPROVED draft, implementing the channel's own accepted ADRs: HTML mode (never
10002
+ // MarkdownV2 — 18 escapes against 3), link preview off by default (x.com previews in Telegram have
10003
+ // been broken since 2022), the 00:00-06:00 MSK quiet window, and ADR-004's standing order that
10004
+ // publishing stays MANUAL — the default run is a dry-run, and a real send needs --send --yes.
10005
+ //
10006
+ // The provenance gate runs IN-PROCESS before any send: the draft's sources.json goes through the
10007
+ // same classification `dz provenance-check` uses, and anything but ALLOWED refuses. A draft with no
10008
+ // manifest is refused too — unchecked is not approved.
10009
+ function tgReadToken(repoRoot, write) {
10010
+ // Token sources, in order: env, then a tokenFile named in .dz/config.json. The token itself is
10011
+ // NEVER printed, logged, or included in any error — only where it was looked for.
10012
+ const env = process.env['TELEGRAM_BOT_TOKEN'];
10013
+ if (env !== undefined && env.trim() !== '')
10014
+ return env.trim();
10015
+ try {
10016
+ const cfg = JSON.parse(readFileSync(join(repoRoot, '.dz', 'config.json'), 'utf-8'));
10017
+ const file = cfg.telegram?.tokenFile;
10018
+ if (typeof file === 'string' && file.trim() !== '' && existsSync(file)) {
10019
+ const text = readFileSync(file, 'utf-8');
10020
+ const m = /TELEGRAM_BOT_TOKEN\s*=\s*"?([^"\n]+)"?/.exec(text);
10021
+ if (m?.[1] !== undefined)
10022
+ return m[1].trim();
10023
+ const bare = text.trim();
10024
+ if (bare !== '' && !bare.includes('\n'))
10025
+ return bare;
10026
+ }
10027
+ }
10028
+ catch { /* fall through to the honest null */ }
10029
+ write('dz tg-post: no bot token — set TELEGRAM_BOT_TOKEN or telegram.tokenFile in .dz/config.json');
10030
+ return null;
10031
+ }
10032
+ function tgApi(token, method, body) {
10033
+ return new Promise((done) => {
10034
+ const payload = JSON.stringify(body);
10035
+ const req = httpsRequest({
10036
+ hostname: 'api.telegram.org',
10037
+ path: `/bot${token}/${method}`,
10038
+ method: 'POST',
10039
+ headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
10040
+ timeout: 30_000,
10041
+ }, (res) => {
10042
+ let data = '';
10043
+ res.on('data', (c) => { data += c.toString('utf-8'); });
10044
+ res.on('end', () => {
10045
+ try {
10046
+ const parsed = JSON.parse(data);
10047
+ done({ ok: parsed.ok === true, ...(typeof parsed.description === 'string' ? { description: parsed.description } : {}), ...(typeof parsed.result?.message_id === 'number' ? { messageId: parsed.result.message_id } : {}) });
10048
+ }
10049
+ catch {
10050
+ done({ ok: false, description: `unparseable response (HTTP ${res.statusCode ?? '?'})` });
10051
+ }
10052
+ });
10053
+ });
10054
+ req.on('error', (e) => done({ ok: false, description: e.message }));
10055
+ req.on('timeout', () => { req.destroy(); done({ ok: false, description: 'timeout after 30s' }); });
10056
+ req.write(payload);
10057
+ req.end();
10058
+ });
10059
+ }
10060
+ async function cmdTgPost(options, flags, cwd, write) {
10061
+ const repoRoot = resolve(options.get('project') ?? cwd);
10062
+ const json = flags.has('json');
10063
+ const draftPath = (options.get('draft') ?? '').trim();
10064
+ if (draftPath === '') {
10065
+ write('dz tg-post: --draft <file.html> is required');
10066
+ return 2;
10067
+ }
10068
+ let draft;
10069
+ try {
10070
+ draft = readFileSync(resolve(cwd, draftPath), 'utf-8');
10071
+ }
10072
+ catch {
10073
+ write(`dz tg-post: cannot read draft ${draftPath}`);
10074
+ return 2;
10075
+ }
10076
+ const issues = tgPostHtmlIssues(draft);
10077
+ // Provenance, in-process. `--manifest` names the draft's sources; its absence is a refusal at the
10078
+ // decision layer, not a quiet pass here.
10079
+ let provenanceOutcome = 'skipped';
10080
+ const manifestPath = (options.get('manifest') ?? '').trim();
10081
+ if (manifestPath !== '') {
10082
+ let manifest = null;
10083
+ try {
10084
+ manifest = parseSourceManifest(readFileSync(resolve(cwd, manifestPath), 'utf-8'));
10085
+ }
10086
+ catch {
10087
+ manifest = null;
10088
+ }
10089
+ const publicRecords = new Set();
10090
+ const show = spawnSync('git', ['-C', repoRoot, 'show', `HEAD:${PROVENANCE_PUBLIC_REL}`], { encoding: 'utf-8', maxBuffer: 8 * 1024 * 1024 });
10091
+ if (show.error === undefined && show.status === 0) {
10092
+ try {
10093
+ const raw = JSON.parse(show.stdout ?? '');
10094
+ if (Array.isArray(raw.records))
10095
+ for (const r of raw.records)
10096
+ if (typeof r === 'string')
10097
+ publicRecords.add(r);
10098
+ }
10099
+ catch { /* an unparseable committed list clears nothing */ }
10100
+ }
10101
+ const resolved = new Map();
10102
+ const toAsk = [];
10103
+ for (const c of manifest?.claims ?? []) {
10104
+ if (c.kind !== 'path' || typeof c.source !== 'string' || c.source.trim() === '')
10105
+ continue;
10106
+ const src = c.source.trim();
10107
+ if (resolved.has(src))
10108
+ continue;
10109
+ const real = provenanceResolve(repoRoot, src);
10110
+ resolved.set(src, real);
10111
+ if (real !== null)
10112
+ toAsk.push(real);
10113
+ }
10114
+ const tracked = new Set();
10115
+ const dirty = new Set();
10116
+ if (toAsk.length > 0) {
10117
+ const ls = spawnSync('git', ['-C', repoRoot, 'ls-files', '-z', '--', ...toAsk], { encoding: 'utf-8', maxBuffer: 16 * 1024 * 1024 });
10118
+ if (ls.error === undefined && ls.status === 0) {
10119
+ for (const rel of (ls.stdout ?? '').split('\0'))
10120
+ if (rel !== '')
10121
+ tracked.add(resolve(repoRoot, rel));
10122
+ }
10123
+ const onDisk = spawnSync('git', ['-C', repoRoot, 'hash-object', '--no-filters', '--', ...toAsk], { encoding: 'utf-8', maxBuffer: 16 * 1024 * 1024 });
10124
+ const inHead = spawnSync('git', ['-C', repoRoot, 'ls-tree', '-z', 'HEAD', '--', ...toAsk], { encoding: 'utf-8', maxBuffer: 16 * 1024 * 1024 });
10125
+ if (onDisk.error !== undefined || onDisk.status !== 0 || inHead.error !== undefined || inHead.status !== 0) {
10126
+ for (const p of toAsk)
10127
+ dirty.add(p);
10128
+ }
10129
+ else {
10130
+ const diskHashes = (onDisk.stdout ?? '').split('\n').map((l) => l.trim()).filter((l) => l !== '');
10131
+ const headHash = new Map();
10132
+ for (const rec of (inHead.stdout ?? '').split('\0')) {
10133
+ if (rec === '')
10134
+ continue;
10135
+ const tab = rec.indexOf('\t');
10136
+ if (tab < 0)
10137
+ continue;
10138
+ const parts = rec.slice(0, tab).split(/\s+/);
10139
+ headHash.set(resolve(repoRoot, rec.slice(tab + 1)), parts[2] ?? '');
10140
+ }
10141
+ toAsk.forEach((abs, i) => {
10142
+ const committed = headHash.get(abs);
10143
+ if (committed === undefined || committed !== diskHashes[i])
10144
+ dirty.add(abs);
10145
+ });
10146
+ }
10147
+ }
10148
+ const decision = decideSourceProvenance(manifest, {
10149
+ ignoredPaths: provenanceIgnored(repoRoot, toAsk),
10150
+ publicRecords,
10151
+ resolved,
10152
+ trackedPaths: tracked,
10153
+ dirtyPaths: dirty,
10154
+ });
10155
+ provenanceOutcome = decision.outcome;
10156
+ if (!json)
10157
+ for (const line of renderSourceProvenance(decision))
10158
+ write(line);
10159
+ }
10160
+ // ADR-005 autopublish guards: read the stop-cord and the send journal as FACTS, then let the pure
10161
+ // decideTgSend judge. An UNREADABLE journal stays undefined ⇒ decideTgSend fails closed on G4/G5.
10162
+ const tgDir = join(repoRoot, '.dz', 'tg-post');
10163
+ const halted = existsSync(join(tgDir, 'HALT'));
10164
+ const sha256 = tgVisibleSha256(draft);
10165
+ let sentLog;
10166
+ const sentLogPath = join(tgDir, 'sent-log.jsonl');
10167
+ if (!existsSync(sentLogPath)) {
10168
+ sentLog = []; // no journal yet is an EMPTY journal, not an unreadable one — a fresh channel sends
10169
+ }
10170
+ else {
10171
+ try {
10172
+ sentLog = [];
10173
+ for (const line of readFileSync(sentLogPath, 'utf-8').split('\n')) {
10174
+ if (line.trim() === '')
10175
+ continue;
10176
+ const r = JSON.parse(line);
10177
+ if (typeof r.sha256 === 'string' && typeof r.ts === 'string') {
10178
+ sentLog.push({ sha256: r.sha256, ts: r.ts, ...(r.status === 'pending' || r.status === 'sent' ? { status: r.status } : {}) });
10179
+ }
10180
+ }
10181
+ }
10182
+ catch {
10183
+ sentLog = undefined; // genuinely unreadable ⇒ fail-closed
10184
+ }
10185
+ }
10186
+ const decision = decideTgSend({
10187
+ issues,
10188
+ provenanceOutcome,
10189
+ confirmed: flags.has('send') && flags.has('yes'),
10190
+ nowUtcIso: new Date().toISOString(),
10191
+ nightOverride: flags.has('night'),
10192
+ halted,
10193
+ sha256,
10194
+ sentLog,
10195
+ maxPostsPerDay: (() => { const n = Number(options.get('max-per-day')); return Number.isFinite(n) && n > 0 ? n : 10; })(),
10196
+ });
10197
+ const visible = tgVisibleLength(draft);
10198
+ if (!json) {
10199
+ for (const i of issues)
10200
+ write(` [${i.kind}] ${i.detail}`);
10201
+ write(`dz tg-post: ${decision.action === 'send' ? 'SENDING' : 'DRY-RUN / REFUSED'} — ${decision.reason}`);
10202
+ write(` ${visible} visible character(s) of ${TG_TEXT_LIMIT}; provenance: ${provenanceOutcome}`);
10203
+ }
10204
+ if (decision.action !== 'send') {
10205
+ if (json)
10206
+ write(JSON.stringify({ ok: false, action: decision.action, reason: decision.reason, issues, visible, provenance: provenanceOutcome }));
10207
+ // A refused send exits 1; a clean DRY-RUN (no --send asked) exits 0 — asking to see is not a failure.
10208
+ return flags.has('send') ? 1 : issues.length > 0 ? 1 : 0;
10209
+ }
10210
+ const token = tgReadToken(repoRoot, write);
10211
+ if (token === null)
10212
+ return 2;
10213
+ const channel = (options.get('channel') ?? '').trim();
10214
+ if (channel === '') {
10215
+ write('dz tg-post: --channel @name (or a chat id) is required to send');
10216
+ return 2;
10217
+ }
10218
+ // Two-phase journal (Codex A-): write a PENDING row BEFORE the network call. If the process dies
10219
+ // between send and the sent-row, G5 dedup sees this pending row on the next run and refuses to
10220
+ // double-publish. Best-effort — a pending-write failure is warned, not fatal (better to risk one
10221
+ // duplicate than to block a legitimate send on a full disk).
10222
+ try {
10223
+ mkdirSync(tgDir, { recursive: true });
10224
+ appendFileSync(sentLogPath, JSON.stringify({ sha256, ts: new Date().toISOString(), channel, status: 'pending' }) + '\n');
10225
+ }
10226
+ catch (e) {
10227
+ write(`dz tg-post: WARNING — could not write the PENDING journal row (${e.message}); the crash-window dedup guard is degraded for this send`);
10228
+ }
10229
+ const sent = await tgApi(token, 'sendMessage', {
10230
+ chat_id: channel,
10231
+ text: draft,
10232
+ parse_mode: 'HTML',
10233
+ // ADR-004: x.com previews in Telegram are broken — never rely on them.
10234
+ link_preview_options: { is_disabled: !flags.has('preview') },
10235
+ });
10236
+ if (!sent.ok) {
10237
+ write(`dz tg-post: Telegram refused — ${sent.description ?? 'no description'}`);
10238
+ if (json)
10239
+ write(JSON.stringify({ ok: false, action: 'send', reason: sent.description ?? 'refused', visible }));
10240
+ return 1;
10241
+ }
10242
+ // Record the send AFTER Telegram accepted it (never before — a failed send must not eat the daily
10243
+ // limit or block a retry via dedup). Best-effort append; a journal write failure is logged, not
10244
+ // fatal — the post already went out.
10245
+ try {
10246
+ mkdirSync(tgDir, { recursive: true });
10247
+ appendFileSync(sentLogPath, JSON.stringify({ sha256, ts: new Date().toISOString(), channel, messageId: sent.messageId ?? null, status: 'sent' }) + '\n');
10248
+ }
10249
+ catch (e) {
10250
+ write(`dz tg-post: WARNING — sent, but could not record it in ${sentLogPath} (${e.message}) — the daily limit and dedup may under-count until fixed`);
10251
+ }
10252
+ write(`dz tg-post: sent to ${channel}${sent.messageId !== undefined ? ` (message ${sent.messageId})` : ''}`);
10253
+ if (json)
10254
+ write(JSON.stringify({ ok: true, action: 'send', channel, messageId: sent.messageId ?? null, visible }));
10255
+ return 0;
10256
+ }
10257
+ async function cmdRecap(options, flags, cwd, write) {
9685
10258
  const repo = resolve(options.get('project') ?? cwd);
9686
10259
  const json = flags.has('json');
10260
+ if (flags.has('refresh-publishes')) {
10261
+ const cache = await fetchNpmPublishTimes(repo, json ? () => { } : write);
10262
+ const cachePath = join(repo, ...RECAP_NPM_CACHE_REL.split('/'));
10263
+ mkdirSync(dirname(cachePath), { recursive: true });
10264
+ writeFileSync(cachePath, `${JSON.stringify(cache, null, 2)}\n`);
10265
+ if (!json) {
10266
+ write(`dz recap: publish-times cache written — ${Object.keys(cache.packages).length} package(s)${cache.failed.length > 0 ? `, ${cache.failed.length} FAILED: ${cache.failed.join(', ')}` : ''}`);
10267
+ }
10268
+ }
9687
10269
  // Every horizon is RECOGNISED, including the refused ones — swallowing `--year` silently would be
9688
10270
  // the same defect as a gate that passes because it never ran.
9689
10271
  const asked = ['day', 'week', 'month', ...REFUSED_HORIZONS].filter((h) => flags.has(h));
@@ -9719,11 +10301,23 @@ function cmdRecap(options, flags, cwd, write) {
9719
10301
  reuse: recapReuse(repo, window),
9720
10302
  uncommittedSlugs: deliveries.uncommitted.sort(),
9721
10303
  });
9722
- if (json)
9723
- write(JSON.stringify(report));
9724
- else
10304
+ if (json) {
10305
+ write(JSON.stringify({ ...report, publishesMeta: publishes === null ? null : { fetchedAt: publishes.fetchedAt ?? null, failed: publishes.failed ?? [] } }));
10306
+ }
10307
+ else {
9725
10308
  for (const line of renderRecap(report))
9726
10309
  write(line);
10310
+ // The cache's AGE and its failures print beside the numbers they qualify: third-party
10311
+ // timestamps are only as fresh as the last explicit --refresh-publishes, and a package the
10312
+ // registry did not answer for is MISSING from the section above — said, not implied.
10313
+ if (publishes?.fetchedAt !== undefined) {
10314
+ const days = Math.floor((Date.parse(`${at.slice(0, 10)}T00:00:00Z`) - Date.parse(publishes.fetchedAt)) / 86_400_000);
10315
+ write(` ℹ publish-times cache fetched ${publishes.fetchedAt.slice(0, 10)}${Number.isFinite(days) && days > 0 ? ` — ${days} day(s) before this report's anchor` : ''}; refresh with --refresh-publishes`);
10316
+ }
10317
+ if (publishes?.failed !== undefined) {
10318
+ write(` ⚠ the registry did not answer for ${publishes.failed.length} package(s) at the last refresh: ${publishes.failed.join(', ')} — their publishes are MISSING above, not zero`);
10319
+ }
10320
+ }
9727
10321
  return 0;
9728
10322
  }
9729
10323
  function cmdFeatureAdrRecord(options, flags, cwd, write) {
@@ -12811,6 +13405,10 @@ export async function runCli(argv, io = {}) {
12811
13405
  return cmdScore(options, flags, cwd, write);
12812
13406
  case 'recap':
12813
13407
  return cmdRecap(options, flags, cwd, write);
13408
+ case 'cadence':
13409
+ return cmdCadence(options, flags, cwd, write);
13410
+ case 'tg-post':
13411
+ return cmdTgPost(options, flags, cwd, write);
12814
13412
  case 'name-check':
12815
13413
  return cmdNameCheck(options, flags, cwd, write);
12816
13414
  case 'provenance-check':