etymd 0.13.0 → 0.15.0

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +30 -19
  3. package/dist/{approve-YUT43YLC.js → approve-MA4Z3TBT.js} +5 -5
  4. package/dist/audit-YSALDC2L.js +11 -0
  5. package/dist/{brief-Z5S6OY2M.js → brief-DPZYSAMC.js} +5 -5
  6. package/dist/{chunk-PXRLOEN5.js → chunk-2RNQ6OLV.js} +146 -717
  7. package/dist/{chunk-DSAQ5S5D.js → chunk-CEO3BXQB.js} +3 -2
  8. package/dist/{chunk-D3R74TJ2.js → chunk-DBWDMIYO.js} +1 -1
  9. package/dist/{chunk-5BVKFJWM.js → chunk-HI7NWPRA.js} +79 -4
  10. package/dist/{chunk-2VLNI3L2.js → chunk-HOR4M6EC.js} +1 -1
  11. package/dist/chunk-IWG77WV3.js +758 -0
  12. package/dist/{chunk-DWL2IKZH.js → chunk-P6ATKV2R.js} +65 -3
  13. package/dist/{chunk-HRJJQCMT.js → chunk-UFNETE6P.js} +69 -20
  14. package/dist/{chunk-YXOAPMQH.js → chunk-Y6RZRED3.js} +2 -2
  15. package/dist/{chunk-LSZGCKIQ.js → chunk-YQZDYDAK.js} +1 -1
  16. package/dist/cli.js +42 -21
  17. package/dist/{config-XAH6PA5G.js → config-724Y3IOB.js} +1 -2
  18. package/dist/{context-F63RSIBH.js → context-JGKU4M7Z.js} +2 -4
  19. package/dist/doctor-Y3DWDEBT.js +18 -0
  20. package/dist/{fleet-YQ35KGEP.js → fleet-4FYZ3GBK.js} +11 -12
  21. package/dist/{gates-DU6SDH2M.js → gates-IBQ7HCAN.js} +6 -7
  22. package/dist/generate-KEX75XNG.js +5 -0
  23. package/dist/index.d.ts +173 -2
  24. package/dist/index.js +713 -198
  25. package/dist/{init-XJEYU2HC.js → init-H57H2JBE.js} +14 -13
  26. package/dist/ledger-T54JDHGP.js +6 -0
  27. package/dist/premise-VMC3UUIB.js +333 -0
  28. package/dist/scan-W4US23MU.js +5 -0
  29. package/dist/{scan-B24RZAV2.js → scan-XBOHDXAH.js} +5 -5
  30. package/dist/{screen-CS6PSG7U.js → screen-E4FC7W5N.js} +2 -1
  31. package/package.json +2 -2
  32. package/dist/audit-YRT4SWSQ.js +0 -12
  33. package/dist/chunk-F75Q43BC.js +0 -59
  34. package/dist/chunk-JHZ2BN4U.js +0 -67
  35. package/dist/doctor-7YKDXSKM.js +0 -19
  36. package/dist/generate-PMCP37DC.js +0 -6
  37. package/dist/ledger-4FOZ5HAB.js +0 -5
  38. package/dist/scan-QDNN7ER3.js +0 -5
@@ -1,31 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { measureContext } from './chunk-F75Q43BC.js';
2
+ import { stateFreshnessLens, rankFindings, listInstructionFiles, buildTruthEnv, emptyCounters, packageManagerUsage, checkDocRefs, listStateDocuments, loadDecisionLedger, checkDecisionRefs, checkTextClaims } from './chunk-IWG77WV3.js';
3
3
  import { readLedger, reconcileLedger, writeLedger, visibleFindings } from './chunk-3E2IPCRY.js';
4
- import { DEFAULT_CONFIG, readConfig, CONFIG_FILE } from './chunk-DWL2IKZH.js';
5
- import { scanProject, expandFileGlobs } from './chunk-YXOAPMQH.js';
6
- import { ETYMD_DIR, writeCachedFacts, readBaseline, deriveProfile, baselineCarriesMachinePath, BASELINE_FILE } from './chunk-JHZ2BN4U.js';
7
- import { PACK_VERSION } from './chunk-LSZGCKIQ.js';
8
- import { pathExists, readJson, readText, isDirectory, matchesAnyGlob, git, normalizeRelPath, isCiEnvironment, isExecutable } from './chunk-4VPBP6K6.js';
4
+ import { measureContext, contextFileLabel } from './chunk-HI7NWPRA.js';
5
+ import { scanProject } from './chunk-Y6RZRED3.js';
6
+ import { DEFAULT_CONFIG, ETYMD_DIR, writeCachedFacts, readBaseline, readConfig, deriveProfile, baselineCarriesMachinePath, BASELINE_FILE, CONFIG_FILE } from './chunk-P6ATKV2R.js';
7
+ import { PACK_VERSION } from './chunk-YQZDYDAK.js';
8
+ import { pathExists, readText, readJson, isCiEnvironment, isExecutable } from './chunk-4VPBP6K6.js';
9
9
  import path from 'path';
10
10
  import YAML from 'yaml';
11
- import { promises } from 'fs';
12
-
13
- // src/engine/finding.ts
14
- var TIER_ORDER = { risk: 0, gap: 1, polish: 2 };
15
- var EFFORT_ORDER = { S: 0, M: 1, L: 2 };
16
- function parseFailOnTier(value) {
17
- if (value === "risk" || value === "gap" || value === "polish") return value;
18
- throw new Error(`--fail-on must be risk|gap|polish, got \`${value}\``);
19
- }
20
- function meetsFailOn(findings, failOn) {
21
- const threshold = TIER_ORDER[failOn];
22
- return findings.some((f) => TIER_ORDER[f.tier] <= threshold);
23
- }
24
- function rankFindings(findings) {
25
- return [...findings].sort(
26
- (a, b) => TIER_ORDER[a.tier] - TIER_ORDER[b.tier] || EFFORT_ORDER[a.effort] - EFFORT_ORDER[b.effort]
27
- );
28
- }
11
+ import { execFile } from 'child_process';
12
+ import { promisify } from 'util';
29
13
 
30
14
  // src/lenses/context-economy.ts
31
15
  var LENS_ID = "context-economy";
