@dzhechkov/harness-cli 0.8.2 → 0.8.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/.dz-manifest.json +20 -20
- package/README.md +127 -14
- package/dist/cli.d.ts +2 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +897 -38
- package/dist/cli.js.map +1 -1
- package/dist/core-compat.d.ts +1 -1
- package/dist/core-compat.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/known-flags.d.ts.map +1 -1
- package/dist/known-flags.js +3 -0
- package/dist/known-flags.js.map +1 -1
- package/package.json +24 -21
- package/sbom.json +19 -19
- package/src/cli.ts +905 -25
- package/src/core-compat.ts +1 -1
- package/src/index.ts +1 -1
- package/src/known-flags.ts +3 -0
package/src/cli.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
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
|
+
import { appendFileSync, chmodSync, closeSync, cpSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, type Dirent } from 'node:fs';
|
|
8
8
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
9
9
|
import { fileURLToPath } from 'node:url';
|
|
10
10
|
import { request as httpsRequest } from 'node:https';
|
|
@@ -15,6 +15,7 @@ import { execFile, execFileSync, execSync, spawn, spawnSync, type ChildProcess }
|
|
|
15
15
|
import { createHash, randomBytes } from 'node:crypto';
|
|
16
16
|
import { homedir, tmpdir } from 'node:os';
|
|
17
17
|
import { createRequire } from 'node:module';
|
|
18
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
18
19
|
|
|
19
20
|
import {
|
|
20
21
|
createSkill,
|
|
@@ -158,6 +159,11 @@ import {
|
|
|
158
159
|
parseWeeklyResetAnchor,
|
|
159
160
|
claimCheck,
|
|
160
161
|
summarize,
|
|
162
|
+
BUNDLED_SLOP_REGISTRY_URL,
|
|
163
|
+
DEFAULT_SLOP_CONFIG,
|
|
164
|
+
parseSlopRegistry,
|
|
165
|
+
slopLint,
|
|
166
|
+
validateSlopLintConfig,
|
|
161
167
|
queryBookKnowledge,
|
|
162
168
|
loadStorePatternsSync,
|
|
163
169
|
patternRecordId,
|
|
@@ -278,6 +284,7 @@ import {
|
|
|
278
284
|
harvestStageOutcomes,
|
|
279
285
|
recommendModels,
|
|
280
286
|
planFeed,
|
|
287
|
+
unfedRuns,
|
|
281
288
|
GRADE_SUCCESS_FLOOR,
|
|
282
289
|
COST_LADDER,
|
|
283
290
|
splitScenarios,
|
|
@@ -302,6 +309,13 @@ import {
|
|
|
302
309
|
renderContentProbe,
|
|
303
310
|
findNonRegistrableSkillDirs,
|
|
304
311
|
assembleCompoundingReport,
|
|
312
|
+
buildDeadwoodReport,
|
|
313
|
+
compactCmdUsageIfNeeded,
|
|
314
|
+
measureCmdUsageDepthDays,
|
|
315
|
+
recordCommandInvocation,
|
|
316
|
+
resolveCmdUsageRoot,
|
|
317
|
+
renderDeadwoodReport,
|
|
318
|
+
CMD_USAGE_LOG_RELATIVE,
|
|
305
319
|
banditStats,
|
|
306
320
|
narrowBanditReport,
|
|
307
321
|
renderBanditHealth,
|
|
@@ -457,6 +471,9 @@ import {
|
|
|
457
471
|
amendmentVerdictLine,
|
|
458
472
|
amendmentsMissingFromPlan,
|
|
459
473
|
AMENDMENT_VACUITY_NOTE,
|
|
474
|
+
extractContractChecklist,
|
|
475
|
+
parseContractVerdictReport,
|
|
476
|
+
verifyContractVerdicts,
|
|
460
477
|
decideSignableSet,
|
|
461
478
|
signableSetLine,
|
|
462
479
|
decideRecordWrite,
|
|
@@ -467,6 +484,7 @@ import {
|
|
|
467
484
|
CADENCE_WINDOW_DAYS,
|
|
468
485
|
readQeRounds,
|
|
469
486
|
QE_ROUNDS_DEFAULT_CEILING,
|
|
487
|
+
adviseRestart,
|
|
470
488
|
describeStoreLocation,
|
|
471
489
|
storeLocationLine,
|
|
472
490
|
resolveTeachTarget,
|
|
@@ -502,10 +520,30 @@ import type { IdeaRecord, IdeaStatus } from '@dzhechkov/harness-core';
|
|
|
502
520
|
import type { Family, ModelRung, Candidate as BtoCandidate, DimScores } from '@dzhechkov/harness-core';
|
|
503
521
|
import type { SetupSpec } from '@dzhechkov/harness-core';
|
|
504
522
|
import type { LogTail } from '@dzhechkov/harness-core';
|
|
505
|
-
import type {
|
|
523
|
+
import type { DeadwoodInventoryItem } from '@dzhechkov/harness-core';
|
|
524
|
+
import type { ContractDiagnostic, ContractEvidenceReader } from '@dzhechkov/harness-core';
|
|
525
|
+
import type { ProvenanceMode, PackVerdict, ClaudeUsageModel, PatternRecord, TargetName, BookKU, HarmonizeReport, UsageCalibrationPlan, ClaimFinding, RecallUsagePatternRow, GateExecution, GateStep, SlopFinding, SlopLintConfig, SlopRegistry } from '@dzhechkov/harness-core';
|
|
506
526
|
import { getPreset, PRESET_NAMES } from '@dzhechkov/harness-presets';
|
|
507
527
|
import { scanGitHub, analyzeRepo, generateReport, deepAnalyze, scanAllSources, ScoutMemory } from '@dzhechkov/scout';
|
|
508
528
|
|
|
529
|
+
/** Literal command inventory, pinned against the main dispatch switch by a layer-1 test. */
|
|
530
|
+
export const DZ_COMMANDS: readonly string[] = [
|
|
531
|
+
'init', 'verify', 'sync', 'update', 'list', 'create-skill', 'info', 'scout',
|
|
532
|
+
'workflow', 'workflow-lint', 'workflow-trace', 'migrate', 'doctor', 'install',
|
|
533
|
+
'bundle', 'teach', 'consolidate', 'recall', 'vector', 'brain', 'statusline',
|
|
534
|
+
'usage', 'claim-check', 'lint', 'sign', 'sbom', 'guard', 'verify-pack', 'setup',
|
|
535
|
+
'pretrain', 'compose', 'diff', 'recommend', 'upgrade', 'auto-canonicalize',
|
|
536
|
+
'publish', 'release', 'parity', 'registry', 'benchmark', 'mcp-scan',
|
|
537
|
+
'sync-upstream', 'drift-check', 'hooks-sync', 'agents-sync', 'sync-canonical',
|
|
538
|
+
'plugin', 'downloads', 'stats', 'architecture', 'project-skills', 'mr-rakes',
|
|
539
|
+
'retro', 'feature-adr-setup', 'challenge', 'discrimination-check',
|
|
540
|
+
'mutation-gate', 'delivery-check', 'skills-verify', 'compounding', 'deadwood',
|
|
541
|
+
'epoch-replay', 'score', 'recap', 'cadence', 'qe-rounds', 'restart-advisor', 'tg-post',
|
|
542
|
+
'name-check', 'provenance-check', 'feature-adr-record', 'amendment-check', 'contract-check',
|
|
543
|
+
'feature-adr-checkpoint', 'profile', 'reqe', 'qe-bridge', 'backlog', 'routing',
|
|
544
|
+
'bto-optimize', 'dashboard', 'roam', 'import-ecc',
|
|
545
|
+
];
|
|
546
|
+
|
|
509
547
|
const USAGE = `dz - DZ cross-platform harness CLI
|
|
510
548
|
|
|
511
549
|
Usage:
|
|
@@ -539,6 +577,7 @@ Usage:
|
|
|
539
577
|
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)
|
|
540
578
|
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)
|
|
541
579
|
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)
|
|
580
|
+
dz deadwood [--weeks <n>] [--json] (advisory zero-usage candidates for human deprecation review; safety-excluded surfaces carry reasons; never deletes or deprecates anything; shallow history says INSUFFICIENT_DATA)
|
|
542
581
|
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)
|
|
543
582
|
dz epoch-replay --emit [--project <dir>] [--limit <N>] [--seed <N>] [--out <file>] (cold-vs-warm work order: instances + PRE-REGISTERED blind A/B assignment; the runner never calls a model)
|
|
544
583
|
dz epoch-replay --judge <filled-work-order.json> [--out <file>] (blind judge prompts from the filled plans)
|
|
@@ -547,6 +586,7 @@ Usage:
|
|
|
547
586
|
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)
|
|
548
587
|
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)
|
|
549
588
|
dz qe-rounds (--slug <feature> | --feature-dir <abs>) [--ceiling <n>] [--project <dir>] [--json] (how many Step-8 review rounds has this feature ALREADY had? Reads what dz qe-bridge already wrote — signoff-<runId>.json and failed-*.json under features/<slug>/.fa-state/qe-bridge — and writes nothing itself, so it can answer for runs already past. A round is a runId, not a file; an attempt with no verdict is counted SEPARATELY and never merged; an unreadable record is NAMED and the count is declared a LOWER BOUND. ONE directory, never a union across checkouts. exit 0 under the ceiling / 1 at-or-over — owner decides, the command does not judge whether the rounds were warranted / 2 NOT ESTABLISHED, which is never "zero rounds")
|
|
589
|
+
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)
|
|
550
590
|
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)
|
|
551
591
|
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)
|
|
552
592
|
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)
|
|
@@ -556,6 +596,7 @@ Usage:
|
|
|
556
596
|
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)
|
|
557
597
|
dz sbom [--pack <name>] [--out <file>] (CycloneDX software bill of materials for the workspace, or for one pack with --pack)
|
|
558
598
|
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)
|
|
599
|
+
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)
|
|
559
600
|
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)
|
|
560
601
|
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)
|
|
561
602
|
dz profile [init|show|set|sync] [--json] (WHO the assistant is talking to — per-user store at ~/.dz/profile.json (0600, NEVER in a project), delivered as a marked block in ~/.claude/CLAUDE.md so it loads in EVERY project, dz installed or not. init = five questions (language, register, deep/weak domains as comma lists — "networking (CCIE; NSX)" keeps the parenthetical as the note, Enter skips — teaches y/n with one re-ask, never a silent default); show ALWAYS prints the store path + age + drift verdict + the rendered block; set register|language|teaches <v> or set deep|weak add|rm <tag> [note] — register accepts the owner's own words (профи / профи лайт / просто), an unknown value is REFUSED naming the accepted set; sync re-writes the block (runs automatically after init/set; foreign content byte-for-byte, timestamped backup before every modifying write). The register changes FORM, never FACTS, and governs dialogue only — never ADRs/commits/QE reports; both rules are baked into the rendered block at every level. exit 0 done / 1 no profile or failed / 2 refused input)
|
|
@@ -570,7 +611,7 @@ Usage:
|
|
|
570
611
|
dz backlog ship <id> [<id>…] [--reason <t>] [--dry-run] [--project <dir>] [--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)
|
|
571
612
|
dz backlog drop <id> [<id>…] [--reason <t>] [--dry-run] [--project <dir>] [--json] (retire an idea: new|enriched|in-progress → dropped)
|
|
572
613
|
dz backlog edit <id> --text "<new>" | --append "<more>" [--dry-run] [--project <dir>] [--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)
|
|
573
|
-
dz routing recommend [--tier <t>] [--apply] [--json] (per-stage args.models suggestion from REAL telemetry — harness records + imported run-meta sidecars — printed WITH its basis
|
|
614
|
+
dz routing recommend [--tier <t>] [--apply] [--json] (per-stage args.models suggestion from REAL telemetry — harness records + imported run-meta sidecars — printed WITH its basis + current/STALE/UNFED store receipt; qe is FORCED cross-family of code; --apply feeds .dz/routing-outcomes.json idempotently by runId)
|
|
574
615
|
dz backlog reopen <id> [<id>…] [--reason <t>] [--dry-run] [--project <dir>] [--json] (back to the pool: shipped|dropped|in-progress → new)
|
|
575
616
|
dz backlog enrich <id> [--project <dir>] [--json] (stage the idea2prd input scaffold in features/<slug>/ and hand off to the idea2prd-manual skill — the CLI never fabricates a PRD)
|
|
576
617
|
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)
|
|
@@ -600,6 +641,7 @@ Usage:
|
|
|
600
641
|
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)
|
|
601
642
|
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)
|
|
602
643
|
dz claim-check [paths...] [--json] [--fail-on high|medium|none] [--project <dir>] (enforce the Integrity Rule: flag untagged/overstated accuracy claims; default scan = root README.md + every discovered package's README.md + features/*/08_qe_report.md + docs/**/*.md (historical feature artifacts are NOT scanned — pass paths explicitly); exit 1 only at/above --fail-on, default high)
|
|
644
|
+
dz lint [paths...] [--json] [--config <file>] [--registry <file>] [--project <dir>] (advisory EN/RU prose-style lint; findings exit 0, incomplete input/policy exits 1, usage exits 2)
|
|
603
645
|
dz pretrain [--project <dir>]
|
|
604
646
|
dz recommend "<task description>"
|
|
605
647
|
dz compose <preset1+preset2+...> [--target <name>]
|
|
@@ -2741,6 +2783,114 @@ function cmdQeRounds(options: Map<string, string>, flags: Set<string>, cwd: stri
|
|
|
2741
2783
|
return 0;
|
|
2742
2784
|
}
|
|
2743
2785
|
|
|
2786
|
+
type RestartAdvisorDiskRead =
|
|
2787
|
+
| { readonly text: string | null; readonly diagnostic: null }
|
|
2788
|
+
| { readonly text: null; readonly diagnostic: string };
|
|
2789
|
+
|
|
2790
|
+
/** Read one fixed advisor evidence path without following a symlink or escaping the project root. */
|
|
2791
|
+
function readRestartAdvisorEvidence(root: string, relativePath: string): RestartAdvisorDiskRead {
|
|
2792
|
+
const contained = containedUnderRoot(root, relativePath);
|
|
2793
|
+
if (!contained.ok) {
|
|
2794
|
+
return { text: null, diagnostic: `${relativePath}: ${contained.why}` };
|
|
2795
|
+
}
|
|
2796
|
+
let stat;
|
|
2797
|
+
try {
|
|
2798
|
+
stat = lstatSync(contained.path);
|
|
2799
|
+
} catch (error) {
|
|
2800
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { text: null, diagnostic: null };
|
|
2801
|
+
return { text: null, diagnostic: `${relativePath}: evidence cannot be inspected (${(error as Error).message})` };
|
|
2802
|
+
}
|
|
2803
|
+
if (stat.isSymbolicLink()) {
|
|
2804
|
+
return { text: null, diagnostic: `${relativePath}: symlink evidence is refused` };
|
|
2805
|
+
}
|
|
2806
|
+
if (!stat.isFile()) {
|
|
2807
|
+
return { text: null, diagnostic: `${relativePath}: evidence exists but is not a regular file` };
|
|
2808
|
+
}
|
|
2809
|
+
try {
|
|
2810
|
+
return { text: readFileSync(contained.path, 'utf-8'), diagnostic: null };
|
|
2811
|
+
} catch (error) {
|
|
2812
|
+
return { text: null, diagnostic: `${relativePath}: evidence cannot be read (${(error as Error).message})` };
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
/** Manual restart recommendation only. I/O ends here; the core remains deterministic and pure. */
|
|
2817
|
+
function cmdRestartAdvisor(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
|
|
2818
|
+
const json = flags.has('json');
|
|
2819
|
+
const rawSlug = options.get('slug') ?? '';
|
|
2820
|
+
const slug = rawSlug.trim();
|
|
2821
|
+
const thresholdRaw = options.get('threshold');
|
|
2822
|
+
const roundsRaw = options.get('rounds');
|
|
2823
|
+
const thresholdOrigin = thresholdRaw === undefined ? 'default' as const : 'flag' as const;
|
|
2824
|
+
const roundsOrigin = roundsRaw === undefined ? 'default' as const : 'flag' as const;
|
|
2825
|
+
|
|
2826
|
+
const emit = (advice: ReturnType<typeof adviseRestart>): number => {
|
|
2827
|
+
if (json) {
|
|
2828
|
+
write(JSON.stringify(advice));
|
|
2829
|
+
} else {
|
|
2830
|
+
write(`dz restart-advisor: ${advice.recommendation} — advisory only; autoAction=false`);
|
|
2831
|
+
write(` policy: threshold ${String(advice.policy.threshold)} (${advice.policy.thresholdOrigin}), rounds ${String(advice.policy.rounds)} (${advice.policy.roundsOrigin})`);
|
|
2832
|
+
write(` source: ${advice.sourcePath ?? 'none'}${advice.corroborated ? ' (corroborated by both stores)' : ''}`);
|
|
2833
|
+
for (const diagnostic of advice.diagnostics) write(` diagnostic: ${JSON.stringify(diagnostic)}`);
|
|
2834
|
+
if (advice.diagnosticsSummary.truncated) {
|
|
2835
|
+
write(` diagnostics: ${advice.diagnosticsSummary.returned}/${advice.diagnosticsSummary.total} shown`);
|
|
2836
|
+
}
|
|
2837
|
+
write(advice.decisionLogLine);
|
|
2838
|
+
}
|
|
2839
|
+
return advice.recommendation === 'RESTART_CODE_STAGE'
|
|
2840
|
+
|| advice.recommendation === 'NO_RESTART_RECOMMENDATION'
|
|
2841
|
+
? 0
|
|
2842
|
+
: 2;
|
|
2843
|
+
};
|
|
2844
|
+
|
|
2845
|
+
const inputErrors: string[] = [];
|
|
2846
|
+
for (const flag of flags) {
|
|
2847
|
+
if (flag !== 'json' && flag !== 'help') inputErrors.push(`--${flag} requires a value or is not supported`);
|
|
2848
|
+
}
|
|
2849
|
+
for (const key of options.keys()) {
|
|
2850
|
+
if (key !== 'slug' && key !== 'threshold' && key !== 'rounds') {
|
|
2851
|
+
inputErrors.push(key.startsWith('_positional_')
|
|
2852
|
+
? `unexpected argument ${JSON.stringify(options.get(key))}`
|
|
2853
|
+
: `unsupported option --${key}`);
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
if (!isSafeSlug(slug)) {
|
|
2857
|
+
inputErrors.push(`--slug ${JSON.stringify(rawSlug)} must be one kebab-case path segment (max 40 characters)`);
|
|
2858
|
+
}
|
|
2859
|
+
const threshold = thresholdRaw ?? 'D';
|
|
2860
|
+
if (threshold !== 'C' && threshold !== 'D') {
|
|
2861
|
+
inputErrors.push(`--threshold ${JSON.stringify(thresholdRaw)} must be exactly C or D`);
|
|
2862
|
+
}
|
|
2863
|
+
const roundsValue = roundsRaw === undefined ? 2 : Number(roundsRaw);
|
|
2864
|
+
if (!Number.isFinite(roundsValue) || !Number.isInteger(roundsValue) || roundsValue < 1) {
|
|
2865
|
+
inputErrors.push(`--rounds ${JSON.stringify(roundsRaw)} must be a positive integer`);
|
|
2866
|
+
}
|
|
2867
|
+
if (inputErrors.length > 0) {
|
|
2868
|
+
return emit(adviseRestart({ slug, inputErrors }, {
|
|
2869
|
+
thresholdOrigin,
|
|
2870
|
+
roundsOrigin,
|
|
2871
|
+
}));
|
|
2872
|
+
}
|
|
2873
|
+
|
|
2874
|
+
const root = resolve(cwd);
|
|
2875
|
+
const checkpointPath = `features/${slug}/.fa-state/checkpoints.jsonl`;
|
|
2876
|
+
const trainingPath = `.dz/fa-training/${slug}/qe.jsonl`;
|
|
2877
|
+
const checkpoints = readRestartAdvisorEvidence(root, checkpointPath);
|
|
2878
|
+
const trainingPairs = readRestartAdvisorEvidence(root, trainingPath);
|
|
2879
|
+
const readDiagnostics = [checkpoints.diagnostic, trainingPairs.diagnostic]
|
|
2880
|
+
.filter((entry): entry is string => entry !== null);
|
|
2881
|
+
return emit(adviseRestart({
|
|
2882
|
+
slug,
|
|
2883
|
+
checkpointsJsonl: checkpoints.text,
|
|
2884
|
+
trainingPairsJsonl: trainingPairs.text,
|
|
2885
|
+
readDiagnostics,
|
|
2886
|
+
}, {
|
|
2887
|
+
threshold: threshold as 'C' | 'D',
|
|
2888
|
+
rounds: roundsValue,
|
|
2889
|
+
thresholdOrigin,
|
|
2890
|
+
roundsOrigin,
|
|
2891
|
+
}));
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2744
2894
|
function cmdCadence(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
|
|
2745
2895
|
const root = resolve(cwd, options.get('project') ?? '.');
|
|
2746
2896
|
const windowRaw = (options.get('window') ?? 'week').trim() as CadenceWindow;
|
|
@@ -6478,6 +6628,256 @@ function cmdBenchmark(options: Map<string, string>, flags: Set<string>, cwd: str
|
|
|
6478
6628
|
return score.passRate >= 80 ? 0 : 1;
|
|
6479
6629
|
}
|
|
6480
6630
|
|
|
6631
|
+
interface SlopScanRow {
|
|
6632
|
+
readonly path: string;
|
|
6633
|
+
readonly status: 'scanned' | 'skipped';
|
|
6634
|
+
readonly paragraphs?: number;
|
|
6635
|
+
readonly findings?: number;
|
|
6636
|
+
readonly reason?: string;
|
|
6637
|
+
}
|
|
6638
|
+
|
|
6639
|
+
interface SlopCliError {
|
|
6640
|
+
readonly path?: string;
|
|
6641
|
+
readonly message: string;
|
|
6642
|
+
}
|
|
6643
|
+
|
|
6644
|
+
interface SlopCliFinding extends SlopFinding {
|
|
6645
|
+
readonly file: string;
|
|
6646
|
+
}
|
|
6647
|
+
|
|
6648
|
+
interface SlopCliReport {
|
|
6649
|
+
readonly schema: 'dz-slop-lint/1';
|
|
6650
|
+
readonly advisory: true;
|
|
6651
|
+
readonly ok: boolean;
|
|
6652
|
+
readonly status: 'clean' | 'findings' | 'incomplete';
|
|
6653
|
+
readonly findings: readonly SlopCliFinding[];
|
|
6654
|
+
readonly scanned: readonly SlopScanRow[];
|
|
6655
|
+
readonly skipped: readonly SlopScanRow[];
|
|
6656
|
+
readonly errors: readonly SlopCliError[];
|
|
6657
|
+
}
|
|
6658
|
+
|
|
6659
|
+
const SLOP_MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
6660
|
+
const SLOP_COURSE_TEXT_KEYS = new Set([
|
|
6661
|
+
'back', 'courseDescription', 'courseTitle', 'description', 'explanation', 'front', 'instruction',
|
|
6662
|
+
'keyConcept', 'keyConcepts', 'note', 'options', 'question', 'reflection', 'shortTitle', 'strengths',
|
|
6663
|
+
'theory', 'title', 'weaknesses', 'wrapup',
|
|
6664
|
+
]);
|
|
6665
|
+
|
|
6666
|
+
function slopDisplayPath(root: string, absolute: string): string {
|
|
6667
|
+
const rel = relative(root, absolute);
|
|
6668
|
+
return rel !== '' && !rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel) ? rel : absolute;
|
|
6669
|
+
}
|
|
6670
|
+
|
|
6671
|
+
function slopWalk(dir: string, depth = 0): string[] {
|
|
6672
|
+
if (depth > 16) return [];
|
|
6673
|
+
const out: string[] = [];
|
|
6674
|
+
let entries: Dirent<string>[];
|
|
6675
|
+
try {
|
|
6676
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
6677
|
+
} catch {
|
|
6678
|
+
return out;
|
|
6679
|
+
}
|
|
6680
|
+
entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
6681
|
+
for (const entry of entries) {
|
|
6682
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'build') continue;
|
|
6683
|
+
if (entry.isSymbolicLink()) continue;
|
|
6684
|
+
const full = join(dir, entry.name);
|
|
6685
|
+
if (entry.isDirectory()) out.push(...slopWalk(full, depth + 1));
|
|
6686
|
+
else if (entry.isFile() && (['.md', '.mdx'].includes(extname(entry.name).toLowerCase()) || entry.name === 'course.json')) out.push(full);
|
|
6687
|
+
}
|
|
6688
|
+
return out;
|
|
6689
|
+
}
|
|
6690
|
+
|
|
6691
|
+
function defaultSlopScanSet(root: string): string[] {
|
|
6692
|
+
const paths: string[] = [];
|
|
6693
|
+
const readme = join(root, 'README.md');
|
|
6694
|
+
if (existsSync(readme)) paths.push(readme);
|
|
6695
|
+
try {
|
|
6696
|
+
for (const pkg of discoverPackages(root)) {
|
|
6697
|
+
const packageReadme = join(pkg.dir, 'README.md');
|
|
6698
|
+
if (existsSync(packageReadme)) paths.push(packageReadme);
|
|
6699
|
+
}
|
|
6700
|
+
} catch { /* a foreign project need not be a dz workspace */ }
|
|
6701
|
+
paths.push(...slopWalk(join(root, 'packages', '@dzhechkov', 'sitedoc', 'src', 'content'))
|
|
6702
|
+
.filter((path) => ['.md', '.mdx'].includes(extname(path).toLowerCase())));
|
|
6703
|
+
try {
|
|
6704
|
+
const featureDir = join(root, 'features');
|
|
6705
|
+
for (const entry of readdirSync(featureDir, { withFileTypes: true })) {
|
|
6706
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
6707
|
+
const course = join(featureDir, entry.name, 'course.json');
|
|
6708
|
+
if (existsSync(course)) paths.push(course);
|
|
6709
|
+
}
|
|
6710
|
+
} catch { /* no features directory */ }
|
|
6711
|
+
return [...new Set(paths.map((path) => resolve(path)))].sort((a, b) => {
|
|
6712
|
+
const left = slopDisplayPath(root, a);
|
|
6713
|
+
const right = slopDisplayPath(root, b);
|
|
6714
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
6715
|
+
});
|
|
6716
|
+
}
|
|
6717
|
+
|
|
6718
|
+
function decodeSlopUtf8(path: string): string {
|
|
6719
|
+
const stat = lstatSync(path);
|
|
6720
|
+
if (!stat.isFile()) throw new Error('not a regular file');
|
|
6721
|
+
if (stat.size > SLOP_MAX_FILE_BYTES) throw new Error(`file exceeds ${SLOP_MAX_FILE_BYTES} byte limit`);
|
|
6722
|
+
const bytes = readFileSync(path);
|
|
6723
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
6724
|
+
}
|
|
6725
|
+
|
|
6726
|
+
function projectCourseJson(text: string): string | null {
|
|
6727
|
+
let value: unknown;
|
|
6728
|
+
try {
|
|
6729
|
+
value = JSON.parse(text);
|
|
6730
|
+
} catch {
|
|
6731
|
+
return null;
|
|
6732
|
+
}
|
|
6733
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
6734
|
+
const root = value as Record<string, unknown>;
|
|
6735
|
+
if (typeof root.language !== 'string' || typeof root.courseTitle !== 'string' ||
|
|
6736
|
+
!Array.isArray(root.topics) || !Array.isArray(root.sections)) return null;
|
|
6737
|
+
const output: string[] = [];
|
|
6738
|
+
const visit = (current: unknown, key = ''): void => {
|
|
6739
|
+
if (typeof current === 'string') {
|
|
6740
|
+
if (SLOP_COURSE_TEXT_KEYS.has(key) && current.trim() !== '') output.push(current);
|
|
6741
|
+
return;
|
|
6742
|
+
}
|
|
6743
|
+
if (Array.isArray(current)) {
|
|
6744
|
+
for (const item of current) visit(item, key);
|
|
6745
|
+
return;
|
|
6746
|
+
}
|
|
6747
|
+
if (current === null || typeof current !== 'object') return;
|
|
6748
|
+
for (const [childKey, child] of Object.entries(current as Record<string, unknown>)) visit(child, childKey);
|
|
6749
|
+
};
|
|
6750
|
+
visit(root);
|
|
6751
|
+
return output.join('\n\n');
|
|
6752
|
+
}
|
|
6753
|
+
|
|
6754
|
+
function slopLoadJson<T>(path: string, validate: (value: unknown) => { readonly ok: true; readonly value: T } | { readonly ok: false; readonly errors: readonly { readonly field: string; readonly value: unknown; readonly reason: string }[] }): T {
|
|
6755
|
+
const decoded = decodeSlopUtf8(path);
|
|
6756
|
+
let parsed: unknown;
|
|
6757
|
+
try {
|
|
6758
|
+
parsed = JSON.parse(decoded);
|
|
6759
|
+
} catch (error) {
|
|
6760
|
+
throw new Error(`invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
6761
|
+
}
|
|
6762
|
+
const result = validate(parsed);
|
|
6763
|
+
if (!result.ok) throw new Error(result.errors.map((error) => `${error.field}=${JSON.stringify(error.value)}: ${error.reason}`).join('; '));
|
|
6764
|
+
return result.value;
|
|
6765
|
+
}
|
|
6766
|
+
|
|
6767
|
+
/**
|
|
6768
|
+
* Read-only adapter over the pure slopLint core. Style findings are advisory by construction:
|
|
6769
|
+
* only usage errors return 2 and incomplete policy/input evidence returns 1.
|
|
6770
|
+
*/
|
|
6771
|
+
function cmdLint(
|
|
6772
|
+
options: Map<string, string>,
|
|
6773
|
+
flags: Set<string>,
|
|
6774
|
+
cwd: string,
|
|
6775
|
+
write: Write,
|
|
6776
|
+
): number {
|
|
6777
|
+
const json = flags.has('json');
|
|
6778
|
+
const root = resolve(cwd, options.get('project') ?? '.');
|
|
6779
|
+
const usageError = (message: string): number => {
|
|
6780
|
+
if (json) write(JSON.stringify({ schema: 'dz-slop-lint/1', advisory: true, ok: false, status: 'incomplete', findings: [], scanned: [], skipped: [], errors: [{ message }] }));
|
|
6781
|
+
else write(`dz lint: ${message}`);
|
|
6782
|
+
return 2;
|
|
6783
|
+
};
|
|
6784
|
+
if (flags.has('config')) return usageError('--config requires a file');
|
|
6785
|
+
if (flags.has('registry')) return usageError('--registry requires a file');
|
|
6786
|
+
|
|
6787
|
+
let config: SlopLintConfig = DEFAULT_SLOP_CONFIG;
|
|
6788
|
+
let registry: SlopRegistry;
|
|
6789
|
+
const setupErrors: SlopCliError[] = [];
|
|
6790
|
+
try {
|
|
6791
|
+
if (options.has('config')) config = slopLoadJson(resolve(root, options.get('config')!), validateSlopLintConfig);
|
|
6792
|
+
} catch (error) {
|
|
6793
|
+
const path = options.get('config');
|
|
6794
|
+
setupErrors.push({ ...(path === undefined ? {} : { path }), message: `config: ${error instanceof Error ? error.message : String(error)}` });
|
|
6795
|
+
}
|
|
6796
|
+
try {
|
|
6797
|
+
const registryPath = options.has('registry') ? resolve(root, options.get('registry')!) : fileURLToPath(BUNDLED_SLOP_REGISTRY_URL);
|
|
6798
|
+
registry = slopLoadJson(registryPath, parseSlopRegistry);
|
|
6799
|
+
} catch (error) {
|
|
6800
|
+
const path = options.get('registry');
|
|
6801
|
+
setupErrors.push({ ...(path === undefined ? {} : { path }), message: `registry: ${error instanceof Error ? error.message : String(error)}` });
|
|
6802
|
+
registry = { schema: 'dz-slop-registry/1', metadata: {} as SlopRegistry['metadata'], markers: [], adjectives: [] };
|
|
6803
|
+
}
|
|
6804
|
+
|
|
6805
|
+
const requested: string[] = [];
|
|
6806
|
+
for (let index = 0; ; index += 1) {
|
|
6807
|
+
const value = options.get(`_positional_${index}`);
|
|
6808
|
+
if (value === undefined) break;
|
|
6809
|
+
requested.push(resolve(root, value));
|
|
6810
|
+
}
|
|
6811
|
+
const explicit = requested.length > 0;
|
|
6812
|
+
const candidates = explicit ? requested.flatMap((path) => {
|
|
6813
|
+
try {
|
|
6814
|
+
const stat = lstatSync(path);
|
|
6815
|
+
if (stat.isSymbolicLink()) return [path];
|
|
6816
|
+
return stat.isDirectory() ? slopWalk(path) : [path];
|
|
6817
|
+
} catch {
|
|
6818
|
+
return [path];
|
|
6819
|
+
}
|
|
6820
|
+
}) : defaultSlopScanSet(root);
|
|
6821
|
+
const scanSet = [...new Set(candidates.map((path) => resolve(path)))].sort((a, b) => {
|
|
6822
|
+
const left = slopDisplayPath(root, a);
|
|
6823
|
+
const right = slopDisplayPath(root, b);
|
|
6824
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
6825
|
+
});
|
|
6826
|
+
|
|
6827
|
+
const findings: SlopCliFinding[] = [];
|
|
6828
|
+
const scanned: SlopScanRow[] = [];
|
|
6829
|
+
const errors = [...setupErrors];
|
|
6830
|
+
if (setupErrors.length === 0) {
|
|
6831
|
+
for (const path of scanSet) {
|
|
6832
|
+
const display = slopDisplayPath(root, path);
|
|
6833
|
+
let source: string;
|
|
6834
|
+
try {
|
|
6835
|
+
source = decodeSlopUtf8(path);
|
|
6836
|
+
} catch (error) {
|
|
6837
|
+
const message = error instanceof TypeError ? `invalid UTF-8: ${error.message}` : error instanceof Error ? error.message : String(error);
|
|
6838
|
+
scanned.push({ path: display, status: 'skipped', reason: message });
|
|
6839
|
+
errors.push({ path: display, message });
|
|
6840
|
+
continue;
|
|
6841
|
+
}
|
|
6842
|
+
if (basename(path) === 'course.json') {
|
|
6843
|
+
const projected = projectCourseJson(source);
|
|
6844
|
+
if (projected === null) {
|
|
6845
|
+
const message = 'unsupported course.json shape';
|
|
6846
|
+
scanned.push({ path: display, status: 'skipped', reason: message });
|
|
6847
|
+
if (explicit) errors.push({ path: display, message });
|
|
6848
|
+
continue;
|
|
6849
|
+
}
|
|
6850
|
+
source = projected;
|
|
6851
|
+
} else if (!['.md', '.mdx'].includes(extname(path).toLowerCase())) {
|
|
6852
|
+
const message = 'unsupported input type; expected Markdown, MDX, or recognized course.json';
|
|
6853
|
+
scanned.push({ path: display, status: 'skipped', reason: message });
|
|
6854
|
+
errors.push({ path: display, message });
|
|
6855
|
+
continue;
|
|
6856
|
+
}
|
|
6857
|
+
const result = slopLint(source, { config, registry });
|
|
6858
|
+
if (result.paragraphCount === 0) errors.push({ path: display, message: 'no analyzable prose' });
|
|
6859
|
+
for (const diagnostic of result.diagnostics) errors.push({ path: display, message: `${diagnostic.code} at line ${diagnostic.line}: ${diagnostic.message}` });
|
|
6860
|
+
for (const finding of result.findings) findings.push({ ...finding, file: display });
|
|
6861
|
+
scanned.push({ path: display, status: 'scanned', paragraphs: result.paragraphCount, findings: result.findings.length });
|
|
6862
|
+
}
|
|
6863
|
+
}
|
|
6864
|
+
// A valid empty directory/default scope is a clean advisory no-op. Explicit missing paths stay
|
|
6865
|
+
// in scanSet and fail above, while a supported file containing no prose remains incomplete.
|
|
6866
|
+
|
|
6867
|
+
const skipped = scanned.filter((row) => row.status === 'skipped');
|
|
6868
|
+
const status: SlopCliReport['status'] = errors.length > 0 ? 'incomplete' : findings.length > 0 ? 'findings' : 'clean';
|
|
6869
|
+
const report: SlopCliReport = {
|
|
6870
|
+
schema: 'dz-slop-lint/1', advisory: true, ok: errors.length === 0, status, findings, scanned, skipped, errors,
|
|
6871
|
+
};
|
|
6872
|
+
if (json) write(JSON.stringify(report));
|
|
6873
|
+
else {
|
|
6874
|
+
write(`dz lint: ${findings.length} finding(s), ${scanned.filter((row) => row.status === 'scanned').length} file(s) scanned — ${status}`);
|
|
6875
|
+
for (const finding of findings) write(` [${finding.ruleId}] ${finding.file}:${finding.lineStart}:${finding.columnStart} — ${finding.excerpt}`);
|
|
6876
|
+
for (const error of errors) write(` incomplete${error.path ? ` ${error.path}` : ''}: ${error.message}`);
|
|
6877
|
+
}
|
|
6878
|
+
return errors.length > 0 ? 1 : 0;
|
|
6879
|
+
}
|
|
6880
|
+
|
|
6481
6881
|
/**
|
|
6482
6882
|
* Exit-code contract for `dz claim-check` (named in the ADR, locked by tests):
|
|
6483
6883
|
* exit 0 when no finding at/above `failOn` exists; exit 1 only when one does.
|
|
@@ -7435,6 +7835,90 @@ function gatherReadmeCounts(root: string): { label: string; a: number; b: number
|
|
|
7435
7835
|
function gatherGuardFacts(op: string, root: string, text: string | undefined, storeCap: number): Record<string, unknown> {
|
|
7436
7836
|
const facts: Record<string, unknown> = { op };
|
|
7437
7837
|
if (op === 'publish') {
|
|
7838
|
+
// Advisory I/O: unreadable telemetry or fed state is absence of evidence, never a fabricated
|
|
7839
|
+
// stale finding and never a publish blocker.
|
|
7840
|
+
try {
|
|
7841
|
+
const routing = readRoutingTelemetry(root);
|
|
7842
|
+
facts['routingFreshness'] = { unfedRunIds: unfedRuns(routing.harvest.samples, routing.alreadyFed) };
|
|
7843
|
+
} catch { /* fail-open: routing-store-stale is SOFT and needs gathered evidence */ }
|
|
7844
|
+
// marketplace-parity: regenerate the two published showcase manifests from the LIVE registry,
|
|
7845
|
+
// but redirect every write to a unique temp root. Version is operator-owned, so pinning the
|
|
7846
|
+
// published value into generatePlugin makes the comparison composition-only by construction.
|
|
7847
|
+
try {
|
|
7848
|
+
const showcaseDir = join(root, '.claude-plugin');
|
|
7849
|
+
if (!existsSync(showcaseDir)) {
|
|
7850
|
+
facts['marketplaceParity'] = { applicable: false };
|
|
7851
|
+
} else {
|
|
7852
|
+
const pluginPath = join(showcaseDir, 'plugin.json');
|
|
7853
|
+
const marketplacePath = join(showcaseDir, 'marketplace.json');
|
|
7854
|
+
const hasPlugin = existsSync(pluginPath);
|
|
7855
|
+
const hasMarketplace = existsSync(marketplacePath);
|
|
7856
|
+
const manifestFailures: { file: 'plugin.json' | 'marketplace.json'; error: string }[] = [];
|
|
7857
|
+
const readManifest = (path: string, file: 'plugin.json' | 'marketplace.json'): unknown => {
|
|
7858
|
+
try {
|
|
7859
|
+
return JSON.parse(readFileSync(path, 'utf8')) as unknown;
|
|
7860
|
+
} catch (error) {
|
|
7861
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
7862
|
+
manifestFailures.push({ file, error: message.replace(/\s+/g, ' ').slice(0, 240) });
|
|
7863
|
+
return undefined;
|
|
7864
|
+
}
|
|
7865
|
+
};
|
|
7866
|
+
const versionOf = (manifest: unknown): string | undefined => {
|
|
7867
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) return undefined;
|
|
7868
|
+
const version = (manifest as Record<string, unknown>)['version'];
|
|
7869
|
+
return typeof version === 'string' && version !== '' ? version : undefined;
|
|
7870
|
+
};
|
|
7871
|
+
const publishedPlugin = hasPlugin ? readManifest(pluginPath, 'plugin.json') : undefined;
|
|
7872
|
+
const publishedMarketplace = hasMarketplace ? readManifest(marketplacePath, 'marketplace.json') : undefined;
|
|
7873
|
+
const marketplaceRecord = publishedMarketplace && typeof publishedMarketplace === 'object' && !Array.isArray(publishedMarketplace)
|
|
7874
|
+
? publishedMarketplace as Record<string, unknown>
|
|
7875
|
+
: undefined;
|
|
7876
|
+
const marketplacePlugins = marketplaceRecord !== undefined && Array.isArray(marketplaceRecord['plugins'])
|
|
7877
|
+
? marketplaceRecord['plugins']
|
|
7878
|
+
: [];
|
|
7879
|
+
const publishedVersion = versionOf(publishedPlugin)
|
|
7880
|
+
?? versionOf(publishedMarketplace)
|
|
7881
|
+
?? versionOf(marketplacePlugins[0]);
|
|
7882
|
+
if (manifestFailures.length > 0) {
|
|
7883
|
+
facts['marketplaceParity'] = {
|
|
7884
|
+
applicable: true,
|
|
7885
|
+
manifestFailures,
|
|
7886
|
+
...(publishedVersion !== undefined ? { publishedVersion } : {}),
|
|
7887
|
+
};
|
|
7888
|
+
} else if (hasPlugin !== hasMarketplace) {
|
|
7889
|
+
facts['marketplaceParity'] = {
|
|
7890
|
+
applicable: true,
|
|
7891
|
+
onlyOnePresent: true,
|
|
7892
|
+
...(publishedVersion !== undefined ? { publishedVersion } : {}),
|
|
7893
|
+
};
|
|
7894
|
+
} else if (!hasPlugin) {
|
|
7895
|
+
facts['marketplaceParity'] = { applicable: false };
|
|
7896
|
+
} else {
|
|
7897
|
+
let scratch: string | undefined;
|
|
7898
|
+
try {
|
|
7899
|
+
const registry = buildRegistry(root);
|
|
7900
|
+
scratch = mkdtempSync(join(tmpdir(), 'dz-guard-marketplace-'));
|
|
7901
|
+
const generated = generatePlugin(scratch, registry, { version: publishedVersion });
|
|
7902
|
+
const freshPlugin = JSON.parse(readFileSync(generated.pluginJsonPath, 'utf8')) as unknown;
|
|
7903
|
+
const freshMarketplace = JSON.parse(readFileSync(generated.marketplaceJsonPath, 'utf8')) as unknown;
|
|
7904
|
+
facts['marketplaceParity'] = {
|
|
7905
|
+
applicable: true,
|
|
7906
|
+
diverged: !isDeepStrictEqual(publishedPlugin, freshPlugin)
|
|
7907
|
+
|| !isDeepStrictEqual(publishedMarketplace, freshMarketplace),
|
|
7908
|
+
...(publishedVersion !== undefined ? { publishedVersion } : {}),
|
|
7909
|
+
};
|
|
7910
|
+
} catch {
|
|
7911
|
+
facts['marketplaceParity'] = {
|
|
7912
|
+
applicable: true,
|
|
7913
|
+
regenerateFailed: true,
|
|
7914
|
+
...(publishedVersion !== undefined ? { publishedVersion } : {}),
|
|
7915
|
+
};
|
|
7916
|
+
} finally {
|
|
7917
|
+
if (scratch !== undefined) rmSync(scratch, { recursive: true, force: true });
|
|
7918
|
+
}
|
|
7919
|
+
}
|
|
7920
|
+
}
|
|
7921
|
+
} catch { /* fail-open only on unexpected showcase-discovery failure; manifest read/parse errors are structured violations above */ }
|
|
7438
7922
|
// agents-md-policy-sync: fixed registry, no tree walk. The pure detector
|
|
7439
7923
|
// recomputes every expected hash from current source text; this gatherer
|
|
7440
7924
|
// only supplies bytes. Any unexpected gather failure omits the fact, and
|
|
@@ -11107,6 +11591,265 @@ function cmdFeatureAdrRecord(options: Map<string, string>, flags: Set<string>, c
|
|
|
11107
11591
|
return emit(decideReadBack(lineToWrite, lastLine), { target });
|
|
11108
11592
|
}
|
|
11109
11593
|
|
|
11594
|
+
type ContractDiskRead =
|
|
11595
|
+
| { readonly ok: true; readonly text: string; readonly realPath: string }
|
|
11596
|
+
| { readonly ok: false; readonly diagnostic: ContractDiagnostic };
|
|
11597
|
+
|
|
11598
|
+
type ContractDirectoryRead =
|
|
11599
|
+
| { readonly ok: true; readonly realPath: string }
|
|
11600
|
+
| { readonly ok: false; readonly diagnostic: ContractDiagnostic };
|
|
11601
|
+
|
|
11602
|
+
function contractRepoRoot(cwd: string): string {
|
|
11603
|
+
let root = cwd;
|
|
11604
|
+
try {
|
|
11605
|
+
root = execSync('git rev-parse --show-toplevel', {
|
|
11606
|
+
cwd,
|
|
11607
|
+
encoding: 'utf-8',
|
|
11608
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
11609
|
+
}).trim() || cwd;
|
|
11610
|
+
} catch { /* temporary repository fixtures intentionally use cwd as their root */ }
|
|
11611
|
+
return resolve(root);
|
|
11612
|
+
}
|
|
11613
|
+
|
|
11614
|
+
function contractReadConfined(repoRoot: string, absolute: string, artifact: string): ContractDiskRead {
|
|
11615
|
+
let rootReal: string;
|
|
11616
|
+
let targetReal: string;
|
|
11617
|
+
try {
|
|
11618
|
+
rootReal = realpathSync(repoRoot);
|
|
11619
|
+
} catch {
|
|
11620
|
+
return {
|
|
11621
|
+
ok: false,
|
|
11622
|
+
diagnostic: { code: 'repository-unreadable', message: 'repository root cannot be resolved', artifact: '.' },
|
|
11623
|
+
};
|
|
11624
|
+
}
|
|
11625
|
+
try {
|
|
11626
|
+
targetReal = realpathSync(absolute);
|
|
11627
|
+
} catch {
|
|
11628
|
+
return {
|
|
11629
|
+
ok: false,
|
|
11630
|
+
diagnostic: { code: 'artifact-unreadable', message: `required artifact cannot be resolved or read: ${artifact}`, artifact },
|
|
11631
|
+
};
|
|
11632
|
+
}
|
|
11633
|
+
const rel = relative(rootReal, targetReal);
|
|
11634
|
+
if (rel === '' || rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel)) {
|
|
11635
|
+
return {
|
|
11636
|
+
ok: false,
|
|
11637
|
+
diagnostic: { code: 'artifact-outside-repository', message: `artifact resolves outside the repository: ${artifact}`, artifact },
|
|
11638
|
+
};
|
|
11639
|
+
}
|
|
11640
|
+
try {
|
|
11641
|
+
if (!statSync(targetReal).isFile()) throw new Error('not a regular file');
|
|
11642
|
+
return { ok: true, text: readFileSync(targetReal, 'utf-8'), realPath: targetReal };
|
|
11643
|
+
} catch {
|
|
11644
|
+
return {
|
|
11645
|
+
ok: false,
|
|
11646
|
+
diagnostic: { code: 'artifact-unreadable', message: `required artifact cannot be read as a file: ${artifact}`, artifact },
|
|
11647
|
+
};
|
|
11648
|
+
}
|
|
11649
|
+
}
|
|
11650
|
+
|
|
11651
|
+
function contractDirectoryConfined(repoRoot: string, absolute: string, artifact: string): ContractDirectoryRead {
|
|
11652
|
+
let rootReal: string;
|
|
11653
|
+
let targetReal: string;
|
|
11654
|
+
try {
|
|
11655
|
+
rootReal = realpathSync(repoRoot);
|
|
11656
|
+
} catch {
|
|
11657
|
+
return {
|
|
11658
|
+
ok: false,
|
|
11659
|
+
diagnostic: { code: 'repository-unreadable', message: 'repository root cannot be resolved', artifact: '.' },
|
|
11660
|
+
};
|
|
11661
|
+
}
|
|
11662
|
+
try {
|
|
11663
|
+
targetReal = realpathSync(absolute);
|
|
11664
|
+
} catch {
|
|
11665
|
+
return {
|
|
11666
|
+
ok: false,
|
|
11667
|
+
diagnostic: { code: 'adr-directory-unreadable', message: `required ADR directory cannot be resolved: ${artifact}`, artifact },
|
|
11668
|
+
};
|
|
11669
|
+
}
|
|
11670
|
+
const rel = relative(rootReal, targetReal);
|
|
11671
|
+
if (rel === '' || rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel)) {
|
|
11672
|
+
return {
|
|
11673
|
+
ok: false,
|
|
11674
|
+
diagnostic: { code: 'artifact-outside-repository', message: `artifact resolves outside the repository: ${artifact}`, artifact },
|
|
11675
|
+
};
|
|
11676
|
+
}
|
|
11677
|
+
try {
|
|
11678
|
+
if (!statSync(targetReal).isDirectory()) throw new Error('not a directory');
|
|
11679
|
+
return { ok: true, realPath: targetReal };
|
|
11680
|
+
} catch {
|
|
11681
|
+
return {
|
|
11682
|
+
ok: false,
|
|
11683
|
+
diagnostic: { code: 'adr-directory-unreadable', message: `required ADR directory is not readable: ${artifact}`, artifact },
|
|
11684
|
+
};
|
|
11685
|
+
}
|
|
11686
|
+
}
|
|
11687
|
+
|
|
11688
|
+
function contractDiagnosticLine(entry: ContractDiagnostic): string {
|
|
11689
|
+
const where = [entry.artifact, entry.contractId ?? entry.sourceId].filter((part): part is string => part !== undefined).join(' · ');
|
|
11690
|
+
return ` [${entry.code}]${where === '' ? '' : ` ${where} —`} ${entry.message}`;
|
|
11691
|
+
}
|
|
11692
|
+
|
|
11693
|
+
function cmdContractCheck(
|
|
11694
|
+
options: Map<string, string>,
|
|
11695
|
+
flags: Set<string>,
|
|
11696
|
+
cwd: string,
|
|
11697
|
+
write: Write,
|
|
11698
|
+
writeErr: WriteErr,
|
|
11699
|
+
): number {
|
|
11700
|
+
const json = flags.has('json');
|
|
11701
|
+
const emitEarly = (outcome: 'fail' | 'not-established', exitCode: 1 | 2, diagnostics: readonly ContractDiagnostic[]): number => {
|
|
11702
|
+
if (json) {
|
|
11703
|
+
write(JSON.stringify({ outcome, exitCode, diagnostics }));
|
|
11704
|
+
} else {
|
|
11705
|
+
for (const entry of diagnostics) writeErr(contractDiagnosticLine(entry));
|
|
11706
|
+
write(`contract-check: ${outcome === 'fail' ? 'FAIL' : 'NOT-ESTABLISHED'} — ${diagnostics[0]?.message ?? 'no trustworthy verdict'}`);
|
|
11707
|
+
}
|
|
11708
|
+
return exitCode;
|
|
11709
|
+
};
|
|
11710
|
+
|
|
11711
|
+
for (const flag of flags) {
|
|
11712
|
+
if (flag !== 'json' && flag !== 'help') {
|
|
11713
|
+
return emitEarly('not-established', 2, [{ code: 'usage-invalid', message: `unknown option --${flag}`, observed: `--${flag}` }]);
|
|
11714
|
+
}
|
|
11715
|
+
}
|
|
11716
|
+
for (const key of options.keys()) {
|
|
11717
|
+
if (key !== 'slug') {
|
|
11718
|
+
return emitEarly('not-established', 2, [{
|
|
11719
|
+
code: 'usage-invalid',
|
|
11720
|
+
message: key.startsWith('_positional_') ? `unexpected argument ${JSON.stringify(options.get(key))}` : `unknown option --${key}`,
|
|
11721
|
+
observed: key.startsWith('_positional_') ? options.get(key) ?? '' : `--${key}`,
|
|
11722
|
+
}]);
|
|
11723
|
+
}
|
|
11724
|
+
}
|
|
11725
|
+
const slug = (options.get('slug') ?? '').trim();
|
|
11726
|
+
if (!isSafeSlug(slug)) {
|
|
11727
|
+
return emitEarly('not-established', 2, [{
|
|
11728
|
+
code: 'slug-invalid',
|
|
11729
|
+
message: 'a kebab-case --slug <feature> is required (one path segment, max 40 characters)',
|
|
11730
|
+
observed: slug,
|
|
11731
|
+
}]);
|
|
11732
|
+
}
|
|
11733
|
+
|
|
11734
|
+
const repoRoot = contractRepoRoot(cwd);
|
|
11735
|
+
const featureDir = join(repoRoot, 'features', slug);
|
|
11736
|
+
const requirementsRel = `features/${slug}/01_requirements.md`;
|
|
11737
|
+
const reportRel = `features/${slug}/08_qe_report.md`;
|
|
11738
|
+
const requirementsRead = contractReadConfined(repoRoot, join(featureDir, '01_requirements.md'), requirementsRel);
|
|
11739
|
+
if (!requirementsRead.ok) return emitEarly('not-established', 2, [requirementsRead.diagnostic]);
|
|
11740
|
+
|
|
11741
|
+
const adrDirRel = `features/${slug}/03_adr`;
|
|
11742
|
+
const adrDirectory = contractDirectoryConfined(repoRoot, join(featureDir, '03_adr'), adrDirRel);
|
|
11743
|
+
if (!adrDirectory.ok) return emitEarly('not-established', 2, [adrDirectory.diagnostic]);
|
|
11744
|
+
const adrDir = adrDirectory.realPath;
|
|
11745
|
+
let adrNames: string[];
|
|
11746
|
+
try {
|
|
11747
|
+
adrNames = readdirSync(adrDir, { withFileTypes: true })
|
|
11748
|
+
.filter((entry) => entry.name.endsWith('.md') && (entry.isFile() || entry.isSymbolicLink()))
|
|
11749
|
+
.map((entry) => entry.name)
|
|
11750
|
+
.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
11751
|
+
} catch {
|
|
11752
|
+
return emitEarly('not-established', 2, [{
|
|
11753
|
+
code: 'adr-directory-unreadable',
|
|
11754
|
+
message: `required ADR directory cannot be read: ${adrDirRel}`,
|
|
11755
|
+
artifact: adrDirRel,
|
|
11756
|
+
}]);
|
|
11757
|
+
}
|
|
11758
|
+
if (adrNames.length === 0) {
|
|
11759
|
+
return emitEarly('not-established', 2, [{
|
|
11760
|
+
code: 'adr-artifacts-missing',
|
|
11761
|
+
message: `no direct ADR Markdown artifacts exist under ${adrDirRel}`,
|
|
11762
|
+
artifact: adrDirRel,
|
|
11763
|
+
observed: 0,
|
|
11764
|
+
}]);
|
|
11765
|
+
}
|
|
11766
|
+
const adrs: Array<{ path: string; text: string }> = [];
|
|
11767
|
+
const adrReadErrors: ContractDiagnostic[] = [];
|
|
11768
|
+
for (const name of adrNames) {
|
|
11769
|
+
const rel = `features/${slug}/03_adr/${name}`;
|
|
11770
|
+
const read = contractReadConfined(repoRoot, join(adrDir, name), rel);
|
|
11771
|
+
if (read.ok) adrs.push({ path: rel, text: read.text });
|
|
11772
|
+
else adrReadErrors.push(read.diagnostic);
|
|
11773
|
+
}
|
|
11774
|
+
if (adrReadErrors.length > 0) return emitEarly('not-established', 2, adrReadErrors);
|
|
11775
|
+
|
|
11776
|
+
const extracted = extractContractChecklist({
|
|
11777
|
+
requirements: { path: requirementsRel, text: requirementsRead.text },
|
|
11778
|
+
adrs,
|
|
11779
|
+
});
|
|
11780
|
+
if (!extracted.ok) return emitEarly('fail', 1, extracted.diagnostics);
|
|
11781
|
+
|
|
11782
|
+
const reportRead = contractReadConfined(repoRoot, join(featureDir, '08_qe_report.md'), reportRel);
|
|
11783
|
+
if (!reportRead.ok) return emitEarly('not-established', 2, [reportRead.diagnostic]);
|
|
11784
|
+
|
|
11785
|
+
const parsed = parseContractVerdictReport(reportRead.text);
|
|
11786
|
+
if (!parsed.ok) {
|
|
11787
|
+
const diagnostics = parsed.diagnostics.map((entry) => ({
|
|
11788
|
+
...entry,
|
|
11789
|
+
artifact: entry.artifact ?? reportRel,
|
|
11790
|
+
}));
|
|
11791
|
+
return emitEarly(parsed.established ? 'fail' : 'not-established', parsed.established ? 1 : 2, diagnostics);
|
|
11792
|
+
}
|
|
11793
|
+
|
|
11794
|
+
const evidenceCache = new Map<string, ReturnType<ContractEvidenceReader['read']>>();
|
|
11795
|
+
const reader: ContractEvidenceReader = {
|
|
11796
|
+
reportArtifact: reportRel,
|
|
11797
|
+
read(artifact) {
|
|
11798
|
+
const cached = evidenceCache.get(artifact);
|
|
11799
|
+
if (cached !== undefined) return cached;
|
|
11800
|
+
const disk = contractReadConfined(repoRoot, join(repoRoot, artifact), artifact);
|
|
11801
|
+
let result: ReturnType<ContractEvidenceReader['read']>;
|
|
11802
|
+
if (!disk.ok) {
|
|
11803
|
+
result = { ok: false, code: `evidence-${disk.diagnostic.code}`, detail: disk.diagnostic.message };
|
|
11804
|
+
} else if (disk.realPath === reportRead.realPath) {
|
|
11805
|
+
result = { ok: false, code: 'evidence-self-citation', detail: `${artifact} resolves to the QE verdict payload itself` };
|
|
11806
|
+
} else {
|
|
11807
|
+
result = { ok: true, text: disk.text };
|
|
11808
|
+
}
|
|
11809
|
+
evidenceCache.set(artifact, result);
|
|
11810
|
+
return result;
|
|
11811
|
+
},
|
|
11812
|
+
};
|
|
11813
|
+
const rawVerification = verifyContractVerdicts(extracted.checklist, parsed.report, reader);
|
|
11814
|
+
const withReportArtifact = (entry: ContractDiagnostic): ContractDiagnostic => ({
|
|
11815
|
+
...entry,
|
|
11816
|
+
artifact: entry.artifact ?? reportRel,
|
|
11817
|
+
});
|
|
11818
|
+
const verification = {
|
|
11819
|
+
...rawVerification,
|
|
11820
|
+
diagnostics: rawVerification.diagnostics.map(withReportArtifact),
|
|
11821
|
+
items: rawVerification.items.map((item) => ({
|
|
11822
|
+
...item,
|
|
11823
|
+
diagnostics: item.diagnostics.map(withReportArtifact),
|
|
11824
|
+
})),
|
|
11825
|
+
};
|
|
11826
|
+
if (json) {
|
|
11827
|
+
write(JSON.stringify({
|
|
11828
|
+
contract: extracted.checklist,
|
|
11829
|
+
report: parsed.report,
|
|
11830
|
+
items: verification.items,
|
|
11831
|
+
diagnostics: verification.diagnostics,
|
|
11832
|
+
counts: verification.counts,
|
|
11833
|
+
overallGrade: verification.overallGrade,
|
|
11834
|
+
outcome: verification.outcome,
|
|
11835
|
+
exitCode: verification.exitCode,
|
|
11836
|
+
}));
|
|
11837
|
+
return verification.exitCode;
|
|
11838
|
+
}
|
|
11839
|
+
for (const item of verification.items) {
|
|
11840
|
+
const reason = item.reason === undefined ? '' : ` — ${item.reason}`;
|
|
11841
|
+
write(` ${item.id}: ${item.verdict ?? 'missing'} · evidence ${item.evidence}${reason}`);
|
|
11842
|
+
}
|
|
11843
|
+
write(` counts: contract=${verification.counts.contractItems} verdict=${verification.counts.verdictItems} met=${verification.counts.met} unmet=${verification.counts.unmet} not-testable=${verification.counts.notTestable} invalid-evidence=${verification.counts.invalidEvidence}`);
|
|
11844
|
+
write(` overall grade: ${verification.overallGrade}`);
|
|
11845
|
+
for (const entry of verification.diagnostics) writeErr(contractDiagnosticLine(entry));
|
|
11846
|
+
const summary = verification.outcome === 'pass'
|
|
11847
|
+
? `${verification.counts.met} contract item(s) met`
|
|
11848
|
+
: `${verification.diagnostics.length} contract or evidence violation(s)`;
|
|
11849
|
+
write(`contract-check: ${verification.outcome === 'pass' ? 'PASS' : 'FAIL'} — ${summary}`);
|
|
11850
|
+
return verification.exitCode;
|
|
11851
|
+
}
|
|
11852
|
+
|
|
11110
11853
|
function cmdAmendmentCheck(options: Map<string, string>, flags: Set<string>, cwd: string, write: Write): number {
|
|
11111
11854
|
const json = flags.has('json');
|
|
11112
11855
|
const readOr = (abs: string): string | null => {
|
|
@@ -12307,6 +13050,90 @@ function readRecallUsageEvents(
|
|
|
12307
13050
|
return usage;
|
|
12308
13051
|
}
|
|
12309
13052
|
|
|
13053
|
+
function readOptionalText(path: string): string {
|
|
13054
|
+
try {
|
|
13055
|
+
return readFileSync(path, 'utf8');
|
|
13056
|
+
} catch {
|
|
13057
|
+
return '';
|
|
13058
|
+
}
|
|
13059
|
+
}
|
|
13060
|
+
|
|
13061
|
+
function deadwoodAllowlistText(): string {
|
|
13062
|
+
const require = createRequire(import.meta.url);
|
|
13063
|
+
const corePackage = require.resolve('@dzhechkov/harness-core/package.json');
|
|
13064
|
+
return readFileSync(join(dirname(corePackage), 'src', 'deadwood-allowlist.json'), 'utf8');
|
|
13065
|
+
}
|
|
13066
|
+
|
|
13067
|
+
function cmdUsageDepthDays(root: string, now: Date): number | null {
|
|
13068
|
+
const text = readOptionalText(join(root, CMD_USAGE_LOG_RELATIVE));
|
|
13069
|
+
if (text === '') return null;
|
|
13070
|
+
return measureCmdUsageDepthDays(text, now);
|
|
13071
|
+
}
|
|
13072
|
+
|
|
13073
|
+
/** Canonical deadwood candidates keyed to every alternate top-level dispatch token. */
|
|
13074
|
+
const DEADWOOD_COMMAND_ALIASES: Readonly<Record<string, readonly string[]>> = {
|
|
13075
|
+
sync: ['update'],
|
|
13076
|
+
};
|
|
13077
|
+
|
|
13078
|
+
function deadwoodInventory(root: string): DeadwoodInventoryItem[] {
|
|
13079
|
+
const aliasTokens = new Set(Object.values(DEADWOOD_COMMAND_ALIASES).flat());
|
|
13080
|
+
const inventory: DeadwoodInventoryItem[] = DZ_COMMANDS
|
|
13081
|
+
.filter((surface) => !aliasTokens.has(surface))
|
|
13082
|
+
.map((surface) => ({
|
|
13083
|
+
surface,
|
|
13084
|
+
kind: 'command',
|
|
13085
|
+
...(DEADWOOD_COMMAND_ALIASES[surface] === undefined
|
|
13086
|
+
? {}
|
|
13087
|
+
: { aliases: DEADWOOD_COMMAND_ALIASES[surface] }),
|
|
13088
|
+
}));
|
|
13089
|
+
for (const rule of DEFAULT_RULES) inventory.push({ surface: rule.id, kind: 'rule' });
|
|
13090
|
+
const skillDir = resolve(root, '.claude/skills');
|
|
13091
|
+
const { skills } = listSkillsDetailed(skillDir);
|
|
13092
|
+
for (const skill of skills) inventory.push({ surface: skill.id, kind: 'skill' });
|
|
13093
|
+
return inventory;
|
|
13094
|
+
}
|
|
13095
|
+
|
|
13096
|
+
/** `dz deadwood` is a read-only advisory report; findings never affect the exit code. */
|
|
13097
|
+
function cmdDeadwood(
|
|
13098
|
+
options: Map<string, string>,
|
|
13099
|
+
flags: Set<string>,
|
|
13100
|
+
cwd: string,
|
|
13101
|
+
write: Write,
|
|
13102
|
+
writeErr: WriteErr,
|
|
13103
|
+
): number {
|
|
13104
|
+
if (flags.has('weeks')) {
|
|
13105
|
+
writeErr('dz deadwood: --weeks requires an integer value');
|
|
13106
|
+
return 1;
|
|
13107
|
+
}
|
|
13108
|
+
const rawWeeks = options.get('weeks') ?? '8';
|
|
13109
|
+
const weeks = Number(rawWeeks);
|
|
13110
|
+
if (!Number.isInteger(weeks) || weeks <= 0 || weeks > 520) {
|
|
13111
|
+
writeErr(`dz deadwood: --weeks must be an integer from 1 to 520 (received ${JSON.stringify(rawWeeks)})`);
|
|
13112
|
+
return 1;
|
|
13113
|
+
}
|
|
13114
|
+
const root = resolve(cwd);
|
|
13115
|
+
try {
|
|
13116
|
+
// Observe integrity before maintenance: compaction may discard malformed lines, but this run
|
|
13117
|
+
// still has to report that they existed rather than laundering the count to zero.
|
|
13118
|
+
const cmdUsageText = readOptionalText(join(resolveCmdUsageRoot(root), CMD_USAGE_LOG_RELATIVE));
|
|
13119
|
+
const report = buildDeadwoodReport({
|
|
13120
|
+
cmdUsageText,
|
|
13121
|
+
guardAuditText: readOptionalText(join(root, '.dz', 'guard-audit.jsonl')),
|
|
13122
|
+
inventory: deadwoodInventory(root),
|
|
13123
|
+
allowlistText: deadwoodAllowlistText(),
|
|
13124
|
+
weeks,
|
|
13125
|
+
now: new Date(),
|
|
13126
|
+
});
|
|
13127
|
+
compactCmdUsageIfNeeded(root);
|
|
13128
|
+
if (flags.has('json')) write(JSON.stringify({ ...report, exitCode: 0 }, null, 2));
|
|
13129
|
+
else write(renderDeadwoodReport(report, 'text'));
|
|
13130
|
+
return 0;
|
|
13131
|
+
} catch (error) {
|
|
13132
|
+
writeErr(`dz deadwood: ${error instanceof Error ? error.message : String(error)}`);
|
|
13133
|
+
return 1;
|
|
13134
|
+
}
|
|
13135
|
+
}
|
|
13136
|
+
|
|
12310
13137
|
/**
|
|
12311
13138
|
* `dz compounding` — does the learning loop actually PAY? (feature compounding, scout C2.)
|
|
12312
13139
|
* Gathers the facts (store rows, apply-leg usage log, guard audit) and hands them to the PURE
|
|
@@ -12383,7 +13210,15 @@ function cmdCompounding(options: Map<string, string>, flags: Set<string>, cwd: s
|
|
|
12383
13210
|
}
|
|
12384
13211
|
}
|
|
12385
13212
|
|
|
12386
|
-
const
|
|
13213
|
+
const now = new Date();
|
|
13214
|
+
const report = assembleCompoundingReport({
|
|
13215
|
+
lessons,
|
|
13216
|
+
usage,
|
|
13217
|
+
guard,
|
|
13218
|
+
nowTs: now.toISOString(),
|
|
13219
|
+
evidenceLogs,
|
|
13220
|
+
cmdUsageDepthDays: cmdUsageDepthDays(root, now),
|
|
13221
|
+
});
|
|
12387
13222
|
// lesson-bandit-rerank §11: the payoff axis joins THIS report rather than growing a private
|
|
12388
13223
|
// dashboard — the `rewardEvents : exposureEvents` row asks exactly the question this command
|
|
12389
13224
|
// already asks of the reinforcement loop (is the apply leg alive, or is it a write-only log?).
|
|
@@ -13523,6 +14358,34 @@ async function cmdBacklog(options: Map<string, string>, flags: Set<string>, cwd:
|
|
|
13523
14358
|
return sub === undefined ? 0 : 1;
|
|
13524
14359
|
}
|
|
13525
14360
|
|
|
14361
|
+
/** Read the recommender's existing telemetry planes plus its idempotency receipt. One adapter is
|
|
14362
|
+
* shared by `recommend` and the publish advisory so their freshness definitions cannot drift. */
|
|
14363
|
+
function readRoutingTelemetry(repoRoot: string): { harvest: ReturnType<typeof harvestStageOutcomes>; alreadyFed: string[] } {
|
|
14364
|
+
const records: unknown[] = readHarnessRecords(repoRoot);
|
|
14365
|
+
for (const base of [join(repoRoot, 'features'), join(repoRoot, '.dz', 'loop-trace')]) {
|
|
14366
|
+
if (!existsSync(base)) continue;
|
|
14367
|
+
let names: string[] = [];
|
|
14368
|
+
try { names = readdirSync(base); } catch { continue; }
|
|
14369
|
+
for (const name of names) {
|
|
14370
|
+
const sidecar = join(base, name, 'run-meta.json');
|
|
14371
|
+
if (!existsSync(sidecar)) continue;
|
|
14372
|
+
try {
|
|
14373
|
+
const meta = JSON.parse(readFileSync(sidecar, 'utf-8')) as { runMeta?: { resolved?: boolean; records?: unknown[] } };
|
|
14374
|
+
if (meta.runMeta?.resolved === true && Array.isArray(meta.runMeta.records)) records.push(...meta.runMeta.records);
|
|
14375
|
+
} catch { /* an unreadable sidecar contributes no asserted record */ }
|
|
14376
|
+
}
|
|
14377
|
+
}
|
|
14378
|
+
let alreadyFed: string[] = [];
|
|
14379
|
+
const fedPath = join(repoRoot, '.dz', 'routing-fed.json');
|
|
14380
|
+
if (existsSync(fedPath)) {
|
|
14381
|
+
const parsed = JSON.parse(readFileSync(join(repoRoot, '.dz', 'routing-fed.json'), 'utf-8')) as unknown;
|
|
14382
|
+
if (!Array.isArray(parsed)) throw new Error('.dz/routing-fed.json must be a JSON array of runIds');
|
|
14383
|
+
if (parsed.some((v) => typeof v !== 'string')) throw new Error('.dz/routing-fed.json contains a non-string runId');
|
|
14384
|
+
alreadyFed = parsed as string[];
|
|
14385
|
+
}
|
|
14386
|
+
return { harvest: harvestStageOutcomes(records), alreadyFed };
|
|
14387
|
+
}
|
|
14388
|
+
|
|
13526
14389
|
/**
|
|
13527
14390
|
* `dz routing` — inspect the learned cost-optimal routing outcome store (feature learned-cost-routing). Shows
|
|
13528
14391
|
* what `args.models[stage]='auto-cost'` currently believes per (stage, complexity-tier, model): gated
|
|
@@ -13537,28 +14400,20 @@ function cmdRouting(options: Map<string, string>, flags: Set<string>, cwd: strin
|
|
|
13537
14400
|
// ── recommend — harvest real telemetry, print per-stage picks WITH THE BASIS, optionally feed the
|
|
13538
14401
|
// store (a9c3dd5c fn 3, ADR-001). Sources: live harness records + imported run-meta.json sidecars.
|
|
13539
14402
|
if (options.get('_positional_0') === 'recommend') {
|
|
13540
|
-
|
|
13541
|
-
|
|
13542
|
-
|
|
13543
|
-
|
|
13544
|
-
|
|
13545
|
-
try { names = readdirSync(base); } catch { continue; }
|
|
13546
|
-
for (const name of names) {
|
|
13547
|
-
const sidecar = join(base, name, 'run-meta.json');
|
|
13548
|
-
if (!existsSync(sidecar)) continue;
|
|
13549
|
-
try {
|
|
13550
|
-
const meta = JSON.parse(readFileSync(sidecar, 'utf-8')) as { runMeta?: { resolved?: boolean; records?: unknown[] } };
|
|
13551
|
-
if (meta.runMeta?.resolved === true && Array.isArray(meta.runMeta.records)) records.push(...meta.runMeta.records);
|
|
13552
|
-
} catch { /* an unreadable sidecar contributes nothing — counted below as noResult */ }
|
|
13553
|
-
}
|
|
14403
|
+
let routing: ReturnType<typeof readRoutingTelemetry>;
|
|
14404
|
+
try { routing = readRoutingTelemetry(repoRoot); }
|
|
14405
|
+
catch (e) {
|
|
14406
|
+
write(`dz routing recommend: cannot read routing freshness state — ${(e as Error).message}`);
|
|
14407
|
+
return 1;
|
|
13554
14408
|
}
|
|
13555
|
-
const harvest =
|
|
13556
|
-
|
|
14409
|
+
const harvest = routing.harvest;
|
|
14410
|
+
let rec = recommendModels(harvest, {
|
|
14411
|
+
...(options.get('tier') !== undefined ? { tier: options.get('tier')! } : {}),
|
|
14412
|
+
alreadyFed: routing.alreadyFed,
|
|
14413
|
+
});
|
|
13557
14414
|
if (flags.has('apply')) {
|
|
13558
14415
|
const fedPath = join(repoRoot, '.dz', 'routing-fed.json');
|
|
13559
|
-
|
|
13560
|
-
try { alreadyFed = JSON.parse(readFileSync(fedPath, 'utf-8')) as string[]; } catch { /* first apply */ }
|
|
13561
|
-
const plan = planFeed(harvest.samples, alreadyFed);
|
|
14416
|
+
const plan = planFeed(harvest.samples, routing.alreadyFed);
|
|
13562
14417
|
for (const sample of plan.toFeed) finalizeOutcome(repoRoot, sample.stage, sample.tier, sample.model, sample.success);
|
|
13563
14418
|
try {
|
|
13564
14419
|
mkdirSync(join(repoRoot, '.dz'), { recursive: true });
|
|
@@ -13567,6 +14422,10 @@ function cmdRouting(options: Map<string, string>, flags: Set<string>, cwd: strin
|
|
|
13567
14422
|
write(`dz routing recommend: fed ${plan.toFeed.length} sample(s) but could NOT persist the fed-set — a re-apply WILL double-count: ${(e as Error).message}`);
|
|
13568
14423
|
return 1;
|
|
13569
14424
|
}
|
|
14425
|
+
rec = recommendModels(harvest, {
|
|
14426
|
+
...(options.get('tier') !== undefined ? { tier: options.get('tier')! } : {}),
|
|
14427
|
+
alreadyFed: plan.fedAfter,
|
|
14428
|
+
});
|
|
13570
14429
|
write(`dz routing recommend --apply: fed ${plan.toFeed.length} sample(s) into .dz/routing-outcomes.json${plan.skippedRuns.length > 0 ? `; skipped ${plan.skippedRuns.length} already-fed run(s) (idempotent by runId)` : ''}`);
|
|
13571
14430
|
}
|
|
13572
14431
|
if (flags.has('json')) {
|
|
@@ -13578,6 +14437,9 @@ function cmdRouting(options: Map<string, string>, flags: Set<string>, cwd: strin
|
|
|
13578
14437
|
write(` ${s.stage.padEnd(14)} ${s.spec.padEnd(20)} ${s.insufficientData ? '[insufficient data — cold-start pick]' : '[quality bar met]'} ${s.pick.evidence}`);
|
|
13579
14438
|
}
|
|
13580
14439
|
write(` basis: ${rec.basis.rule}`);
|
|
14440
|
+
if (rec.basis.freshness === 'current') write(' store: current (0 unharvested runs)');
|
|
14441
|
+
else if (rec.basis.freshness === 'stale') write(` store: STALE — ${rec.basis.unfed.count} run(s) harvested but never fed; auto-cost is routing from an older snapshot — run \`dz routing recommend --apply\``);
|
|
14442
|
+
else write(' store: UNFED — auto-cost has no learned rows; picks below are cold-start');
|
|
13581
14443
|
write(` basis: skipped records — no result ${rec.basis.skipped.noResult}, no modelsUsed ${rec.basis.skipped.noModels} (predates model routing — history, not an error), no grade ${rec.basis.skipped.noGrade}, unknown model ${rec.basis.skipped.unknownModel}`);
|
|
13582
14444
|
write(` basis: ${rec.basis.crossFamilyNote}`);
|
|
13583
14445
|
return 0;
|
|
@@ -14175,8 +15037,10 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
14175
15037
|
// reads appear nowhere in help, and static extraction over the dispatch table lost `--week` from
|
|
14176
15038
|
// `dz recap` — a refusal built on either list would reject working commands, which is a worse
|
|
14177
15039
|
// failure than the one being fixed. Goes to STDERR so a `--json` consumer's stdout stays clean.
|
|
14178
|
-
|
|
14179
|
-
|
|
15040
|
+
if (command !== 'contract-check') {
|
|
15041
|
+
for (const notice of unknownFlagNotice([...flags, ...options.keys()].filter((k) => !k.startsWith('_positional_')), KNOWN_CLI_FLAGS)) {
|
|
15042
|
+
writeErr(notice.line);
|
|
15043
|
+
}
|
|
14180
15044
|
}
|
|
14181
15045
|
|
|
14182
15046
|
// ── `dz --version` / `dz -v` / `dz version` — PRE-DISPATCH, before the help branch ──
|
|
@@ -14204,6 +15068,14 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
14204
15068
|
return 0;
|
|
14205
15069
|
}
|
|
14206
15070
|
|
|
15071
|
+
// Only registered command identifiers are telemetry. An unknown first argv token may be a path,
|
|
15072
|
+
// typo, or secret-like value; persisting it would violate the command-name-only privacy boundary.
|
|
15073
|
+
// `contract-check` has an explicit byte-for-byte read-only contract: even the advisory command
|
|
15074
|
+
// usage ledger would mutate the repository being audited and invalidate its own safety proof.
|
|
15075
|
+
if (command !== 'contract-check') {
|
|
15076
|
+
recordCommandInvocation(cwd, DZ_COMMANDS.includes(command) ? command : '', new Date());
|
|
15077
|
+
}
|
|
15078
|
+
|
|
14207
15079
|
try {
|
|
14208
15080
|
switch (command) {
|
|
14209
15081
|
case 'init':
|
|
@@ -14253,6 +15125,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
14253
15125
|
return cmdUsage(options, optionLists, flags, cwd, write);
|
|
14254
15126
|
case 'claim-check':
|
|
14255
15127
|
return cmdClaimCheck(options, optionLists, flags, cwd, write);
|
|
15128
|
+
case 'lint':
|
|
15129
|
+
return cmdLint(options, flags, cwd, write);
|
|
14256
15130
|
case 'sign':
|
|
14257
15131
|
return cmdSign(options, flags, cwd, write);
|
|
14258
15132
|
case 'sbom':
|
|
@@ -14325,6 +15199,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
14325
15199
|
return cmdSkillsVerify(options, flags, cwd, write);
|
|
14326
15200
|
case 'compounding':
|
|
14327
15201
|
return cmdCompounding(options, flags, cwd, write);
|
|
15202
|
+
case 'deadwood':
|
|
15203
|
+
return cmdDeadwood(options, flags, cwd, write, writeErr);
|
|
14328
15204
|
case 'epoch-replay':
|
|
14329
15205
|
return cmdEpochReplay(options, flags, cwd, write);
|
|
14330
15206
|
case 'score':
|
|
@@ -14335,6 +15211,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
14335
15211
|
return cmdCadence(options, flags, cwd, write);
|
|
14336
15212
|
case 'qe-rounds':
|
|
14337
15213
|
return cmdQeRounds(options, flags, cwd, write);
|
|
15214
|
+
case 'restart-advisor':
|
|
15215
|
+
return cmdRestartAdvisor(options, flags, cwd, write);
|
|
14338
15216
|
case 'tg-post':
|
|
14339
15217
|
return cmdTgPost(options, flags, cwd, write);
|
|
14340
15218
|
case 'name-check':
|
|
@@ -14345,6 +15223,8 @@ export async function runCli(argv: string[], io: CliIo = {}): Promise<number> {
|
|
|
14345
15223
|
return cmdFeatureAdrRecord(options, flags, cwd, write);
|
|
14346
15224
|
case 'amendment-check':
|
|
14347
15225
|
return cmdAmendmentCheck(options, flags, cwd, write);
|
|
15226
|
+
case 'contract-check':
|
|
15227
|
+
return cmdContractCheck(options, flags, cwd, write, writeErr);
|
|
14348
15228
|
case 'feature-adr-checkpoint':
|
|
14349
15229
|
return cmdFeatureAdrCheckpoint(options, flags, cwd, write);
|
|
14350
15230
|
case 'profile':
|