@spike1292/claude-memory 0.0.0-stage → 0.14.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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -2
  3. package/hooks/distill-session.mjs +74 -0
  4. package/hooks/graph-staleness-check.mjs +25 -0
  5. package/hooks/hooks.json +94 -0
  6. package/hooks/insights-surface.mjs +48 -0
  7. package/hooks/lib/distill-session.mjs +1560 -0
  8. package/hooks/lib/dupe-report.mjs +61 -0
  9. package/hooks/lib/env-shell.mjs +92 -0
  10. package/hooks/lib/graph-staleness-check.mjs +394 -0
  11. package/hooks/lib/hook-io.mjs +715 -0
  12. package/hooks/lib/insights-surface.mjs +165 -0
  13. package/hooks/lib/memory-link-lint.mjs +499 -0
  14. package/hooks/lib/memory-recall.mjs +219 -0
  15. package/hooks/lib/omp.mjs +103 -0
  16. package/hooks/lib/opencode.mjs +231 -0
  17. package/hooks/lib/paths.mjs +452 -0
  18. package/hooks/lib/semantic-index-refresh.mjs +155 -0
  19. package/hooks/lib/validate-note.mjs +218 -0
  20. package/hooks/lib/vault-env.sh +110 -0
  21. package/hooks/memory-link-lint.mjs +65 -0
  22. package/hooks/memory-recall.mjs +251 -0
  23. package/hooks/semantic-index-refresh.mjs +23 -0
  24. package/hooks/session-context.mjs +9 -0
  25. package/hooks/validate-note.mjs +52 -0
  26. package/hooks/vault-memory-sync.sh +154 -0
  27. package/omp/index.js +1 -0
  28. package/opencode/index.js +1 -0
  29. package/package.json +51 -4
  30. package/scripts/claude-memory.mjs +31 -0
  31. package/scripts/doctor-perf.mjs +121 -0
  32. package/scripts/doctor.sh +558 -0
  33. package/scripts/env.mjs +6 -0
  34. package/scripts/lib/claude-memory.mjs +168 -0
  35. package/scripts/lib/doctor-perf.mjs +434 -0
  36. package/scripts/lib/hook-stats.mjs +864 -0
  37. package/scripts/lib/lexical.mjs +85 -0
  38. package/scripts/lib/memory-adopt.mjs +69 -0
  39. package/scripts/lib/memory-audit-checks.mjs +344 -0
  40. package/scripts/lib/memory-eval.mjs +381 -0
  41. package/scripts/lib/memory-mark.mjs +135 -0
  42. package/scripts/lib/memory-mcp.mjs +142 -0
  43. package/scripts/lib/memory-merge.mjs +316 -0
  44. package/scripts/lib/memory-mine.mjs +108 -0
  45. package/scripts/lib/memory-promote.mjs +207 -0
  46. package/scripts/lib/memory-prune.mjs +84 -0
  47. package/scripts/lib/memory-semantic.mjs +999 -0
  48. package/scripts/lib/memory-setup.mjs +170 -0
  49. package/scripts/lib/memory-synth-vault.mjs +538 -0
  50. package/scripts/lib/model-default.mjs +7 -0
  51. package/scripts/lib/models.mjs +58 -0
  52. package/scripts/lib/prune-logs.mjs +130 -0
  53. package/scripts/lib/recall-stats.mjs +354 -0
  54. package/scripts/lib/share-modules.mjs +70 -0
  55. package/scripts/lib/slim-install.mjs +162 -0
  56. package/scripts/lib/vault-mcp.mjs +405 -0
  57. package/scripts/memory-adopt.mjs +160 -0
  58. package/scripts/memory-audit-checks.mjs +375 -0
  59. package/scripts/memory-eval.mjs +753 -0
  60. package/scripts/memory-mark.mjs +39 -0
  61. package/scripts/memory-mcp.mjs +35 -0
  62. package/scripts/memory-merge.mjs +55 -0
  63. package/scripts/memory-prune.mjs +44 -0
  64. package/scripts/memory-semantic.mjs +1192 -0
  65. package/scripts/memory-setup.mjs +33 -0
  66. package/scripts/memory-synth-vault.mjs +251 -0
  67. package/scripts/prune-logs.mjs +42 -0
  68. package/scripts/share-modules.mjs +79 -0
  69. package/scripts/slim-install.mjs +55 -0
  70. package/scripts/vault-mcp.mjs +50 -0
  71. package/stubs/onnxruntime-web/index.mjs +11 -0
  72. package/stubs/onnxruntime-web/package.json +12 -0
  73. package/stubs/sharp/index.mjs +11 -0
  74. package/stubs/sharp/package.json +12 -0