@@ -39,13 +23,15 @@ var contextEconomyLens = {
39
23
  const budgets = ctx.config?.config.context ?? DEFAULT_CONFIG.context;
40
24
  const budget = await measureContext(ctx.root, budgets.perFileWords);
41
25
  const findings = [];
26
+ const aliased = budget.files.filter((f) => f.aliases?.length);
42
27
  for (const f of budget.extractionCandidates) {
28
+ const label = contextFileLabel(f);
43
29
  findings.push({
44
30
  id: `${LENS_ID}/heavy-file:${f.path}`,
45
31
  lens: LENS_ID,
46
32
  tier: "gap",
47
- claim: `${f.path} loads ${f.words} words (~${f.approxTokens} tokens) into every session`,
48
- evidence: [`${f.path}: ${f.words} words`],
33
+ claim: `${label} loads ${f.words} words (~${f.approxTokens} tokens) into every session`,
34
+ evidence: [`${label}: ${f.words} words`],
49
35
  why: "Reference material that loads every session taxes attention and cost on tasks that never need it.",
50
36
  action: "Extract the reference bulk into an on-demand skill/doc and keep a pointer.",
51
37
  effort: "M",
@@ -58,7 +44,7 @@ var contextEconomyLens = {
58
44
  lens: LENS_ID,
59
45
  tier: "gap",
60
46
  claim: `The always-loaded footprint is ${budget.totalWords} words (~${budget.totalApproxTokens} tokens) \u2014 over the ${budgets.totalWords}-word budget`,
61
- evidence: budget.files.slice(0, 5).map((f) => `${f.path}: ${f.words}w`),
47
+ evidence: budget.files.slice(0, 5).map((f) => `${contextFileLabel(f)}: ${f.words}w`),
62
48
  why: "Every session pays this before the task begins; instruction-following degrades as the resident context grows.",
63
49
  action: "Run `etymd context` for the per-file breakdown and extract the heaviest block.",
64
50
  effort: "M",
@@ -73,6 +59,9 @@ var contextEconomyLens = {
73
59
  status: "ran",
74
60
  disclosures: [
75
61
  ...ctx.config?.problems ?? [],
62
+ ...aliased.map(
63
+ (f) => `${contextFileLabel(f)} are one file (same inode) \u2014 counted once, at ${f.words} words.`
64
+ ),
76
65
  `Budgets: ${budgets.perFileWords} words/file, ${budgets.totalWords} words total (${budgets.perFileWords === DEFAULT_CONFIG.context.perFileWords && budgets.totalWords === DEFAULT_CONFIG.context.totalWords ? `defaults \u2014 override under \`context\` in ${CONFIG_FILE}` : `set in ${CONFIG_FILE}`}). Scoped Cursor rules excluded.`
77
66
  ],
78
67
  findings
@@ -473,6 +462,70 @@ async function buildGateInventory(root, facts) {
473
462
  commitlintDep
474
463
  };
475
464
  }
465
+ var pExecFile = promisify(execFile);
466
+ var HOOK_FILES = ["pre-commit", "pre-push", "commit-msg"];
467
+ var SCREEN_CALL_RE = /"\$GATE"\s+screen\b/;
468
+ var DEV_BUILD_ARM = "[ -x ./dist/cli.js ]";
469
+ async function probeScreener(root, facts) {
470
+ const absent = {
471
+ present: false,
472
+ doors: [],
473
+ runner: null,
474
+ source: null,
475
+ answersScreen: null
476
+ };
477
+ const dir = facts.hooks.dir;
478
+ if (!dir) return absent;
479
+ const doors = [];
480
+ let devBuildArm = false;
481
+ for (const name of HOOK_FILES) {
482
+ const text = await readText(path.join(root, dir, name));
483
+ if (!text || !SCREEN_CALL_RE.test(text)) continue;
484
+ doors.push(`${dir}/${name}`);
485
+ if (text.includes(DEV_BUILD_ARM)) devBuildArm = true;
486
+ }
487
+ if (!doors.length) return absent;
488
+ let runner = null;
489
+ let source = null;
490
+ const override = process.env.CONTENT_GATE;
491
+ if (override) {
492
+ runner = override;
493
+ source = "CONTENT_GATE";
494
+ } else if (devBuildArm && await pathExists(path.join(root, "dist", "cli.js"))) {
495
+ runner = path.join(root, "dist", "cli.js");
496
+ source = "dev-build";
497
+ } else {
498
+ runner = "etymd";
499
+ source = "path";
500
+ }
501
+ try {
502
+ await pExecFile(runner, ["screen", "--help"], { cwd: root, timeout: 1e4 });
503
+ return { present: true, doors, runner, source, answersScreen: true };
504
+ } catch (err) {
505
+ const e = err;
506
+ if (e.code === "ENOENT") {
507
+ return {
508
+ present: true,
509
+ doors,
510
+ runner: null,
511
+ source,
512
+ answersScreen: null,
513
+ skipped: `no checker named \`${runner}\` is installed \u2014 the screen doors no-op here by design, and nothing was verified.`
514
+ };
515
+ }
516
+ if (e.killed || e.code === "ETIMEDOUT") {
517
+ return {
518
+ present: true,
519
+ doors,
520
+ runner,
521
+ source,
522
+ answersScreen: null,
523
+ skipped: `\`${runner} screen --help\` did not return within 10s \u2014 the runner was not verified either way.`
524
+ };
525
+ }
526
+ return { present: true, doors, runner, source, answersScreen: false };
527
+ }
528
+ }
476
529
 
477
530
  // src/lenses/gate-integrity/lens.ts
478
531
  var LENS_ID2 = "gate-integrity";
@@ -616,6 +669,28 @@ function deriveGateFindings(inv, disclosures = []) {
616
669
  function localToolInHook(inv, tool) {
617
670
  return inv.local.preCommit.includes(tool) || inv.local.prePush.includes(tool) || inv.local.commitMsg.includes(tool);
618
671
  }
672
+ function deriveScreenerFindings(probe, disclosures) {
673
+ if (!probe.present) return [];
674
+ if (probe.skipped) {
675
+ disclosures.push(`Content screen: ${probe.skipped}`);
676
+ return [];
677
+ }
678
+ if (probe.answersScreen !== false) return [];
679
+ const via = probe.source === "CONTENT_GATE" ? "resolved from the CONTENT_GATE override" : probe.source === "dev-build" ? "resolved to this repo's own ./dist/cli.js build" : "resolved from PATH";
680
+ return [
681
+ finding({
682
+ id: `${LENS_ID2}/content-screen-unrunnable`,
683
+ tier: "risk",
684
+ kind: "truth",
685
+ claim: `The content screen resolves to \`${probe.runner}\`, which does not understand \`screen\` \u2014 the gate cannot run`,
686
+ evidence: [...probe.doors, `${probe.runner} screen --help \u2192 failed (${via})`],
687
+ why: "The commit door fails closed on an error that explains nothing, and the push door \u2014 advisory by design \u2014 skips the whole-tree pass in silence, so the repo reads as screened when nothing screened it.",
688
+ action: "Install or upgrade etymd (`screen` needs 0.11+), or point CONTENT_GATE at a checker that provides it, then re-run `etymd gates` to refresh the hooks.",
689
+ effort: "S",
690
+ confidence: "high"
691
+ })
692
+ ];
693
+ }
619
694
  var gateIntegrityLens = {
620
695
  id: LENS_ID2,
621
696
  version: "1",
@@ -656,6 +731,7 @@ var gateIntegrityLens = {
656
731
  if (inv.ci.system === "none")
657
732
  disclosures.push("No CI configuration found \u2014 CI\u2194local comparisons skipped.");
658
733
  const findings = deriveGateFindings(inv, disclosures);
734
+ findings.push(...deriveScreenerFindings(await probeScreener(ctx.root, ctx.facts), disclosures));
659
735
  return {
660
736
  lens: LENS_ID2,
661
737
  version: "1",
@@ -667,534 +743,12 @@ var gateIntegrityLens = {
667
743
  };
668
744
  }
669
745
  };
670
- var LENS_ID3 = "state-freshness";
671
- var DECISIONS_FORMAT_MARKER = "<!-- decisions-format: 1 -->";
672
- var KNOWN_FORMAT_VERSION = 1;
673
- var MARKER_RE = /<!--\s*decisions-format:\s*(\d+)([^>]*?)-->/;
674
- var FIELD_NAME_RE = /^[A-Za-z0-9 _-]+$/;
675
- var BUILT_IN_FIELDS = /* @__PURE__ */ new Set(["scope"]);
676
- var MS_PER_DAY = 864e5;
677
- function parseDecisionsFormat(text) {
678
- const m = MARKER_RE.exec(text);
679
- if (!m) return null;
680
- const problems = [];
681
- const fields = [];
682
- const offset = m.index ?? 0;
683
- const version = Number(m[1]);
684
- if (version !== KNOWN_FORMAT_VERSION) {
685
- problems.push(
686
- `declares decisions-format version ${version}; this etymd understands version ${KNOWN_FORMAT_VERSION} \u2014 checked as version ${KNOWN_FORMAT_VERSION}.`
687
- );
688
- }
689
- const attrs = (m[2] ?? "").trim();
690
- if (!attrs) return { fields, offset, problems };
691
- const declared = /^fields=(.*)$/.exec(attrs);
692
- if (!declared) {
693
- problems.push(`marker attribute \`${attrs}\` is not understood \u2014 ignored (only \`fields=\`).`);
694
- return { fields, offset, problems };
695
- }
696
- const seen = new Set(BUILT_IN_FIELDS);
697
- for (const raw of declared[1].split(",")) {
698
- const name = raw.trim();
699
- if (!name) continue;
700
- if (!FIELD_NAME_RE.test(name)) {
701
- problems.push(
702
- `declared field \`${name}\` is not a usable field name (letters, digits, spaces, \`-\`, \`_\`) \u2014 not checked.`
703
- );
704
- continue;
705
- }
706
- const key = name.toLowerCase();
707
- if (seen.has(key)) continue;
708
- seen.add(key);
709
- fields.push(name);
710
- }
711
- if (fields.length === 0 && problems.length === 0) {
712
- problems.push("marker declares `fields=` with no field names \u2014 no extra fields checked.");
713
- }
714
- return { fields, offset, problems };
715
- }
716
- function hasField(block, name) {
717
- return new RegExp(`${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s*]*:`).test(block);
718
- }
719
- function parseDecisionEntries(text) {
720
- const headings = [...text.matchAll(/^## .*$/gm)];
721
- const entries = [];
722
- for (let i = 0; i < headings.length; i++) {
723
- const h = headings[i];
724
- const m = /^## (D-(\d+))\b/.exec(h[0]);
725
- if (!m) continue;
726
- const offset = h.index ?? 0;
727
- const start = offset + h[0].length;
728
- const end = i + 1 < headings.length ? headings[i + 1].index : void 0;
729
- entries.push({ id: m[1], num: Number(m[2]), block: text.slice(start, end), offset });
730
- }
731
- return entries;
732
- }
733
- function checkIdSequence(file, entries) {
734
- const findings = [];
735
- const nextFree = Math.max(0, ...entries.map((e) => e.num)) + 1;
736
- const seen = /* @__PURE__ */ new Map();
737
- const duplicated = /* @__PURE__ */ new Set();
738
- let prev;
739
- for (const entry of entries) {
740
- if (seen.has(entry.num)) {
741
- if (!duplicated.has(entry.num)) {
742
- duplicated.add(entry.num);
743
- findings.push({
744
- id: `${LENS_ID3}/duplicate-id:${file}:${entry.id}`,
745
- lens: LENS_ID3,
746
- tier: "gap",
747
- claim: `${file} carries more than one ${entry.id} entry`,
748
- evidence: [`${file}: ${entry.id} appears twice`],
749
- why: "Two decisions under one id cannot be cited, superseded, or dismissed unambiguously \u2014 append races collide exactly here.",
750
- action: `Rename the later entry to D-${String(nextFree).padStart(3, "0")} (the next free id).`,
751
- effort: "S",
752
- confidence: "high"
753
- });
754
- }
755
- } else {
756
- seen.set(entry.num, entry);
757
- if (prev && entry.num < prev.num) {
758
- findings.push({
759
- id: `${LENS_ID3}/id-order:${file}:${entry.id}`,
760
- lens: LENS_ID3,
761
- tier: "gap",
762
- claim: `${file} lists ${entry.id} after ${prev.id} \u2014 ids out of append order`,
763
- evidence: [`${file}: ${prev.id} precedes ${entry.id}`],
764
- why: "An append-only record reads in id order; out-of-order ids make the newest decision hard to find and the next id hard to pick.",
765
- action: `Rename the out-of-order entry into sequence (next free id: D-${String(nextFree).padStart(3, "0")}).`,
766
- effort: "S",
767
- confidence: "high"
768
- });
769
- }
770
- prev = entry;
771
- }
772
- }
773
- return findings;
774
- }
775
- function checkFormatFields(file, entries, today, declaredFields, markerOffset) {
776
- const findings = [];
777
- for (const entry of entries) {
778
- const bound = entry.offset >= markerOffset;
779
- for (const field of bound ? declaredFields : []) {
780
- if (hasField(entry.block, field)) continue;
781
- findings.push({
782
- id: `${LENS_ID3}/field-missing:${file}:${entry.id}:${field}`,
783
- lens: LENS_ID3,
784
- tier: "gap",
785
- claim: `${file} ${entry.id} has no ${field}: field`,
786
- evidence: [`${file}: ${entry.id}`, `${file} marker declares required field \`${field}\``],
787
- why: "The file declares this field required on every entry after the marker; whatever reads the record for it finds nothing here.",
788
- action: `Add a ${field}: line to ${entry.id}.`,
789
- effort: "S",
790
- confidence: "high"
791
- });
792
- }
793
- if (bound && !/Scope[\s*]*:/.test(entry.block)) {
794
- findings.push({
795
- id: `${LENS_ID3}/scope-missing:${file}:${entry.id}`,
796
- lens: LENS_ID3,
797
- tier: "gap",
798
- claim: `${file} ${entry.id} has no Scope: field`,
799
- evidence: [`${file}: ${entry.id}`],
800
- why: "A decision without a scope binds nobody \u2014 a reader cannot tell whether it covers the project they are working in.",
801
- action: "Add a Scope: line naming what the decision binds.",
802
- effort: "S",
803
- confidence: "high"
804
- });
805
- }
806
- const revisit = /Revisit[\s*]*:[\s*]*(\d{4}-\d{2}-\d{2})/.exec(entry.block);
807
- if (revisit && revisit[1] < today) {
808
- findings.push({
809
- id: `${LENS_ID3}/revisit-due:${file}:${entry.id}`,
810
- lens: LENS_ID3,
811
- tier: "gap",
812
- claim: `${file} ${entry.id} was due for revisit on ${revisit[1]}`,
813
- evidence: [`${file}: ${entry.id} Revisit: ${revisit[1]}`],
814
- why: "Review debt is due \u2014 a Revisit date is a promise to re-evaluate, and a past one silently hardens into policy.",
815
- action: "Re-evaluate the decision: supersede it or move the Revisit date.",
816
- effort: "S",
817
- confidence: "high"
818
- });
819
- }
820
- }
821
- return findings;
822
- }
823
- var stateFreshnessLens = {
824
- id: LENS_ID3,
825
- version: "1",
826
- title: "State freshness",
827
- kind: "truth",
828
- async run(ctx) {
829
- const budgets = ctx.config?.config.state ?? DEFAULT_CONFIG.state;
830
- const findings = [];
831
- const disclosures = [...ctx.config?.problems ?? []];
832
- const outOfScope = [];
833
- const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
834
- const stateArtifacts = ctx.facts.artifacts.filter((a) => a.kind === "state" && a.exists);
835
- const decisionArtifacts = ctx.facts.artifacts.filter((a) => a.kind === "decisions" && a.exists);
836
- if (stateArtifacts.length === 0 && decisionArtifacts.length === 0) {
837
- disclosures.push("No state or decisions artifacts detected \u2014 nothing to check.");
838
- }
839
- const freshness = ctx.facts.freshness;
840
- if (!freshness) {
841
- disclosures.push("Scan carried no freshness facts \u2014 staleness unchecked.");
842
- } else {
843
- for (const u of freshness.unverifiable) {
844
- disclosures.push(`Freshness of ${u.path} is unverifiable (${u.reason}) \u2014 not flagged.`);
845
- }
846
- for (const a of stateArtifacts) {
847
- const fact = freshness.artifacts.find((f) => f.artifactId === a.id);
848
- if (!fact || !freshness.repoLastCommit) continue;
849
- if (fact.dirty) {
850
- disclosures.push(
851
- `${a.path} has uncommitted changes \u2014 modified since its last commit; treated fresh-now, not flagged.`
852
- );
853
- continue;
854
- }
855
- if (!fact.commitsSince) continue;
856
- const gapDays = Math.floor(
857
- (Date.parse(freshness.repoLastCommit) - Date.parse(fact.lastCommit)) / MS_PER_DAY
858
- );
859
- if (gapDays <= budgets.staleAfterDays) continue;
860
- const escalated = gapDays > budgets.staleAfterDays * 3;
861
- findings.push({
862
- id: `${LENS_ID3}/stale-state:${a.path}`,
863
- lens: LENS_ID3,
864
- tier: escalated ? "risk" : "gap",
865
- claim: `${a.path} trails the repo by ${gapDays} days of commit traffic \u2014 it says "now" but the repo moved on`,
866
- evidence: [
867
- `${a.path} last commit: ${fact.lastCommit}`,
868
- `repo last commit: ${freshness.repoLastCommit}`
869
- ],
870
- why: escalated ? `Over three times the ${budgets.staleAfterDays}-day threshold while commits kept landing \u2014 every session starts from a picture of the project that is no longer true.` : `A state doc more than ${budgets.staleAfterDays} days behind continued commit traffic misleads every session that loads it.`,
871
- action: "Refresh the state doc (or record why it is still current).",
872
- effort: "S",
873
- confidence: "high"
874
- });
875
- }
876
- }
877
- for (const a of stateArtifacts) {
878
- const text = await readText(path.join(ctx.root, a.path));
879
- if (text === null) {
880
- disclosures.push(`${a.path} could not be read \u2014 unexamined, not clean.`);
881
- outOfScope.push(a.path);
882
- continue;
883
- }
884
- if (text.length > budgets.maxChars) {
885
- findings.push({
886
- id: `${LENS_ID3}/state-over-budget:${a.path}`,
887
- lens: LENS_ID3,
888
- tier: "gap",
889
- claim: `${a.path} is ${text.length} chars \u2014 over the ${budgets.maxChars}-char state budget`,
890
- evidence: [`${a.path}: ${text.length} chars`],
891
- why: "Session-injection hooks truncate state around 10,000 chars \u2014 an over-budget state doc gets cut mid-sentence, and every session pays its full weight before the task begins.",
892
- action: "Trim to budget; move overflow into decisions/docs and keep a pointer.",
893
- effort: "M",
894
- confidence: "high"
895
- });
896
- }
897
- }
898
- for (const a of decisionArtifacts) {
899
- const text = await readText(path.join(ctx.root, a.path));
900
- if (text === null) {
901
- disclosures.push(
902
- `${a.path} recognized as a decisions convention (directory) \u2014 age-exempt; per-entry format checks apply only to marker-carrying decisions files.`
903
- );
904
- continue;
905
- }
906
- const entries = parseDecisionEntries(text);
907
- findings.push(...checkIdSequence(a.path, entries));
908
- const format = parseDecisionsFormat(text);
909
- if (!format) {
910
- disclosures.push(
911
- `${a.path} carries no \`${DECISIONS_FORMAT_MARKER}\` marker \u2014 format checks skipped (forward-only, never retroactive); id-sequence checks still ran.`
912
- );
913
- outOfScope.push(a.path);
914
- continue;
915
- }
916
- for (const problem of format.problems) disclosures.push(`${a.path}: ${problem}`);
917
- const exempt = entries.filter((e) => e.offset < format.offset);
918
- if (format.fields.length > 0) {
919
- disclosures.push(
920
- `${a.path} declares required entry fields: ${format.fields.join(", ")} \u2014 checked on every entry at or after the marker (etymd attaches no meaning to the names).`
921
- );
922
- }
923
- if (exempt.length > 0) {
924
- disclosures.push(
925
- `${a.path}: ${exempt.length} entr${exempt.length === 1 ? "y" : "ies"} precede the format marker (${exempt[0]?.id}\u2026${exempt[exempt.length - 1]?.id}) \u2014 field presence not checked there (forward-only from the marker's position).`
926
- );
927
- }
928
- findings.push(...checkFormatFields(a.path, entries, today, format.fields, format.offset));
929
- }
930
- disclosures.push(
931
- `Thresholds: staleAfterDays ${budgets.staleAfterDays} (3x escalates to risk), state budget ${budgets.maxChars} chars (${budgets.staleAfterDays === DEFAULT_CONFIG.state.staleAfterDays && budgets.maxChars === DEFAULT_CONFIG.state.maxChars ? `defaults \u2014 override under \`state\` in ${CONFIG_FILE}` : `set in ${CONFIG_FILE}`}). Decisions artifacts are exempt from age \u2014 old decisions are history, not defects.`
932
- );
933
- return {
934
- lens: LENS_ID3,
935
- version: "1",
936
- title: "State freshness",
937
- kind: "truth",
938
- status: "ran",
939
- disclosures,
940
- findings,
941
- ...outOfScope.length ? { outOfScope } : {}
942
- };
943
- }
944
- };
945
- async function listInstructionFiles(root, facts, scope) {
946
- const files = [];
947
- const add = async (rel) => {
948
- const text = await readText(path.join(root, rel));
949
- if (text !== null) files.push({ path: normalizeRelPath(rel), text });
950
- };
951
- const singleFileArtifacts = [
952
- "agents",
953
- "claude",
954
- "gemini",
955
- "copilot",
956
- "cursorrules",
957
- "cline",
958
- "windsurf"
959
- ];
960
- for (const id of singleFileArtifacts) {
961
- const artifact = facts.artifacts.find((a) => a.id === id);
962
- if (artifact?.exists) await add(artifact.path);
963
- }
964
- const rulesDir = path.join(root, ".cursor", "rules");
965
- if (await isDirectory(rulesDir)) {
966
- try {
967
- for (const entry of await promises.readdir(rulesDir)) {
968
- if (entry.endsWith(".md") || entry.endsWith(".mdc"))
969
- await add(path.join(".cursor/rules", entry));
970
- }
971
- } catch {
972
- }
973
- }
974
- const skillsDir = path.join(root, ".claude", "skills");
975
- if (await isDirectory(skillsDir)) {
976
- try {
977
- for (const entry of await promises.readdir(skillsDir)) {
978
- const skill = path.join(".claude/skills", entry, "SKILL.md");
979
- await add(skill);
980
- }
981
- } catch {
982
- }
983
- }
984
- const detected = new Set(files.map((f) => f.path));
985
- const included = [];
986
- for (const rel of await expandFileGlobs(root, scope?.include ?? [])) {
987
- if (detected.has(rel)) continue;
988
- const before = files.length;
989
- await add(rel);
990
- if (files.length > before) included.push(rel);
991
- }
992
- const exclude = scope?.exclude ?? [];
993
- if (!exclude.length) return { files, excluded: [], included };
994
- const kept = [];
995
- const excluded = [];
996
- for (const file of files) {
997
- if (matchesAnyGlob(file.path, exclude)) excluded.push(file.path);
998
- else kept.push(file);
999
- }
1000
- return { files: kept, excluded, included };
1001
- }
1002
- async function listStateDocuments(root, facts) {
1003
- const docs = [];
1004
- for (const artifact of facts.artifacts) {
1005
- if (artifact.kind !== "state" || !artifact.exists) continue;
1006
- const text = await readText(path.join(root, artifact.path));
1007
- if (text !== null) docs.push({ path: normalizeRelPath(artifact.path), text });
1008
- }
1009
- return docs;
1010
- }
1011
- function extractCodeTokens(text) {
1012
- const tokens = [];
1013
- for (const m of text.matchAll(/`([^`\n]+)`/g)) tokens.push(m[1].trim());
1014
- for (const block of text.matchAll(/```[a-z]*\n([\s\S]*?)```/g)) {
1015
- for (const line of block[1].split("\n")) {
1016
- const trimmed = line.trim();
1017
- if (trimmed && !trimmed.startsWith("#")) tokens.push(trimmed);
1018
- }
1019
- }
1020
- return tokens;
1021
- }
1022
- var PM_BUILTINS = /* @__PURE__ */ new Set([
1023
- "install",
1024
- "i",
1025
- "add",
1026
- "remove",
1027
- "rm",
1028
- "up",
1029
- "update",
1030
- "upgrade",
1031
- "dlx",
1032
- "exec",
1033
- "create",
1034
- "init",
1035
- "link",
1036
- "unlink",
1037
- "publish",
1038
- "pack",
1039
- "audit",
1040
- "outdated",
1041
- "why",
1042
- "list",
1043
- "ls",
1044
- "view",
1045
- "info",
1046
- "config",
1047
- "store",
1048
- "import",
1049
- "rebuild",
1050
- "prune",
1051
- "setup",
1052
- "env",
1053
- "bin",
1054
- "root",
1055
- "licenses",
1056
- "patch",
1057
- "approve-builds",
1058
- "workspaces",
1059
- "workspace",
1060
- "cache",
1061
- "version",
1062
- "help"
1063
- ]);
1064
- function extractCommandClaims(text) {
1065
- const scripts = /* @__PURE__ */ new Map();
1066
- let filteredSkipped = 0;
1067
- for (const token of extractCodeTokens(text)) {
1068
- for (const m of token.matchAll(
1069
- /(?:^|&&\s*|\|\|\s*|;\s*|\|\s*|\$\s+|\(\s*)(pnpm|yarn|npm|bun)\s+(?:(run)\s+)?(-{0,2}[A-Za-z0-9:._@/[\]-]+)/g
1070
- )) {
1071
- const pm = m[1];
1072
- const ranExplicit = Boolean(m[2]);
1073
- const arg = m[3];
1074
- if (arg.startsWith("-")) {
1075
- filteredSkipped += 1;
1076
- continue;
1077
- }
1078
- if (pm === "npm" && !ranExplicit && arg !== "test" && arg !== "start") continue;
1079
- if ((pm === "bun" || pm === "yarn" || pm === "pnpm") && !ranExplicit && PM_BUILTINS.has(arg))
1080
- continue;
1081
- if (ranExplicit && PM_BUILTINS.has(arg)) continue;
1082
- scripts.set(arg, token);
1083
- }
1084
- }
1085
- return { scripts, filteredSkipped };
1086
- }
1087
- var PATH_TOKEN_RE = /^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.$-]+)+\/?$/;
1088
- var KNOWN_EXTENSIONS = /* @__PURE__ */ new Set([
1089
- ..."ts tsx cts mts js jsx cjs mjs json jsonc json5 md mdx mdc yml yaml toml ini cfg conf env sh bash zsh fish ps1 bat cmd css scss sass less html htm xml svg sql prisma graphql gql proto py rb rs go java kt kts swift c h cc cpp hpp cs php vue svelte astro txt log lock csv tsv png jpg jpeg gif webp ico avif woff woff2 ttf otf wasm map pem key crt tf tfvars example sample local snap ejs hbs pug".split(" ")
1090
- ]);
1091
- var CREATION_CONTEXT_RE = /\b(?:creat(?:e|es|ed|ing)|generat(?:e|es|ed|ing)|scaffold(?:s|ed|ing)?|quarantin(?:e|es|ed|ing)|(?:writ(?:e|es|ten|ing)|output(?:s|ted)?|emit(?:s|ted|ting)?|sav(?:e|es|ed|ing)|mov(?:e|es|ed|ing)|copy|copi(?:es|ed))\s+(?:it\s+|them\s+)?(?:to|into)|new\s+(?:file|directory|folder)|will\s+(?:be\s+)?(?:created|generated|written)|add(?:s|ed|ing)?\s+(?:a|the)\s+new)\b/i;
1092
- var PLACEHOLDER_SEGMENTS = /* @__PURE__ */ new Set(["placeholder", "foo", "bar", "baz", "qux"]);
1093
- var PLACEHOLDER_PREFIX_RE = /^(?:my|your)-/i;
1094
- function isPlaceholderClaim(token) {
1095
- return token.split("/").some((seg) => PLACEHOLDER_PREFIX_RE.test(seg) || PLACEHOLDER_SEGMENTS.has(seg.toLowerCase()));
1096
- }
1097
- function claimContext(text, index) {
1098
- const start = text.lastIndexOf("\n", index) + 1;
1099
- const endRaw = text.indexOf("\n", index);
1100
- const end = endRaw === -1 ? text.length : endRaw;
1101
- const line = text.slice(start, end);
1102
- if (!/^\s*(?:[-*+]|\d+[.)]|\|)/.test(line)) return line;
1103
- let cursor = start;
1104
- while (cursor > 0) {
1105
- const prevEnd = cursor - 1;
1106
- const prevStart = text.lastIndexOf("\n", prevEnd - 1) + 1;
1107
- const prev = text.slice(prevStart, prevEnd);
1108
- cursor = prevStart;
1109
- if (!prev.trim()) continue;
1110
- if (/^\s*(?:[-*+]|\d+[.)]|\|)/.test(prev)) continue;
1111
- return `${prev}
1112
- ${line}`;
1113
- }
1114
- return line;
1115
- }
1116
- function extractPathClaims(text) {
1117
- const prospectiveOnly = /* @__PURE__ */ new Map();
1118
- const placeholder = /* @__PURE__ */ new Set();
1119
- for (const m of text.matchAll(/`([^`\n]+)`/g)) {
1120
- const token = m[1].trim();
1121
- if (token.includes(" ") || token.length > 120) continue;
1122
- if (token.startsWith("/") || token.startsWith("~") || token.startsWith("@") || token.startsWith("$"))
1123
- continue;
1124
- if (token.includes("://") || token.startsWith("www.")) continue;
1125
- if (/[*?{}<>|]/.test(token)) continue;
1126
- if (token.includes("@")) continue;
1127
- if (!PATH_TOKEN_RE.test(token)) continue;
1128
- if (token.split("/").some((seg) => seg.startsWith("$"))) continue;
1129
- const isDirClaim = token.endsWith("/");
1130
- const ext = token.toLowerCase().match(/\.([a-z0-9]{1,8})$/)?.[1];
1131
- if (!isDirClaim && !(ext && KNOWN_EXTENSIONS.has(ext))) continue;
1132
- const claim = token.replace(/\/$/, "");
1133
- if (isPlaceholderClaim(claim)) {
1134
- placeholder.add(claim);
1135
- continue;
1136
- }
1137
- const prospective2 = CREATION_CONTEXT_RE.test(claimContext(text, m.index ?? 0));
1138
- prospectiveOnly.set(claim, (prospectiveOnly.get(claim) ?? true) && prospective2);
1139
- }
1140
- const paths = [];
1141
- const prospective = [];
1142
- for (const [claim, only] of prospectiveOnly) {
1143
- if (only) prospective.push(claim);
1144
- else paths.push(claim);
1145
- }
1146
- return { paths, prospective, placeholder: [...placeholder] };
1147
- }
1148
- var LOCAL_REF_LEADINS = new Set(
1149
- "decision decisions entry entries ruling rulings record records ledger id ids item items see per in of on at by to as is was are were the a an and or but not with under over from via vs than after before since between through against latest newest earliest only also still now supersedes superseded superseding amends amended extends extended cites cited citing adds added adding wrote written writes locked locks closed closes opened opens resolves resolved reopened recorded number numbers".split(" ")
1150
- );
1151
- function extractDecisionRefs(text) {
1152
- const byNum = /* @__PURE__ */ new Map();
1153
- for (const m of text.matchAll(/\bD-(\d{1,4})\b/g)) {
1154
- const index = m.index ?? 0;
1155
- if (index > 0 && /[-/_.]/.test(text[index - 1])) continue;
1156
- const before = text.slice(Math.max(0, index - 48), index);
1157
- const lead = /([A-Za-z][A-Za-z0-9'’-]*)[ \t]+$/.exec(before)?.[1];
1158
- const local = !lead || LOCAL_REF_LEADINS.has(lead.toLowerCase());
1159
- const num = Number(m[1]);
1160
- const seen = byNum.get(num);
1161
- if (!seen) byNum.set(num, { asWritten: m[0], local });
1162
- else seen.local = seen.local || local;
1163
- }
1164
- const refs = /* @__PURE__ */ new Map();
1165
- let qualifiedSkipped = 0;
1166
- for (const [num, ref] of byNum) {
1167
- if (ref.local) refs.set(num, ref.asWritten);
1168
- else qualifiedSkipped += 1;
1169
- }
1170
- return { refs, qualifiedSkipped };
1171
- }
1172
- function packageManagerUsage(text) {
1173
- const counts = /* @__PURE__ */ new Map();
1174
- for (const token of extractCodeTokens(text)) {
1175
- for (const m of token.matchAll(/\b(pnpm|yarn|npm|bun)\s+(?:run\s+)?[A-Za-z-]/g)) {
1176
- const pm = m[1];
1177
- counts.set(pm, (counts.get(pm) ?? 0) + 1);
1178
- }
1179
- }
1180
- return counts;
1181
- }
1182
- var KNOWN_DOC_REFS = [
1183
- "AGENTS.md",
1184
- "CLAUDE.md",
1185
- "PROJECT_CONTEXT.md",
1186
- "DECISIONS.md",
1187
- "GEMINI.md"
1188
- ];
1189
- function extractDocRefs(text) {
1190
- return KNOWN_DOC_REFS.filter((name) => text.includes(name));
1191
- }
1192
746
 
1193
747
  // src/lenses/instruction-truth/lens.ts
1194
- var LENS_ID4 = "instruction-truth";
748
+ var LENS_ID3 = "instruction-truth";
1195
749
  var MAX_PATH_FINDINGS_PER_FILE = 15;
1196
750
  function finding2(partial) {
1197
- return { lens: LENS_ID4, ...partial };
751
+ return { lens: LENS_ID3, ...partial };
1198
752
  }
1199
753
  function compareCommands(baseline, fresh) {
1200
754
  const out = [];
@@ -1203,7 +757,7 @@ function compareCommands(baseline, fresh) {
1203
757
  if (before && !(before in fresh.commands.raw)) {
1204
758
  out.push(
1205
759
  finding2({
1206
- id: `${LENS_ID4}/command-gone-${role}`,
760
+ id: `${LENS_ID3}/command-gone-${role}`,
1207
761
  tier: "risk",
1208
762
  claim: `Documented ${role} command \`${before}\` no longer exists in package.json`,
1209
763
  evidence: ["package.json"],
@@ -1225,7 +779,7 @@ function compareArtifacts(baseline, fresh) {
1225
779
  if (a.exists && now && !now.exists) {
1226
780
  out.push(
1227
781
  finding2({
1228
- id: `${LENS_ID4}/artifact-gone-${a.id}`,
782
+ id: `${LENS_ID3}/artifact-gone-${a.id}`,
1229
783
  tier: "gap",
1230
784
  claim: `${a.label} was present at baseline but is now missing`,
1231
785
  evidence: [a.path],
@@ -1243,7 +797,7 @@ function compareLayout(baseline, fresh) {
1243
797
  const now = new Set(fresh.tree.dirs.map((d) => d.name));
1244
798
  return baseline.tree.dirs.filter((d) => !now.has(d.name)).map(
1245
799
  (d) => finding2({
1246
- id: `${LENS_ID4}/dir-gone-${d.name}`,
800
+ id: `${LENS_ID3}/dir-gone-${d.name}`,
1247
801
  tier: "gap",
1248
802
  claim: `Top-level \`${d.name}/\` from the baseline no longer exists \u2014 the repo map may be stale`,
1249
803
  evidence: [`${d.name}/`],
@@ -1255,7 +809,7 @@ function compareLayout(baseline, fresh) {
1255
809
  );
1256
810
  }
1257
811
  var instructionTruthLens = {
1258
- id: LENS_ID4,
812
+ id: LENS_ID3,
1259
813
  version: "1",
1260
814
  title: "Instruction truth",
1261
815
  kind: "truth",
@@ -1273,7 +827,7 @@ var instructionTruthLens = {
1273
827
  if (!files.length) {
1274
828
  findings.push(
1275
829
  finding2({
1276
- id: `${LENS_ID4}/no-contract`,
830
+ id: `${LENS_ID3}/no-contract`,
1277
831
  tier: "gap",
1278
832
  claim: "No agent instruction files exist (AGENTS.md or equivalents)",
1279
833
  evidence: ["AGENTS.md (missing)"],
@@ -1284,98 +838,17 @@ var instructionTruthLens = {
1284
838
  })
1285
839
  );
1286
840
  }
1287
- const knownScripts = new Set(Object.keys(facts.commands.raw));
1288
- for (const pkg of facts.packages) {
1289
- const pkgJson = await readJson(
1290
- path.join(root, pkg.dir, "package.json")
1291
- );
1292
- for (const key of Object.keys(pkgJson?.scripts ?? {})) knownScripts.add(key);
1293
- }
1294
- const pathResolves = async (claim) => {
1295
- const bases = [root, ...facts.packages.map((p) => path.join(root, p.dir))];
1296
- for (const base of bases) {
1297
- if (await pathExists(path.join(base, claim))) return true;
1298
- if (await pathExists(path.join(base, "src", claim))) return true;
1299
- if (await pathExists(path.join(base, "scripts", claim))) return true;
1300
- }
1301
- return false;
1302
- };
1303
- const binResolves = async (name) => {
1304
- const bases = [root, ...facts.packages.map((p) => path.join(root, p.dir))];
1305
- for (const base of bases) {
1306
- if (await pathExists(path.join(base, "node_modules", ".bin", name))) return true;
1307
- }
1308
- return false;
841
+ const env = await buildTruthEnv(root, facts);
842
+ const counters = emptyCounters();
843
+ const claimOpts = {
844
+ lensId: LENS_ID3,
845
+ missingPathTier: "gap",
846
+ maxPathFindings: MAX_PATH_FINDINGS_PER_FILE
1309
847
  };
1310
- const nodeModulesInstalled = await pathExists(path.join(root, "node_modules"));
1311
- const manifestExists = await pathExists(path.join(root, "package.json")) || facts.packages.length > 0;
1312
- let totalFilteredSkipped = 0;
1313
- let binaryResolved = 0;
1314
- let unverifiableCommands = 0;
1315
- let gitignoredSkipped = 0;
1316
- let prospectiveSkipped = 0;
1317
- let placeholderSkipped = 0;
1318
848
  const auditClaims = async (file) => {
1319
- const { scripts: claimed, filteredSkipped } = extractCommandClaims(file.text);
1320
- totalFilteredSkipped += filteredSkipped;
1321
- for (const [script, raw] of claimed) {
1322
- if (knownScripts.has(script)) continue;
1323
- if (await binResolves(script)) {
1324
- binaryResolved += 1;
1325
- continue;
1326
- }
1327
- if (!nodeModulesInstalled && manifestExists) {
1328
- unverifiableCommands += 1;
1329
- continue;
1330
- }
1331
- findings.push(
1332
- finding2({
1333
- id: `${LENS_ID4}/stale-command:${file.path}:${script}`,
1334
- tier: "risk",
1335
- claim: `${file.path} tells agents to run \`${script}\` \u2014 no such script exists`,
1336
- evidence: [`${file.path}: \`${raw}\``, "package.json scripts (root + workspaces)"],
1337
- why: "An agent following this instruction runs a command that fails \u2014 or silently skips the check it was meant to run.",
1338
- action: "Update the instruction to the current script name (or restore the script).",
1339
- effort: "S",
1340
- confidence: "high"
1341
- })
1342
- );
1343
- }
1344
- const { paths, prospective, placeholder } = extractPathClaims(file.text);
1345
- prospectiveSkipped += prospective.length;
1346
- placeholderSkipped += placeholder.length;
1347
- const missing = [];
1348
- for (const claim of paths) {
1349
- if (!await pathResolves(claim)) missing.push(claim);
1350
- }
1351
- const ignoredOut = missing.length ? await git(root, ["check-ignore", ...missing]) : null;
1352
- const gitignored = new Set((ignoredOut ?? "").split("\n").filter(Boolean));
1353
- let pathFindings = 0;
1354
- for (const claim of missing) {
1355
- if (gitignored.has(claim)) {
1356
- gitignoredSkipped += 1;
1357
- continue;
1358
- }
1359
- if (pathFindings >= MAX_PATH_FINDINGS_PER_FILE) {
1360
- disclosures.push(
1361
- `${file.path}: more than ${MAX_PATH_FINDINGS_PER_FILE} missing-path claims \u2014 truncated.`
1362
- );
1363
- break;
1364
- }
1365
- pathFindings += 1;
1366
- findings.push(
1367
- finding2({
1368
- id: `${LENS_ID4}/stale-path:${file.path}:${claim}`,
1369
- tier: "gap",
1370
- claim: `${file.path} references \`${claim}\` \u2014 it does not exist in the repo`,
1371
- evidence: [file.path, `missing: ${claim}`],
1372
- why: "Agents navigate by these references; a dead path wastes a lookup and erodes trust in the rest of the file.",
1373
- action: "Fix or remove the reference.",
1374
- effort: "S",
1375
- confidence: "medium"
1376
- })
1377
- );
1378
- }
849
+ const result = await checkTextClaims(env, file, claimOpts, counters);
850
+ findings.push(...result.findings);
851
+ disclosures.push(...result.disclosures);
1379
852
  };
1380
853
  for (const file of files) {
1381
854
  await auditClaims(file);
@@ -1386,7 +859,7 @@ var instructionTruthLens = {
1386
859
  if (pm === facts.packageManager || count < 2 || count <= own) continue;
1387
860
  findings.push(
1388
861
  finding2({
1389
- id: `${LENS_ID4}/pm-conflict:${file.path}`,
862
+ id: `${LENS_ID3}/pm-conflict:${file.path}`,
1390
863
  tier: "gap",
1391
864
  claim: `${file.path} instructs \`${pm}\` (${count}\xD7) but the repo uses ${facts.packageManager}`,
1392
865
  evidence: [file.path, `lockfile \u2192 ${facts.packageManager}`],
@@ -1399,64 +872,15 @@ var instructionTruthLens = {
1399
872
  break;
1400
873
  }
1401
874
  }
1402
- for (const ref of extractDocRefs(file.text)) {
1403
- if (await pathExists(path.join(root, ref))) continue;
1404
- findings.push(
1405
- finding2({
1406
- id: `${LENS_ID4}/dangling-ref:${file.path}:${ref}`,
1407
- tier: "gap",
1408
- claim: `${file.path} references ${ref} \u2014 no such file exists`,
1409
- evidence: [file.path, `missing: ${ref}`],
1410
- why: "The pointer chain agents follow breaks at a file they can never read.",
1411
- action: `Create ${ref} or remove the reference.`,
1412
- effort: "S",
1413
- confidence: "high"
1414
- })
1415
- );
1416
- }
875
+ findings.push(...(await checkDocRefs(env, file, LENS_ID3, counters)).findings);
1417
876
  }
1418
877
  const auditedPaths = new Set(files.map((f) => f.path));
1419
878
  const stateDocs = await listStateDocuments(root, facts);
1420
- let qualifiedRefsSkipped = 0;
1421
- let unresolvableRefs = 0;
1422
- let ledgerIds = null;
1423
- const ledgerSources = [];
1424
- if (stateDocs.length) {
1425
- for (const artifact of facts.artifacts) {
1426
- if (artifact.kind !== "decisions" || !artifact.exists) continue;
1427
- const text = await readText(path.join(root, artifact.path));
1428
- if (text === null) continue;
1429
- const entries = parseDecisionEntries(text);
1430
- if (!entries.length) continue;
1431
- ledgerIds ??= /* @__PURE__ */ new Set();
1432
- for (const entry of entries) ledgerIds.add(entry.num);
1433
- ledgerSources.push(artifact.path);
1434
- }
1435
- }
879
+ const ledger = stateDocs.length ? await loadDecisionLedger(root, facts) : { ids: null, sources: [] };
880
+ const ledgerSources = ledger.sources;
1436
881
  for (const doc of stateDocs) {
1437
882
  if (!auditedPaths.has(doc.path)) await auditClaims(doc);
1438
- const { refs, qualifiedSkipped } = extractDecisionRefs(doc.text);
1439
- qualifiedRefsSkipped += qualifiedSkipped;
1440
- if (!refs.size) continue;
1441
- if (!ledgerIds) {
1442
- unresolvableRefs += refs.size;
1443
- continue;
1444
- }
1445
- for (const [num, asWritten] of refs) {
1446
- if (ledgerIds.has(num)) continue;
1447
- findings.push(
1448
- finding2({
1449
- id: `${LENS_ID4}/dead-decision-ref:${doc.path}:${asWritten}`,
1450
- tier: "gap",
1451
- claim: `${doc.path} cites ${asWritten} \u2014 no such entry exists in ${ledgerSources.join(", ")}`,
1452
- evidence: [doc.path, `${ledgerSources.join(", ")}: no ${asWritten} entry`],
1453
- why: "A state doc is read as ground truth on return; a citation the decision record cannot back sends readers to a ruling that was never written.",
1454
- action: "Fix the reference \u2014 or record the missing decision.",
1455
- effort: "S",
1456
- confidence: "medium"
1457
- })
1458
- );
1459
- }
883
+ findings.push(...checkDecisionRefs(doc, ledger, { lensId: LENS_ID3 }, counters).findings);
1460
884
  }
1461
885
  if (ctx.baseline) {
1462
886
  findings.push(
@@ -1479,29 +903,34 @@ var instructionTruthLens = {
1479
903
  "No committed baseline (.etymd/baseline.json) \u2014 drift over time is not measurable; run `etymd init` to approve one."
1480
904
  );
1481
905
  }
1482
- if (binaryResolved) {
906
+ if (counters.binaryResolved) {
907
+ disclosures.push(
908
+ `${counters.binaryResolved} command claim(s) are installed binaries (node_modules/.bin), not package scripts \u2014 treated as true.`
909
+ );
910
+ }
911
+ if (counters.unverifiableCommands) {
1483
912
  disclosures.push(
1484
- `${binaryResolved} command claim(s) are installed binaries (node_modules/.bin), not package scripts \u2014 treated as true.`
913
+ `node_modules is not installed \u2014 ${counters.unverifiableCommands} command claim(s) matching no package script could not be checked against installed binaries; skipped, not flagged.`
1485
914
  );
1486
915
  }
1487
- if (unverifiableCommands) {
916
+ if (counters.gitignoredSkipped) {
1488
917
  disclosures.push(
1489
- `node_modules is not installed \u2014 ${unverifiableCommands} command claim(s) matching no package script could not be checked against installed binaries; skipped, not flagged.`
918
+ `${counters.gitignoredSkipped} missing path claim(s) are gitignored (machine-local, e.g. .env) \u2014 existence is not verifiable from the repo; skipped, not flagged.`
1490
919
  );
1491
920
  }
1492
- if (gitignoredSkipped) {
921
+ if (counters.prospectiveSkipped) {
1493
922
  disclosures.push(
1494
- `${gitignoredSkipped} missing path claim(s) are gitignored (machine-local, e.g. .env) \u2014 existence is not verifiable from the repo; skipped, not flagged.`
923
+ `${counters.prospectiveSkipped} path claim(s) sit in create-this prose (the file instructs generating them) \u2014 forward-looking, not stale; skipped, not flagged.`
1495
924
  );
1496
925
  }
1497
- if (prospectiveSkipped) {
926
+ if (counters.placeholderSkipped) {
1498
927
  disclosures.push(
1499
- `${prospectiveSkipped} path claim(s) sit in create-this prose (the file instructs generating them) \u2014 forward-looking, not stale; skipped, not flagged.`
928
+ `${counters.placeholderSkipped} path claim(s) are naming stand-ins (e.g. \`my-custom-skill\`) rather than real references; skipped, not flagged.`
1500
929
  );
1501
930
  }
1502
- if (placeholderSkipped) {
931
+ if (counters.tildeSkipped) {
1503
932
  disclosures.push(
1504
- `${placeholderSkipped} path claim(s) are naming stand-ins (e.g. \`my-custom-skill\`) rather than real references; skipped, not flagged.`
933
+ `${counters.tildeSkipped} well-known doc mention(s) sit inside \`~/\` home paths (e.g. \`~/.claude/CLAUDE.md\`) \u2014 machine-global files, not this repo's; skipped, not flagged.`
1505
934
  );
1506
935
  }
1507
936
  if (stateDocs.length) {
@@ -1509,14 +938,14 @@ var instructionTruthLens = {
1509
938
  `Checked ${stateDocs.length} state document(s) for command, path, and decision-reference claims (same skip classes as instruction files); decision ids resolved against ${ledgerSources.length ? ledgerSources.join(", ") : "nothing \u2014 no decisions file with D-NNN entries"}.`
1510
939
  );
1511
940
  }
1512
- if (qualifiedRefsSkipped) {
941
+ if (counters.qualifiedRefsSkipped) {
1513
942
  disclosures.push(
1514
- `${qualifiedRefsSkipped} decision reference(s) name another record (e.g. a fleet-level ledger) \u2014 not claims about this repo's decisions; skipped, not flagged.`
943
+ `${counters.qualifiedRefsSkipped} decision reference(s) name another record (e.g. a fleet-level ledger) \u2014 not claims about this repo's decisions; skipped, not flagged.`
1515
944
  );
1516
945
  }
1517
- if (unresolvableRefs) {
946
+ if (counters.unresolvableRefs) {
1518
947
  disclosures.push(
1519
- `${unresolvableRefs} decision reference(s) could not be resolved \u2014 no decisions file with \`## D-NNN\` entries; skipped, not flagged.`
948
+ `${counters.unresolvableRefs} decision reference(s) could not be resolved \u2014 no decisions file with \`## D-NNN\` entries; skipped, not flagged.`
1520
949
  );
1521
950
  }
1522
951
  if (excluded.length) {
@@ -1531,10 +960,10 @@ var instructionTruthLens = {
1531
960
  );
1532
961
  }
1533
962
  disclosures.push(
1534
- `Checked ${files.length} instruction file(s); commands resolved against root + ${facts.packages.length} workspace manifest(s) plus installed binaries; paths matched against root and package roots. Heuristics: workspace-filtered commands skipped (${totalFilteredSkipped}); tokens without a recognized extension treated as prose (a dir claim needs a trailing slash); gitignored claims unverifiable; create-this and stand-in path claims skipped; absolute/globbed/placeholder tokens skipped; framework-pattern staleness not checked.`
963
+ `Checked ${files.length} instruction file(s); commands resolved against root + ${facts.packages.length} workspace manifest(s) plus installed binaries; paths matched against root and package roots. Heuristics: workspace-filtered commands skipped (${counters.filteredSkipped}); tokens without a recognized extension treated as prose (a dir claim needs a trailing slash); gitignored claims unverifiable; create-this and stand-in path claims skipped; absolute/globbed/placeholder tokens skipped; doc mentions inside \`~/\` home paths skipped; framework-pattern staleness not checked.`
1535
964
  );
1536
965
  return {
1537
- lens: LENS_ID4,
966
+ lens: LENS_ID3,
1538
967
  version: "1",
1539
968
  title: "Instruction truth",
1540
969
  kind: "truth",
@@ -1608,4 +1037,4 @@ async function runAudit(root, opts = {}) {
1608
1037
  };
1609
1038
  }
1610
1039
 
1611
- export { meetsFailOn, parseFailOnTier, runAudit };
1040
+ export { runAudit };