@@ -0,0 +1,85 @@
1
+ // The lexical vocabulary shared by the search CLI and the UserPromptSubmit recall hook: the card
2
+ // sentinel, the stopword list, the tokeniser, BM25 and the supersession marker. Nothing else.
3
+ //
4
+ // Split out from memory-semantic.mjs so hooks/memory-recall.mjs can import it STATICALLY, above its
5
+ // fail-open try — memory-semantic.mjs's module scope does console.log() + process.exit(1) on an
6
+ // unknown model, which would crash every prompt's recall hook. Design story and the module-init
7
+ // cost measurement (2026-08-19): docs/architecture.md, section B1.
8
+ //
9
+ // THIS FILE IMPORTS NOTHING — not even a node builtin. Keep it that way: an import added here runs
10
+ // on every prompt, armed or not.
11
+ //
12
+ // memory-semantic.mjs re-exports all four, so existing consumers and tests are unchanged.
13
+
14
+ // The card chunk's heading (`CARD`) is a WIRE value, not a label — every reader binds it as a SQL
15
+ // parameter so a rename cannot go silent again. Full failure mode: R4 in docs/architecture.md.
16
+ export const CARD = '(card)';
17
+
18
+ // Anywhere in a parenthetical: "(measured 2026-08-12, superseded 2026-08-14 by [[x]])" is a marker.
19
+ export const SUPERSEDED_MARKER = /superseded\s+\d{4}-\d{2}-\d{2}\s+by\s+\[\[[^\]]+\]\]/i;
20
+ export const SUPERSEDED_BY = /^\s*superseded_by:\s*(.+)$/m;
21
+
22
+ export const STOP = new Set(
23
+ 'the a an and or of to in on for is are was were it its this that with as by at from be not you your we our they them if then when what which how why do does did can could should would use used using via no yes into over under more most less least than each per also only just same other about have has had will'.split(
24
+ ' ',
25
+ ),
26
+ );
27
+
28
+ /**
29
+ * @param {string} s
30
+ * @returns {string[]}
31
+ */
32
+ export const lexTokens = (s) =>
33
+ s
34
+ .toLowerCase()
35
+ .split(/[^a-z0-9]+/)
36
+ .filter((w) => w.length > 2 && !STOP.has(w));
37
+
38
+ // Textbook BM25 over the chunk texts already in the index — no second store, no extra dependency.
39
+ //
40
+ // k1/b are DEFAULTS here and callers that gate on an absolute score must pass them explicitly:
41
+ // recall's MIN_SCORE = 6.0 and its MIN_SCORE/2 trailing floor are calibrated against 1.2/0.75, and
42
+ // a tune made for the CLI's fusion arm would silently rescale both. See hooks/lib/memory-recall.mjs.
43
+
44
+ /** @typedef {{ toks: string[] }} Bm25Doc */
45
+
46
+ // df and avgdl depend on the corpus, not the query: the server's bundles are immutable and asked
47
+ // every prompt, and recomputing them cost ~250 ms per query over all projects (2026-12-02).
48
+ /** @type {WeakMap<readonly Bm25Doc[], { df: Map<string, number>, avgdl: number }>} */
49
+ const corpusStats = new WeakMap();
50
+
51
+ /**
52
+ * @param {readonly Bm25Doc[]} docs
53
+ * @param {readonly string[]} qTokens
54
+ * @param {number} [k1]
55
+ * @param {number} [b]
56
+ * @returns {number[]}
57
+ */
58
+ export function bm25(docs, qTokens, k1 = 1.2, b = 0.75) {
59
+ const N = docs.length || 1;
60
+ let stats = corpusStats.get(docs);
61
+ if (!stats) {
62
+ const df = new Map();
63
+ for (const d of docs) for (const t of new Set(d.toks)) df.set(t, (df.get(t) || 0) + 1);
64
+ stats = { df, avgdl: docs.reduce((a, d) => a + d.toks.length, 0) / N };
65
+ corpusStats.set(docs, stats);
66
+ }
67
+ const { df, avgdl } = stats;
68
+ const want = new Set(qTokens);
69
+ return docs.map((d) => {
70
+ /** @type {Map<string, number> | null} */
71
+ let tf = null;
72
+ for (const t of d.toks) if (want.has(t)) (tf ??= new Map()).set(t, (tf.get(t) || 0) + 1);
73
+ if (!tf) return 0;
74
+ let s = 0;
75
+ for (const t of qTokens) {
76
+ const f = tf.get(t) || 0;
77
+ if (!f) continue;
78
+ const n = df.get(t) || 0;
79
+ s +=
80
+ (Math.log(1 + (N - n + 0.5) / (n + 0.5)) * (f * (k1 + 1))) /
81
+ (f + k1 * (1 - b + (b * d.toks.length) / avgdl));
82
+ }
83
+ return s;
84
+ });
85
+ }
@@ -0,0 +1,69 @@
1
+ // The adopt/rollback state machine for /memory:adopt (#96), the only path that writes to
2
+ // `permanent/`. `io` is injected so the gate — a held-out eval run shelling out to
3
+ // memory-eval.mjs — is testable without a subprocess or a real vault.
4
+ // CLI entry: scripts/memory-adopt.mjs. Tests: node --test scripts/lib/memory-adopt.test.mjs
5
+
6
+ /**
7
+ * Undrafted skeleton, drafted into the permanent shape, or neither — read off the frontmatter
8
+ * `type:` line only, since matching the placeholder PROSE would break on a note quoting its own
9
+ * history.
10
+ * @param {string} raw
11
+ * @returns {'undrafted' | 'ready' | 'wrong-type'}
12
+ */
13
+ export function checkDraftStatus(raw) {
14
+ const fm = raw.match(/^---\n([\s\S]*?)\n---\n/)?.[1] ?? '';
15
+ if (/^type:[ \t]*promotion-candidate[ \t]*$/m.test(fm)) return 'undrafted';
16
+ if (/^type:[ \t]*permanent[ \t]*$/m.test(fm)) return 'ready';
17
+ return 'wrong-type';
18
+ }
19
+
20
+ /** @typedef {{ failures: string[], recall1?: number | null, frozen?: string | null }} GateResult */
21
+ /** @typedef {{ readFile: (p: string) => string, writeFile: (p: string, s: string) => void, removeFile: (p: string) => void, exists: (p: string) => boolean, reindex: () => void, runGate: () => GateResult }} AdoptIO */
22
+ /** @typedef {{ stagedPath: string, targetPath: string, dryRun: boolean, force: boolean }} AdoptOpts */
23
+ /** @typedef {{ status: 'undrafted' | 'wrong-type' | 'exists' | 'dry-run' | 'rejected' | 'adopted', reasons?: string[], recall1?: number | null, frozen?: string | null }} AdoptResult */
24
+
25
+ /**
26
+ * Copy staged -> permanent/, reindex, run the held-out gate, roll back on failure. A rejected
27
+ * proposal keeps its staged file so it can be fixed and retried.
28
+ * @param {AdoptIO} io
29
+ * @param {AdoptOpts} opts
30
+ * @returns {AdoptResult}
31
+ */
32
+ export function adopt(io, opts) {
33
+ const raw = io.readFile(opts.stagedPath);
34
+ const draft = checkDraftStatus(raw);
35
+ if (draft === 'undrafted') return { status: 'undrafted' };
36
+ if (draft === 'wrong-type') return { status: 'wrong-type' };
37
+ const targetExisted = io.exists(opts.targetPath);
38
+ if (targetExisted && !opts.force) return { status: 'exists' };
39
+ if (opts.dryRun) return { status: 'dry-run' };
40
+ // --force overwrites an existing permanent/ note; a rejected gate must restore it, not delete
41
+ // it, or a failed re-draft of an already-adopted topic loses the note that was there before.
42
+ const previous = targetExisted ? io.readFile(opts.targetPath) : null;
43
+
44
+ /** @param {string[]} reasons @returns {AdoptResult} */
45
+ const reject = (reasons) => {
46
+ if (previous == null) io.removeFile(opts.targetPath);
47
+ else io.writeFile(opts.targetPath, previous);
48
+ try {
49
+ io.reindex(); // best-effort: a second failure here must not mask the real reason below
50
+ } catch {
51
+ /* the rejection stands either way */
52
+ }
53
+ return { status: 'rejected', reasons };
54
+ };
55
+
56
+ io.writeFile(opts.targetPath, raw);
57
+ try {
58
+ io.reindex();
59
+ } catch (e) {
60
+ // Reached with permanent/ already holding the unvalidated copy — a bare throw here would crash
61
+ // uncaught and leave it there with neither a gate run nor a rollback.
62
+ return reject([`reindex failed: ${/** @type {Error} */ (e).message}`]);
63
+ }
64
+ const gate = io.runGate();
65
+ if (gate.failures.length) return reject(gate.failures);
66
+
67
+ io.removeFile(opts.stagedPath);
68
+ return { status: 'adopted', recall1: gate.recall1 ?? null, frozen: gate.frozen ?? null };
69
+ }
@@ -0,0 +1,344 @@
1
+ #!/usr/bin/env node
2
+ // Mechanical half of /memory:health. Run it, judge the output — it decides nothing.
3
+ //
4
+ // Why this exists: hand-derived audits got the same two checks wrong twice (REFLECTIONS.md
5
+ // 2026-08-10, 2026-08-14) — confidence-nesting is a recorded failure mode in
6
+ // docs/decisions/2026-08-22-auto-memory.md; the abbreviated-path false positive is at
7
+ // isAbbreviated() below. Judgement stays with the auditor; this only finds candidates.
8
+ //
9
+ // Usage: node ~/.claude/scripts/memory-audit-checks.mjs [repo-dir] (default: cwd)
10
+ // ponytail: prints findings, never edits. Deleting or rewriting a note needs confirmation anyway.
11
+
12
+ import { execFileSync } from 'node:child_process';
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { SUPERSEDED_BY, SUPERSEDED_MARKER } from './lexical.mjs';
16
+ import { mdFiles, FENCE, INLINE_CODE } from '../../hooks/lib/memory-link-lint.mjs';
17
+
18
+ // ---------------------------------------------------------------- predicates (self-tested below)
19
+
20
+ // A claim about STATE that a later event can reverse — not an instruction. "**Never** cite an ADR
21
+ // from its filename" is advice and stays true forever; "cra2 prod has never served traffic" is a
22
+ // measurement with a shelf life. Gate on a state verb, and drop imperative openers.
23
+ const STATE_VERB =
24
+ 'served?|serves|had|has|have|been|is|are|was|were|ran|run|happened|occurred|shipped|landed|merged|deployed|fired|reached|exists?|existed|added|done|implemented|fixed|enabled|migrated|started|carried';
25
+ const STANDING = new RegExp(
26
+ `\\b(?:never (?:${STATE_VERB})|(?:has|have|had|is|are|was|were) never|not yet (?:${STATE_VERB})|` +
27
+ `no [a-z0-9 '\`*-]{0,25} yet\\b|(?:none|zero) (?:of )?[a-z0-9 '\`*-]{0,25}(?:traffic|usage|customers|requests)|` +
28
+ `so far no|still no\\b|(?:has|have)(?:n't| not) (?:${STATE_VERB}))`,
29
+ 'i',
30
+ );
31
+ // Imperative advice: the line's first words tell the reader what to do.
32
+ const IMPERATIVE =
33
+ /^[\s>*_#-]*(?:\*\*)?(?:never|do not|don't|avoid|always|prefer|use|treat|read|check|verify)\b/i;
34
+
35
+ /** @param {string} line @returns {boolean} */
36
+ export function isStandingNegative(line) {
37
+ const t = line.trim();
38
+ if (!t || t.startsWith('_Also asked as')) return false;
39
+ if (IMPERATIVE.test(t)) return false;
40
+ return STANDING.test(t);
41
+ }
42
+
43
+ // confidence: is nested under metadata:, so it is indented. A ^-anchored grep reports every note
44
+ // as missing it — the exact false positive logged in REFLECTIONS 2026-08-10 and re-hit 2026-08-14.
45
+ /** @param {string} frontmatter @returns {boolean} */
46
+ export function hasConfidence(frontmatter) {
47
+ return /^\s*confidence:\s*(high|medium|low)\s*$/m.test(frontmatter);
48
+ }
49
+
50
+ // An abbreviated path (`libs/foo/.../bar.ts`) is prose, not a claim. Reporting it "missing" is the
51
+ // other logged false positive: 15 of 24 "absent" paths in the 2026-08-14 audit were these.
52
+ /** @param {string} context @returns {boolean} */
53
+ export function isAbbreviated(context) {
54
+ return /…|\.\.\./.test(context);
55
+ }
56
+
57
+ // Carry-forward list: rows in REFLECTIONS.md whose disposition is still "deferred". A deferred item
58
+ // used to survive only if the next prune happened to rank it — two duplicate pairs deferred on
59
+ // 2026-08-08 were still there on 2026-08-14, because the 2026-08-08 prune merged three *different*
60
+ // pairs. The row IS the ledger: closing an item means editing its disposition, not just doing it.
61
+ /**
62
+ * @param {string} text
63
+ * @returns {{ entry: string, finding: string, disposition: string }[]}
64
+ */
65
+ export function parseDeferred(text) {
66
+ /** @type {{ entry: string, finding: string, disposition: string }[]} */
67
+ const out = [];
68
+ let entry = '?';
69
+ for (const line of text.split('\n')) {
70
+ const h = line.match(/^##\s+(\d{4}-\d{2}-\d{2})\s*—\s*(\S+)/);
71
+ if (h) entry = `${h[1]} ${h[2]}`;
72
+ if (!line.startsWith('|')) continue;
73
+ const cells = line
74
+ .split('|')
75
+ .slice(1, -1)
76
+ .map((c) => c.trim());
77
+ if (cells.length < 2) continue;
78
+ const disposition = cells[cells.length - 1];
79
+ if (/^\s*-+\s*$/.test(cells[0]) || /^disposition$/i.test(disposition)) continue; // header / separator
80
+ if (entry === '?') continue; // a disposition belongs to a dated entry; tables above the first one are not findings
81
+ // Anchor to the opening token: a "**declined** — complementary, not deferred" row is CLOSED.
82
+ if (!/^[\s*_]*deferred\b/i.test(disposition)) continue;
83
+ out.push({ entry, finding: cells[0], disposition });
84
+ }
85
+ return out;
86
+ }
87
+
88
+ // Finds claims that announce supersession in prose ("⚠ SUPERSEDED …") without the machine-readable
89
+ // marker `(superseded YYYY-MM-DD by [[note]])` that SUPERSEDED_MARKER checks for. Full per-claim
90
+ // (not per-note) model and why: skills/protocol/SKILL.md "Per-claim supersession: two dates, not
91
+ // one".
92
+ //
93
+ // Only CLAIM-supersession, not component replacement. "Core Modules already superseded by
94
+ // `@integration/api-client-*`" and "redirects-poller superseded by the KVS pipeline" describe
95
+ // software being replaced — true statements that will never need a marker. The house style for a
96
+ // dead *claim* is line-initial and shouty: "⚠ SUPERSEDED …" or "**Superseded since …**".
97
+ const SUPERSEDED_PROSE =
98
+ /^[\s>*_#-]*(?:⚠\s*)?\**(?:SUPERSEDED\b|Superseded (?:since|on|by)\b|No longer true\b)/m;
99
+ /**
100
+ * @param {string} raw
101
+ * @returns {{ declared: string|null, on: string|null, inProse: boolean, marked: boolean }}
102
+ */
103
+ export function supersessionState(raw) {
104
+ const fm = (raw.match(/^---\n([\s\S]*?)\n---/) || [])[1] || '';
105
+ const by = (fm.match(SUPERSEDED_BY) || [])[1];
106
+ const on = (fm.match(/^\s*superseded_on:\s*(.+)$/m) || [])[1];
107
+ const body = raw.slice(fm.length);
108
+ return {
109
+ declared: by ? by.trim().replace(/^["'\[]+|["'\]]+$/g, '') : null,
110
+ on: on ? on.trim() : null,
111
+ inProse: SUPERSEDED_PROSE.test(body),
112
+ marked: SUPERSEDED_MARKER.test(body),
113
+ };
114
+ }
115
+
116
+ // FRESH-1: flags a present-tense claim about a volatile quantity with no stamp and no dated
117
+ // container. Full timeless/snapshot/pointer model: skills/protocol/SKILL.md "Per-claim recency:
118
+ // timeless, snapshot, or pointer".
119
+ //
120
+ // Precision over recall: the quantity must sit NEXT TO the volatile noun ("965 Insights notes",
121
+ // "47 tasks"), not merely somewhere on the same line. A looser version reported 133 hits across 47
122
+ // notes — mostly ticket ids like ATL-3317 and MR numbers — which is a backlog nobody reads.
123
+ const VOLATILE =
124
+ '(?:tasks?|jobs?|tickets?|issues?|notes?|projects?|libs?|apps?|services?|clusters?|instances?|stacks?|alarms?|errors?|events?|requests?|users?|members?|commits?|branches?|files?|pairs?|gaps?|duplicates?)';
125
+ const COUNTED = new RegExp(
126
+ `(?<![-#!\\w/.])(?:~|about\\s+)?\\d{1,6}(?:,\\d{3})*\\s*%?\\s+(?:\\w+\\s+){0,2}${VOLATILE}\\b`,
127
+ 'i',
128
+ );
129
+ const PAST =
130
+ /\b(was|were|had|reached|hit|closed|shipped|merged|landed|dropped|ended|became|used to|previously|at the time)\b/i;
131
+ // Any ISO date on the line makes it a snapshot — "Measured **2026-08-08** … 501 projects" is a
132
+ // dated observation whether or not the date sits in the parenthesised house style.
133
+ const STAMPED = /\d{4}-\d{2}(-\d{2})?/;
134
+ const POINTER =
135
+ /\b(where truth lives|source of truth|read it from|query it|re-?run|check the MR|from the (?:API|dashboard))\b/i;
136
+
137
+ /** @param {string} line @returns {boolean} */
138
+ export function isUnstampedVolatileClaim(line) {
139
+ const t = line.trim();
140
+ if (!t || t.startsWith('|') || t.startsWith('>') || t.startsWith('_Also asked as')) return false;
141
+ if (/^#{1,6}\s/.test(t) || /^```/.test(t)) return false;
142
+ if (/^\w[\w-]*:\s/.test(t)) return false; // frontmatter key: value
143
+ if (STAMPED.test(t) || POINTER.test(t) || PAST.test(t)) return false; // dated, pointed, or history
144
+ return COUNTED.test(t.replace(/`[^`]*`/g, ' ')); // quoted code is never a claim
145
+ }
146
+
147
+ // CLAIM-1: a METRIC must name the instrument that produced it — three specific incidents this
148
+ // prevents, and why prose/an L1 note didn't, are in
149
+ // docs/decisions/2026-08-31-audit-check-provenance.md.
150
+ //
151
+ // Deliberately narrow. FRESH-1 already covers plain counts going stale; this covers the class that
152
+ // actually burned us — evaluative scores, which look authoritative precisely because they are
153
+ // specific. A bare count is a fact; a metric is a claim about a measurement.
154
+ // The metric word must sit NEXT TO a value. "Filename drift hides coverage" and "ALB coverage → the
155
+ // EDGE dashboard" use these words descriptively; only "recall@5 46.4%" or "MRR 0.289" is a claim
156
+ // about a measurement. First cut matched the word anywhere on a line containing any digit and was
157
+ // ~80% false positives — the same over-loose first draft as FRESH-1 (133 hits) and the supersession
158
+ // check (2 of 3). Assume a new check is miscalibrated until its output has been read line by line.
159
+ const METRIC =
160
+ /\b(recall(@\d+)?|precision|MRR|F1|accuracy|hit[- ]rate|error[- ]rate|p50|p90|p95|p99|latency|throughput|uptime)\b[^.;]{0,15}?\d|\d+(\.\d+)?\s*%?\s*(recall|precision|MRR|accuracy|uptime)\b/i;
161
+ // A target is not a measurement: "SLO: p90 latency < 2s" states an objective, and objectives do not
162
+ // need provenance — they need agreement.
163
+ const TARGET = /\b(SLO|SLA|objective|target|budget|threshold|goal|aim for|must stay)\b/i;
164
+ // Provenance = anything letting a reader re-run or locate the measurement: a script, a command, a
165
+ // case set, a dated "measured/verified", or an explicit sample size.
166
+ const PROVENANCE =
167
+ /(`[^`]*(?:\.mjs|\.py|\.sh|\.jsonl|--run|--mode|--cases)[^`]*`|\b(?:measur\w+|verified|benchmark(?:ed)?|case set|sample|question set|over \d+ (?:cases|questions|notes)|n\s*=\s*\d+)\b|\d{4}-\d{2}-\d{2})/i;
168
+
169
+ // `context` is the line plus its neighbours: a claim and its provenance routinely straddle a wrap
170
+ // ("On a versioned 28-case set:\n semantic **recall@5 46.4%**"), and flagging the second half of a
171
+ // properly-sourced sentence is noise.
172
+ /** @param {string} line @param {string} [context] @returns {boolean} */
173
+ export function isUnprovenancedMetric(line, context = line) {
174
+ const t = line.trim();
175
+ if (!t || t.startsWith('_Also asked as') || /^\w[\w-]*:\s/.test(t)) return false;
176
+ if (/^#{1,6}\s/.test(t) || /^```/.test(t) || t.startsWith('|')) return false;
177
+ if (!METRIC.test(t)) return false;
178
+ if (TARGET.test(t)) return false;
179
+ // Advice ABOUT metrics is not a claim OF one. "Store live metrics alongside the queries that
180
+ // produced them" is the same lesson this check enforces — flagging it is pure noise.
181
+ if (
182
+ IMPERATIVE.test(t) ||
183
+ /^[\s>*_#-]*(?:\*\*)?(?:comparing|storing|measuring|tracking|reporting)\b/i.test(t)
184
+ )
185
+ return false;
186
+ return !PROVENANCE.test(context);
187
+ }
188
+
189
+ // FRESH-4: a dated heading opens a snapshot region — everything under "## Measured 2026-08-08"
190
+ // claims what was true then, so it cannot rot. Region ends at the next heading of equal or higher
191
+ // level. Without this the lint flags every line of a measurement section.
192
+ /**
193
+ * @param {string} body
194
+ * @returns {{ line: number, text: string }[]}
195
+ */
196
+ export function freshnessFindings(body) {
197
+ /** @type {{ line: number, text: string }[]} */
198
+ const out = [];
199
+ for (const [line, i] of undatedLines(body))
200
+ if (isUnstampedVolatileClaim(line)) out.push({ line: i + 1, text: line.trim() });
201
+ return out;
202
+ }
203
+
204
+ /** @param {string} body @returns {Generator<[string, number]>} */
205
+ function* undatedLines(body) {
206
+ /** @type {number|null} */
207
+ let datedLevel = null;
208
+ for (const [i, line] of body.split('\n').entries()) {
209
+ const h = line.match(/^(#{1,6})\s+(.*)$/);
210
+ if (h) {
211
+ const level = h[1].length;
212
+ if (datedLevel !== null && level <= datedLevel) datedLevel = null;
213
+ if (/\d{4}-\d{2}(-\d{2})?/.test(h[2])) datedLevel = level;
214
+ continue;
215
+ }
216
+ if (datedLevel === null) yield [line, i];
217
+ }
218
+ }
219
+
220
+ // FRESH-2: an `as of` stamp older than its window.
221
+ const AS_OF = /\bas of (\d{4})-(\d{2})-(\d{2})\b/gi;
222
+ /**
223
+ * @param {string} body
224
+ * @param {number} windowDays
225
+ * @param {string} today YYYY-MM-DD
226
+ * @returns {{ line: number, date: string, age: number, text: string }[]}
227
+ */
228
+ export function staleStampFindings(body, windowDays, today) {
229
+ const day = (/** @type {string} */ y, /** @type {string} */ m, /** @type {string} */ d) =>
230
+ Date.UTC(+y, +m - 1, +d) / 864e5;
231
+ const now = day(.../** @type {[string, string, string]} */ (today.split('-')));
232
+ /** @type {{ line: number, date: string, age: number, text: string }[]} */
233
+ const out = [];
234
+ const lines = body.split('\n');
235
+ const masked = body.replace(FENCE, (b) => b.replace(/[^\n]/g, '')).replace(INLINE_CODE, '');
236
+ for (const [line, i] of undatedLines(masked))
237
+ for (const m of line.matchAll(AS_OF)) {
238
+ const age = now - day(m[1], m[2], m[3]);
239
+ if (age > windowDays)
240
+ out.push({ line: i + 1, date: `${m[1]}-${m[2]}-${m[3]}`, age, text: lines[i].trim() });
241
+ }
242
+ return out;
243
+ }
244
+
245
+ /**
246
+ * @param {Iterable<string>} paths
247
+ * @returns {Map<string, string[]>}
248
+ */
249
+ export function buildSuffixIndex(paths) {
250
+ const idx = new Map();
251
+ for (const t of paths)
252
+ for (let i = t.indexOf('/'); i !== -1; i = t.indexOf('/', i + 1)) {
253
+ const suf = t.slice(i + 1);
254
+ if (!idx.has(suf)) idx.set(suf, []);
255
+ /** @type {string[]} */ (idx.get(suf)).push(t);
256
+ }
257
+ return idx;
258
+ }
259
+
260
+ /**
261
+ * The newest commit that deleted or renamed each path, and the rename target. Paths git never saw
262
+ * are absent from the map, as is everything when git fails.
263
+ *
264
+ * @param {string} repo
265
+ * @param {string[]} wanted
266
+ * @returns {Map<string, { sha: string, to?: string }>}
267
+ */
268
+ export function pathFates(repo, wanted) {
269
+ /** @type {Map<string, { sha: string, to?: string }>} */
270
+ const fates = new Map();
271
+ if (!wanted.length) return fates;
272
+ /** @param {string[]} args */
273
+ const git = (args) =>
274
+ execFileSync('git', args, {
275
+ cwd: repo,
276
+ encoding: 'utf8',
277
+ stdio: ['ignore', 'pipe', 'ignore'],
278
+ maxBuffer: 256 * 1024 * 1024,
279
+ });
280
+ let prefix, log;
281
+ try {
282
+ prefix = git(['rev-parse', '--show-prefix']).trim();
283
+ // No pathspec and no --relative: either hides the rename target, and git reports the rename as D.
284
+ // ponytail: walks all history, add a --since bound if a large repo makes the audit slow
285
+ log = git(['log', '-M', '--diff-filter=DR', '--name-status', '--format=%x00%h']);
286
+ } catch {
287
+ return fates;
288
+ }
289
+ const want = new Map(wanted.map((w) => [prefix + w, w]));
290
+ let sha = '';
291
+ for (const line of log.split('\n')) {
292
+ if (line.startsWith('\0')) sha = line.slice(1);
293
+ const [status, from, to] = line.split('\t');
294
+ const w = want.get(from);
295
+ if (!w || fates.has(w)) continue;
296
+ fates.set(w, status.startsWith('R') ? { sha, to: path.posix.relative(prefix, to) } : { sha });
297
+ }
298
+ return fates;
299
+ }
300
+
301
+ /** @param {string} f @returns {string[]} */
302
+ export function checkFile(f) {
303
+ if (!fs.existsSync(f)) return [];
304
+ const raw = fs.readFileSync(f, 'utf8');
305
+ const lines = raw.split('\n');
306
+ /** @type {string[]} */
307
+ const out = [];
308
+ lines.forEach((l, n) => {
309
+ const ctx = lines.slice(Math.max(0, n - 2), n + 2).join(' ');
310
+ if (isUnprovenancedMetric(l, ctx))
311
+ out.push(
312
+ ` · line ${n + 1}: metric with no instrument named — cite the run, script, case set or date`,
313
+ );
314
+ });
315
+ for (const fr of freshnessFindings(raw))
316
+ out.push(
317
+ ` · line ${fr.line}: volatile quantity, no stamp — make it timeless, a dated snapshot, or a pointer`,
318
+ );
319
+ const s = supersessionState(raw);
320
+ if (s.inProse && !s.marked && !s.declared)
321
+ out.push(' · reversal stated in prose only — mark it: (superseded YYYY-MM-DD by [[note]])');
322
+ return out;
323
+ }
324
+
325
+ /** @param {string} d @returns {string[]} */
326
+ const noteNames = (d) => mdFiles(d).map((f) => path.basename(f, '.md'));
327
+
328
+ // Obsidian resolves a wikilink vault-wide, so a link into another project's notes is not dangling.
329
+ /**
330
+ * @param {string} vault @param {string} slug @param {Set<string>} local this project's note names
331
+ * @returns {(name: string) => 'here' | 'elsewhere' | null}
332
+ */
333
+ export function linkResolver(vault, slug, local) {
334
+ const permanent = new Set(noteNames(path.join(vault, 'permanent')));
335
+ const elsewhere = new Set();
336
+ for (const layer of ['Memory', 'Insights']) {
337
+ const root = path.join(vault, layer);
338
+ if (!fs.existsSync(root)) continue;
339
+ for (const e of fs.readdirSync(root, { withFileTypes: true }))
340
+ if (e.isDirectory() && e.name !== slug)
341
+ for (const n of noteNames(path.join(root, e.name))) if (n !== 'MEMORY') elsewhere.add(n);
342
+ }
343
+ return (n) => (local.has(n) || permanent.has(n) ? 'here' : elsewhere.has(n) ? 'elsewhere' : null);
344
+ }