@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.
- package/LICENSE +21 -0
- package/README.md +412 -2
- package/hooks/distill-session.mjs +74 -0
- package/hooks/graph-staleness-check.mjs +25 -0
- package/hooks/hooks.json +94 -0
- package/hooks/insights-surface.mjs +48 -0
- package/hooks/lib/distill-session.mjs +1560 -0
- package/hooks/lib/dupe-report.mjs +61 -0
- package/hooks/lib/env-shell.mjs +92 -0
- package/hooks/lib/graph-staleness-check.mjs +394 -0
- package/hooks/lib/hook-io.mjs +715 -0
- package/hooks/lib/insights-surface.mjs +165 -0
- package/hooks/lib/memory-link-lint.mjs +499 -0
- package/hooks/lib/memory-recall.mjs +219 -0
- package/hooks/lib/omp.mjs +103 -0
- package/hooks/lib/opencode.mjs +231 -0
- package/hooks/lib/paths.mjs +452 -0
- package/hooks/lib/semantic-index-refresh.mjs +155 -0
- package/hooks/lib/validate-note.mjs +218 -0
- package/hooks/lib/vault-env.sh +110 -0
- package/hooks/memory-link-lint.mjs +65 -0
- package/hooks/memory-recall.mjs +251 -0
- package/hooks/semantic-index-refresh.mjs +23 -0
- package/hooks/session-context.mjs +9 -0
- package/hooks/validate-note.mjs +52 -0
- package/hooks/vault-memory-sync.sh +154 -0
- package/omp/index.js +1 -0
- package/opencode/index.js +1 -0
- package/package.json +51 -4
- package/scripts/claude-memory.mjs +31 -0
- package/scripts/doctor-perf.mjs +121 -0
- package/scripts/doctor.sh +558 -0
- package/scripts/env.mjs +6 -0
- package/scripts/lib/claude-memory.mjs +168 -0
- package/scripts/lib/doctor-perf.mjs +434 -0
- package/scripts/lib/hook-stats.mjs +864 -0
- package/scripts/lib/lexical.mjs +85 -0
- package/scripts/lib/memory-adopt.mjs +69 -0
- package/scripts/lib/memory-audit-checks.mjs +344 -0
- package/scripts/lib/memory-eval.mjs +381 -0
- package/scripts/lib/memory-mark.mjs +135 -0
- package/scripts/lib/memory-mcp.mjs +142 -0
- package/scripts/lib/memory-merge.mjs +316 -0
- package/scripts/lib/memory-mine.mjs +108 -0
- package/scripts/lib/memory-promote.mjs +207 -0
- package/scripts/lib/memory-prune.mjs +84 -0
- package/scripts/lib/memory-semantic.mjs +999 -0
- package/scripts/lib/memory-setup.mjs +170 -0
- package/scripts/lib/memory-synth-vault.mjs +538 -0
- package/scripts/lib/model-default.mjs +7 -0
- package/scripts/lib/models.mjs +58 -0
- package/scripts/lib/prune-logs.mjs +130 -0
- package/scripts/lib/recall-stats.mjs +354 -0
- package/scripts/lib/share-modules.mjs +70 -0
- package/scripts/lib/slim-install.mjs +162 -0
- package/scripts/lib/vault-mcp.mjs +405 -0
- package/scripts/memory-adopt.mjs +160 -0
- package/scripts/memory-audit-checks.mjs +375 -0
- package/scripts/memory-eval.mjs +753 -0
- package/scripts/memory-mark.mjs +39 -0
- package/scripts/memory-mcp.mjs +35 -0
- package/scripts/memory-merge.mjs +55 -0
- package/scripts/memory-prune.mjs +44 -0
- package/scripts/memory-semantic.mjs +1192 -0
- package/scripts/memory-setup.mjs +33 -0
- package/scripts/memory-synth-vault.mjs +251 -0
- package/scripts/prune-logs.mjs +42 -0
- package/scripts/share-modules.mjs +79 -0
- package/scripts/slim-install.mjs +55 -0
- package/scripts/vault-mcp.mjs +50 -0
- package/stubs/onnxruntime-web/index.mjs +11 -0
- package/stubs/onnxruntime-web/package.json +12 -0
- package/stubs/sharp/index.mjs +11 -0
- package/stubs/sharp/package.json +12 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Logic half; the CLI entry is scripts/memory-eval.mjs. Flags and worked examples: commands/eval.md.
|
|
3
|
+
// Score a retrieval change against THE SAME cases every time — why a versioned set replaced
|
|
4
|
+
// hand-written questions: docs/decisions/2026-08-24-eval-harness-design.md.
|
|
5
|
+
//
|
|
6
|
+
// Case sets live under $CLAUDE_MEMORY_HOME/eval/ and are GITIGNORED: they contain vault content.
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { bm25, lexTokens } from './lexical.mjs';
|
|
10
|
+
import { MAX_NOTES, semanticArm } from '../../hooks/lib/memory-recall.mjs';
|
|
11
|
+
import { fileQuery } from '../../hooks/lib/paths.mjs';
|
|
12
|
+
import { redirect } from './memory-merge.mjs';
|
|
13
|
+
|
|
14
|
+
export const RECALL_KS = [1, 3, 5, 10];
|
|
15
|
+
|
|
16
|
+
/** @typedef {{ note: string, text: string }} EvalDoc */
|
|
17
|
+
/** @typedef {{ note: string, score: number }} RankedNote */
|
|
18
|
+
/** @typedef {{ q: string, results: RankedNote[] }} RankedQuery */
|
|
19
|
+
|
|
20
|
+
// ---------------------------------------------------------------- pure helpers (self-tested)
|
|
21
|
+
|
|
22
|
+
/** @param {string} stem @returns {Set<string>} */
|
|
23
|
+
export function titleTokens(stem) {
|
|
24
|
+
return new Set(
|
|
25
|
+
stem
|
|
26
|
+
.toLowerCase()
|
|
27
|
+
.replace(/^\d{4}-\d{2}-\d{2}-/, '')
|
|
28
|
+
.split(/[^a-z0-9]+/)
|
|
29
|
+
.filter((w) => w.length > 3),
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Strip everything that would leak the answer's own vocabulary or isn't prose: frontmatter,
|
|
34
|
+
// headings, code fences, wikilinks — and critically the `_Also asked as:` line, which is a list of
|
|
35
|
+
// queries the note was written to match. Generating a question from it would score our own aliases.
|
|
36
|
+
/** @param {string} raw @returns {string} */
|
|
37
|
+
export function evalBody(raw) {
|
|
38
|
+
let t = raw.replace(/^---\n[\s\S]*?\n---\n?/, '');
|
|
39
|
+
t = t.replace(/```[\s\S]*?```/g, ' ');
|
|
40
|
+
t = t.replace(/^_Also asked as:[\s\S]*$/m, ' ');
|
|
41
|
+
t = t.replace(/^#{1,6} .*$/gm, ' ');
|
|
42
|
+
t = t.replace(/\[\[([^\]|]+)(\|[^\]]*)?\]\]/g, ' ');
|
|
43
|
+
t = t.replace(/`[^`]*`/g, ' ');
|
|
44
|
+
return t;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A paraphrase must not reuse the note's title words, or it degenerates into a keyword lookup that
|
|
48
|
+
// every channel scores well.
|
|
49
|
+
/**
|
|
50
|
+
* @param {string} body
|
|
51
|
+
* @param {string} stem
|
|
52
|
+
* @param {string} style
|
|
53
|
+
* @returns {string|null}
|
|
54
|
+
*/
|
|
55
|
+
export function pickSentence(body, stem, style) {
|
|
56
|
+
const tt = titleTokens(stem);
|
|
57
|
+
const sents = body
|
|
58
|
+
.split(/(?<=[.!?])\s+|\n{2,}/)
|
|
59
|
+
.map((s) => s.replace(/\s+/g, ' ').trim())
|
|
60
|
+
.filter((s) => s.length >= 40 && s.length <= 220 && /[a-z]/.test(s));
|
|
61
|
+
if (!sents.length) return null;
|
|
62
|
+
/** @param {string} s @returns {number} */
|
|
63
|
+
const score = (s) => {
|
|
64
|
+
const toks = new Set(
|
|
65
|
+
s
|
|
66
|
+
.toLowerCase()
|
|
67
|
+
.split(/[^a-z0-9]+/)
|
|
68
|
+
.filter((w) => w.length > 3),
|
|
69
|
+
);
|
|
70
|
+
let overlap = 0;
|
|
71
|
+
for (const w of toks) if (tt.has(w)) overlap++;
|
|
72
|
+
return style === 'keyword' ? overlap : -overlap; // keyword wants the title words, semantic avoids them
|
|
73
|
+
};
|
|
74
|
+
return sents.sort((a, b) => score(b) - score(a) || b.length - a.length)[0];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The keyword baseline for `--run --mode lexical`. It scores WHOLE NOTES, so it is NOT a model of
|
|
78
|
+
// the recall hook, which scores only the `(card)` chunk — the two disagreed 50%/25% against
|
|
79
|
+
// 100%/100%. k1/b are passed explicitly so a change to bm25()'s defaults cannot move this in
|
|
80
|
+
// silence. Both, with the numbers: docs/decisions/2026-08-24-eval-harness-design.md.
|
|
81
|
+
/**
|
|
82
|
+
* @param {readonly EvalDoc[]} docs
|
|
83
|
+
* @param {readonly string[]} queries
|
|
84
|
+
* @param {number} k
|
|
85
|
+
* @returns {RankedQuery[]}
|
|
86
|
+
*/
|
|
87
|
+
export function lexicalRank(docs, queries, k) {
|
|
88
|
+
const scored = docs.map((d) => ({ note: d.note, toks: lexTokens(d.text) }));
|
|
89
|
+
return queries.map((q) => {
|
|
90
|
+
const s = bm25(scored, [...new Set(lexTokens(q))], 1.2, 0.75);
|
|
91
|
+
return {
|
|
92
|
+
q,
|
|
93
|
+
results: scored
|
|
94
|
+
.map((d, i) => ({ note: d.note, score: s[i] }))
|
|
95
|
+
.sort((a, b) => b.score - a.score)
|
|
96
|
+
.slice(0, k),
|
|
97
|
+
};
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// An unscorable case scores as an ordinary miss: dropping it would let the figure improve because
|
|
102
|
+
// the instrument broke. So it is never flattered, only diluted — which is why the caller reports
|
|
103
|
+
// and blocks on them separately instead of leaving the percentage to carry the news.
|
|
104
|
+
/**
|
|
105
|
+
* @param {readonly { rank: number }[]} perCase
|
|
106
|
+
* @returns {{ recall: Record<number, number>, mrr: number }}
|
|
107
|
+
*/
|
|
108
|
+
export function metrics(perCase) {
|
|
109
|
+
const n = perCase.length || 1;
|
|
110
|
+
/** @type {Record<number, number>} */
|
|
111
|
+
const recall = {};
|
|
112
|
+
for (const k of RECALL_KS)
|
|
113
|
+
recall[k] = perCase.filter((c) => c.rank > 0 && c.rank <= k).length / n;
|
|
114
|
+
const mrr = perCase.reduce((a, c) => a + (c.rank ? 1 / c.rank : 0), 0) / n;
|
|
115
|
+
return { recall, mrr };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// The ONE place a case-set filename is built — never rebuild it, including in a message that quotes
|
|
119
|
+
// a path. Slug-scoped because $CLAUDE_MEMORY_HOME/eval/ is shared by every project on the machine;
|
|
120
|
+
// the `-heldout` suffix is empty for a tuning set so existing ones need no migration.
|
|
121
|
+
// docs/decisions/2026-08-24-eval-harness-design.md.
|
|
122
|
+
/**
|
|
123
|
+
* @param {string} dir
|
|
124
|
+
* @param {string} slug
|
|
125
|
+
* @param {string} style
|
|
126
|
+
* @param {string} [kind]
|
|
127
|
+
* @returns {string}
|
|
128
|
+
*/
|
|
129
|
+
export function defaultCasesPath(dir, slug, style, kind = KIND.tuning) {
|
|
130
|
+
// `kindOfPath` reads the kind off the suffix, so `--style heldout` would build
|
|
131
|
+
// `eval-cases-<slug>-heldout.jsonl` — a TUNING set that reports as held-out. Refusing the style is
|
|
132
|
+
// cheaper than making the reader reconstruct slug and style from a path it is only given whole.
|
|
133
|
+
if (`-${style}`.endsWith(HELD_OUT_SUFFIX.replace('.jsonl', '')))
|
|
134
|
+
throw new Error(`--style "${style}" would mislabel a tuning set as held-out`);
|
|
135
|
+
// Throwing, not defaulting: `--kind holdout` silently scoring the TUNING set would report a
|
|
136
|
+
// number the operator reads as held out, which is worse than no number at all.
|
|
137
|
+
if (kind !== KIND.tuning && kind !== KIND.heldOut)
|
|
138
|
+
throw new Error(`unknown case-set kind ${kind} — use ${KIND.tuning} or ${KIND.heldOut}`);
|
|
139
|
+
return kind === KIND.heldOut
|
|
140
|
+
? path.join(dir, `eval-cases-${slug}-${style}${HELD_OUT_SUFFIX}`)
|
|
141
|
+
: path.join(dir, `eval-cases-${slug}-${style}.jsonl`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The verdicts goldCoverage() decides. A constant, not a literal: a copy in the producer and
|
|
145
|
+
// another in the branch that reads it drift apart in silence, and every test written against the
|
|
146
|
+
// copy stays green while the branch goes dead.
|
|
147
|
+
export const GOLD = /** @type {const} */ ({
|
|
148
|
+
ok: 'ok',
|
|
149
|
+
churn: 'churn',
|
|
150
|
+
mismatch: 'mismatch',
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// Below this fraction of gold notes resolving, the case set is not measuring this vault at all. Low
|
|
154
|
+
// on purpose: it separates a mismatched CORPUS from ordinary churn and nothing else.
|
|
155
|
+
export const GOLD_FLOOR = 0.5;
|
|
156
|
+
|
|
157
|
+
// A case set built from a DIFFERENT vault scored a confident 0% instead of erroring (#97). A
|
|
158
|
+
// FRACTION, not "any miss", because `permanent/` notes are cross-project. The refusal reports counts
|
|
159
|
+
// and never note names — they may belong to another project's private vault.
|
|
160
|
+
// docs/decisions/2026-08-24-eval-harness-design.md.
|
|
161
|
+
/**
|
|
162
|
+
* `gold` is `unknown` because this is the boundary that checks a JSON.parse claim.
|
|
163
|
+
* @param {readonly { gold?: unknown }[]} cases
|
|
164
|
+
* @param {ReadonlySet<string>} known
|
|
165
|
+
* @returns {{ total: number, resolved: number, verdict: 'ok'|'churn'|'mismatch' }}
|
|
166
|
+
*/
|
|
167
|
+
export function goldCoverage(cases, known) {
|
|
168
|
+
// Array-guarded: a line with no `gold` key flatMapped to `undefined` and counted as an
|
|
169
|
+
// unresolvable ref, so a malformed file reported as another vault's.
|
|
170
|
+
const gold = cases.flatMap((c) => (Array.isArray(c.gold) ? c.gold : []));
|
|
171
|
+
const resolved = gold.filter((g) => known.has(g)).length;
|
|
172
|
+
// A set with no gold at all is a mismatch on purpose, not an accident of NaN comparing false.
|
|
173
|
+
const fraction = gold.length ? resolved / gold.length : 0;
|
|
174
|
+
return {
|
|
175
|
+
total: gold.length,
|
|
176
|
+
resolved,
|
|
177
|
+
verdict: fraction === 1 ? GOLD.ok : fraction >= GOLD_FLOOR ? GOLD.churn : GOLD.mismatch,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ---------------------------------------------------------------- set kind, gate, pairwise (#87)
|
|
182
|
+
|
|
183
|
+
// The distinction is only worth anything if it is mechanical, so it lives in the FILENAME.
|
|
184
|
+
export const KIND = /** @type {const} */ ({ tuning: 'tuning', heldOut: 'held-out' });
|
|
185
|
+
|
|
186
|
+
const HELD_OUT_SUFFIX = '-heldout.jsonl';
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The kind of the case set actually being read, from its resolved path.
|
|
190
|
+
*
|
|
191
|
+
* The suffix is the whole test, which is why `--style` may not end in it — see `defaultCasesPath`.
|
|
192
|
+
*
|
|
193
|
+
* @param {string} p
|
|
194
|
+
* @returns {string}
|
|
195
|
+
*/
|
|
196
|
+
export function kindOfPath(p) {
|
|
197
|
+
return p.endsWith(HELD_OUT_SUFFIX) ? KIND.heldOut : KIND.tuning;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// A broken instrument, not a bad result — which is why the gate blocks on these.
|
|
201
|
+
export const UNSCORABLE = /** @type {const} */ ({
|
|
202
|
+
gold: 'a gold or owner note named by this case is not in the vault',
|
|
203
|
+
empty: 'retrieval returned nothing for this question',
|
|
204
|
+
score: 'a returned result carries a non-finite score',
|
|
205
|
+
noGold: 'this case names no gold note at all',
|
|
206
|
+
tied: 'every returned result scored the same, so the order is arrival order, not a ranking',
|
|
207
|
+
merged: 'the owner and a gold note were merged into one note, so the case asserts nothing',
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Can this case yield a number at all? Null means yes — including "yes, and the gold note lost".
|
|
212
|
+
*
|
|
213
|
+
* @param {{ gold?: unknown, owner?: unknown, type?: string }} c
|
|
214
|
+
* @param {readonly { note: string, score?: number }[]} results
|
|
215
|
+
* @param {ReadonlySet<string>} known
|
|
216
|
+
* @returns {string|null}
|
|
217
|
+
*/
|
|
218
|
+
export function unscorableReason(c, results, known) {
|
|
219
|
+
const badScore = results.some((r) => r.score !== undefined && !Number.isFinite(r.score));
|
|
220
|
+
if (c.type === TYPE.abstain) return badScore ? UNSCORABLE.score : null;
|
|
221
|
+
if (!results.length) return UNSCORABLE.empty;
|
|
222
|
+
if (badScore) return UNSCORABLE.score;
|
|
223
|
+
// A tie end to end is arrival order, not a ranking — `--mode lexical` returns k results all
|
|
224
|
+
// scoring 0 for a question matching nothing, which the two arms above cannot see.
|
|
225
|
+
const scores = results.map((r) => r.score).filter((x) => x !== undefined);
|
|
226
|
+
if (scores.length > 1 && scores.every((x) => x === scores[0])) return UNSCORABLE.tied;
|
|
227
|
+
// `gold` is a disjunction — `c.gold.includes()` hits on ANY member — so one surviving member
|
|
228
|
+
// leaves the case scorable. `owner` is one ref, so losing it loses the assertion.
|
|
229
|
+
const gold = Array.isArray(c.gold) ? c.gold : [];
|
|
230
|
+
if (!gold.length) return UNSCORABLE.noGold;
|
|
231
|
+
if (!gold.some((g) => known.has(g))) return UNSCORABLE.gold;
|
|
232
|
+
if (c.owner && !known.has(String(c.owner))) return UNSCORABLE.gold;
|
|
233
|
+
if (c.owner && gold.includes(c.owner)) return UNSCORABLE.merged;
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* A pairwise case: the question belongs to `owner`, and `gold` names the note that must NOT win it.
|
|
239
|
+
*
|
|
240
|
+
* The owner must be FOUND, not merely ahead, or a question matching nothing passes. `named` is at
|
|
241
|
+
* most Infinity, so the sentinel enforces that and no extra guard is needed.
|
|
242
|
+
*
|
|
243
|
+
* @param {{ gold: readonly string[], owner: string }} c
|
|
244
|
+
* @param {readonly { note: string }[]} results
|
|
245
|
+
* @returns {{ owner: number, named: number, pass: boolean }}
|
|
246
|
+
*/
|
|
247
|
+
export function pairwise(c, results) {
|
|
248
|
+
/** @param {string} n @returns {number} */
|
|
249
|
+
const rankOf = (n) => {
|
|
250
|
+
const i = results.findIndex((r) => r.note === n);
|
|
251
|
+
return i < 0 ? Infinity : i + 1;
|
|
252
|
+
};
|
|
253
|
+
const owner = rankOf(c.owner);
|
|
254
|
+
const named = Math.min(...c.gold.map(rankOf), Infinity);
|
|
255
|
+
return { owner, named, pass: owner < named };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// A case's `type` field; absent is a plain recall or pairwise case. Not `KIND`: that is the set's
|
|
259
|
+
// tuning/held-out label, and either kind of set may carry either type.
|
|
260
|
+
export const TYPE = /** @type {const} */ ({ supersede: 'supersede', abstain: 'abstain' });
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Would the recall hook stay silent on these results? Its own gate, imported, because MIN_COS is
|
|
264
|
+
* cosine-scaled and only the semantic arm's scores are cosine. Sliced to MAX_NOTES because that is
|
|
265
|
+
* the `k` the hook asks the server for; a deeper hit over the gate is one the hook never sees.
|
|
266
|
+
* Null from semanticArm() means empty results, i.e. an empty index, where keywordArm() abstains.
|
|
267
|
+
*
|
|
268
|
+
* @param {readonly { note: string, score?: number }[]} results
|
|
269
|
+
* @returns {boolean}
|
|
270
|
+
*/
|
|
271
|
+
export const abstains = (results) => !injectedNotes(results).length;
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The notes the hook's semantic arm would inject, in order — its gate, cap and character budget.
|
|
275
|
+
*
|
|
276
|
+
* @param {readonly { note: string, score?: number, text?: string }[]} results
|
|
277
|
+
* @returns {string[]}
|
|
278
|
+
*/
|
|
279
|
+
export function injectedNotes(results) {
|
|
280
|
+
const hits = results.slice(0, MAX_NOTES).map((r) => ({ layer: '', ...r }));
|
|
281
|
+
const e = semanticArm(hits)?.entry;
|
|
282
|
+
return e && !e.abstained ? (e.notes ?? []).slice(0, e.injected) : [];
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Precision is averaged over cases that inject anything; false injection is over cases with no
|
|
287
|
+
* relevant note at all (#226). Null precision means nothing was injected, not zero.
|
|
288
|
+
*
|
|
289
|
+
* @param {readonly { relevant: readonly string[], injected: readonly string[] }[]} rows
|
|
290
|
+
*/
|
|
291
|
+
export function injection(rows) {
|
|
292
|
+
const spoke = rows.filter((r) => r.injected.length);
|
|
293
|
+
const hits = spoke.map((r) => r.injected.filter((n) => r.relevant.includes(n)).length);
|
|
294
|
+
const none = rows.filter((r) => !r.relevant.length);
|
|
295
|
+
return {
|
|
296
|
+
injecting: spoke.length,
|
|
297
|
+
precision: spoke.length
|
|
298
|
+
? spoke.reduce((a, r, i) => a + hits[i] / r.injected.length, 0) / spoke.length
|
|
299
|
+
: null,
|
|
300
|
+
relevantInjected: hits.reduce((a, b) => a + b, 0),
|
|
301
|
+
injected: spoke.reduce((a, r) => a + r.injected.length, 0),
|
|
302
|
+
noRelevant: none.length,
|
|
303
|
+
falseInjections: none.filter((r) => r.injected.length).length,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* A case's query: its question, or the file-scoped query for a case that names a `file`.
|
|
309
|
+
*
|
|
310
|
+
* @param {{ q?: unknown, file?: unknown }} c
|
|
311
|
+
* @param {string} repo
|
|
312
|
+
* @returns {unknown}
|
|
313
|
+
*/
|
|
314
|
+
export const caseQuery = (c, repo) =>
|
|
315
|
+
typeof c.file === 'string' && c.q === undefined ? fileQuery(c.file, repo) : c.q;
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* The accept/reject rule, as a list of reasons to reject. Empty means accept.
|
|
319
|
+
*
|
|
320
|
+
* Opt-in: `--run` with no floor prints a number and exits 0, as every existing caller expects.
|
|
321
|
+
* Soft, not strict-improvement: ungated lost 52.8 pts. docs/decisions/2026-09-04-eval-gate.md.
|
|
322
|
+
*
|
|
323
|
+
* @param {{ recall1: number, minRank1: number|null, unscorable: number, pairFails: number,
|
|
324
|
+
* recallCases: number }} x
|
|
325
|
+
* @returns {string[]}
|
|
326
|
+
*/
|
|
327
|
+
export function gateFailures({ recall1, minRank1, unscorable, pairFails, recallCases }) {
|
|
328
|
+
const out = [];
|
|
329
|
+
// An assertion, not a metric: it fails with or without a floor.
|
|
330
|
+
if (pairFails) out.push(`${pairFails} pairwise case(s) failed: the owner did not outrank`);
|
|
331
|
+
// Unscorable blocks only under a floor: goldCoverage's `churn` band has always warned about a
|
|
332
|
+
// pruned gold note and scored past it, and refusing that unprompted breaks every plain `--run`.
|
|
333
|
+
if (minRank1 == null) return out;
|
|
334
|
+
if (unscorable)
|
|
335
|
+
out.push(`${unscorable} unscorable case(s) — the set did not measure them, so it did not pass`);
|
|
336
|
+
// metrics() divides by `|| 1`, so an all-pairwise set compared the floor against a 0 nothing
|
|
337
|
+
// had measured. A floor over an empty population is not a low score.
|
|
338
|
+
if (!recallCases) return out;
|
|
339
|
+
if (recall1 < minRank1)
|
|
340
|
+
out.push(
|
|
341
|
+
`recall@1 ${(recall1 * 100).toFixed(1)}% is below the floor ${(minRank1 * 100).toFixed(1)}%`,
|
|
342
|
+
);
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* The identity of a case set, publishable where its contents are not.
|
|
348
|
+
*
|
|
349
|
+
* The set stays machine-local (vault content), so the hash is what gets quoted. `trimEnd` so an
|
|
350
|
+
* editor's trailing newline is not a different set.
|
|
351
|
+
*
|
|
352
|
+
* @param {string} text
|
|
353
|
+
* @returns {string}
|
|
354
|
+
*/
|
|
355
|
+
export function casesHash(text) {
|
|
356
|
+
return createHash('sha256').update(text.replace(/\r\n/g, '\n').trimEnd()).digest('hex');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Point each case's `gold` and `owner` at the note a merge folded them into, in place. Returns how
|
|
361
|
+
* many names moved.
|
|
362
|
+
*
|
|
363
|
+
* @param {{ gold: string[], owner?: string }[]} cases
|
|
364
|
+
* @param {ReadonlySet<string>} known
|
|
365
|
+
* @param {ReadonlyMap<string, string>} redirects
|
|
366
|
+
* @returns {number}
|
|
367
|
+
*/
|
|
368
|
+
export function followCases(cases, known, redirects) {
|
|
369
|
+
let followed = 0;
|
|
370
|
+
/** @param {string} n */
|
|
371
|
+
const follow = (n) => {
|
|
372
|
+
const to = redirect(n, known, redirects);
|
|
373
|
+
if (to !== n) followed++;
|
|
374
|
+
return to;
|
|
375
|
+
};
|
|
376
|
+
for (const c of cases) {
|
|
377
|
+
c.gold = c.gold.map(follow);
|
|
378
|
+
if (c.owner) c.owner = follow(String(c.owner));
|
|
379
|
+
}
|
|
380
|
+
return followed;
|
|
381
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Marking a note as manually adjudicated: `reconcile: manual` in its frontmatter, meaning the
|
|
2
|
+
// distiller must never auto-fold a later restatement into it.
|
|
3
|
+
//
|
|
4
|
+
// Logic half; the CLI entry is scripts/memory-mark.mjs. Not a flag on memory-semantic.mjs on
|
|
5
|
+
// purpose — docs/architecture.md, "Declined, and kept declined".
|
|
6
|
+
//
|
|
7
|
+
// Tests: node --test scripts/lib/memory-mark.test.mjs
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
const FIELD = 'reconcile: manual';
|
|
12
|
+
|
|
13
|
+
/** Matches the field as its OWN frontmatter line — never the same words in prose. */
|
|
14
|
+
const MARKED = /^reconcile:[ \t]*manual[ \t]*$/m;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The frontmatter block of a note, or null when it has none.
|
|
18
|
+
*
|
|
19
|
+
* @param {string} raw
|
|
20
|
+
* @returns {string | null}
|
|
21
|
+
*/
|
|
22
|
+
export function frontmatter(raw) {
|
|
23
|
+
const m = raw.match(/^---\n([\s\S]*?)\n---\n/);
|
|
24
|
+
return m ? m[1] : null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {string} raw
|
|
29
|
+
* @returns {boolean}
|
|
30
|
+
*/
|
|
31
|
+
export function isMarked(raw) {
|
|
32
|
+
const fm = frontmatter(raw);
|
|
33
|
+
return !!fm && MARKED.test(fm);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Is the note at `file` marked? Why the mark exists: docs/decisions/2026-08-23-embedding-reconcile.md.
|
|
38
|
+
* Unreadable fails OPEN — an unreadable note is not evidence of a human judgement.
|
|
39
|
+
*
|
|
40
|
+
* @param {string} file
|
|
41
|
+
* @returns {boolean}
|
|
42
|
+
*/
|
|
43
|
+
export function isManual(file) {
|
|
44
|
+
try {
|
|
45
|
+
return isMarked(fs.readFileSync(file, 'utf8'));
|
|
46
|
+
} catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The note's text with the mark added or removed, or null when it already reads that way.
|
|
53
|
+
*
|
|
54
|
+
* Returning null rather than identical text is what lets the caller report "already marked" instead
|
|
55
|
+
* of rewriting a file and claiming a change it did not make — the mtime alone would re-embed the
|
|
56
|
+
* note on the next incremental index.
|
|
57
|
+
*
|
|
58
|
+
* @param {string} raw
|
|
59
|
+
* @param {boolean} [want]
|
|
60
|
+
* @returns {string | null}
|
|
61
|
+
*/
|
|
62
|
+
export function applyMark(raw, want = true) {
|
|
63
|
+
const fm = frontmatter(raw);
|
|
64
|
+
if (fm === null) return null;
|
|
65
|
+
if (isMarked(raw) === want) return null;
|
|
66
|
+
return want
|
|
67
|
+
? raw.replace(/\n---\n/, `\n${FIELD}\n---\n`)
|
|
68
|
+
: raw.replace(/^reconcile:[ \t]*manual[ \t]*\n/m, '');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Find a note by NAME anywhere under the vault.
|
|
73
|
+
*
|
|
74
|
+
* Names are addressed rather than paths because names are unique vault-wide — the semantic index
|
|
75
|
+
* keys by filename stem — and because `--dupes`, the report a caller is reading these names out of,
|
|
76
|
+
* prints names and not paths.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} vault
|
|
79
|
+
* @param {string} name
|
|
80
|
+
* @returns {string | null}
|
|
81
|
+
*/
|
|
82
|
+
export function resolveNote(vault, name) {
|
|
83
|
+
if (name.endsWith('.md') && fs.existsSync(name)) return name;
|
|
84
|
+
const wanted = `${name.replace(/\.md$/, '')}.md`;
|
|
85
|
+
/** @type {string[]} */
|
|
86
|
+
const stack = [vault];
|
|
87
|
+
while (stack.length) {
|
|
88
|
+
const dir = /** @type {string} */ (stack.pop());
|
|
89
|
+
/** @type {fs.Dirent[]} */
|
|
90
|
+
let entries;
|
|
91
|
+
try {
|
|
92
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
93
|
+
} catch {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
for (const e of entries) {
|
|
97
|
+
const full = path.join(dir, e.name);
|
|
98
|
+
if (e.isDirectory()) stack.push(full);
|
|
99
|
+
else if (e.name === wanted) return full;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @typedef {{ name: string, file?: string, status: 'marked'|'unmarked'|'unchanged'|'missing'|'no-frontmatter' }} MarkResult */
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @param {string} vault
|
|
109
|
+
* @param {readonly string[]} names
|
|
110
|
+
* @param {boolean} [want]
|
|
111
|
+
* @returns {MarkResult[]}
|
|
112
|
+
*/
|
|
113
|
+
export function markNotes(vault, names, want = true) {
|
|
114
|
+
/** @type {MarkResult[]} */
|
|
115
|
+
const out = [];
|
|
116
|
+
for (const name of names) {
|
|
117
|
+
const file = resolveNote(vault, name);
|
|
118
|
+
if (!file) {
|
|
119
|
+
out.push({ name, status: 'missing' });
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const raw = fs.readFileSync(file, 'utf8');
|
|
123
|
+
const next = applyMark(raw, want);
|
|
124
|
+
if (next === null) {
|
|
125
|
+
// Refusing a note with no frontmatter rather than inventing a block: a note shaped unlike
|
|
126
|
+
// this vault's notes is not one to guess at, and a second writer corrupting the first's
|
|
127
|
+
// frontmatter is a whole class of bug this repo has already paid for.
|
|
128
|
+
out.push({ name, file, status: frontmatter(raw) === null ? 'no-frontmatter' : 'unchanged' });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
fs.writeFileSync(file, next);
|
|
132
|
+
out.push({ name, file, status: want ? 'marked' : 'unmarked' });
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Read-only stdio MCP server with one tool, memory_search: the hybrid ranking of
|
|
2
|
+
// `memory-semantic.mjs --query`, answered by the shared --serve process. Why stdio beside the HTTP
|
|
3
|
+
// vault-mcp, and why one tool: docs/decisions/2026-12-03-memory-mcp.md.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import readline from 'node:readline';
|
|
6
|
+
import { MODEL_KEY, indexedSlugs, isIndexedSlug } from './memory-semantic.mjs';
|
|
7
|
+
import { askServe, keywordSearch } from './vault-mcp.mjs';
|
|
8
|
+
|
|
9
|
+
export const VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
10
|
+
|
|
11
|
+
export const TOOL = {
|
|
12
|
+
name: 'memory_search',
|
|
13
|
+
description:
|
|
14
|
+
'Search the memory vault (facts, lessons, logs) with hybrid semantic + keyword recall. ' +
|
|
15
|
+
'Use the words the answer would be written in. One line per hit: score [layer] note — snippet. ' +
|
|
16
|
+
'slug defaults to the current project.',
|
|
17
|
+
inputSchema: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
query: { type: 'string' },
|
|
21
|
+
k: { type: 'integer', minimum: 1, maximum: 20, default: 5 },
|
|
22
|
+
slug: { type: 'string', description: 'Vault project key; defaults to this project' },
|
|
23
|
+
},
|
|
24
|
+
required: ['query'],
|
|
25
|
+
additionalProperties: false,
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** @param {{ note: string, layer: string, text?: string | null, score: number }[]} hits */
|
|
30
|
+
export function formatHits(hits) {
|
|
31
|
+
if (!hits.length) return 'no hits';
|
|
32
|
+
return hits
|
|
33
|
+
.map((h) => {
|
|
34
|
+
const snip = (h.text ?? '').replace(/\s+/g, ' ').trim().slice(0, 160);
|
|
35
|
+
return `${h.score} [${h.layer}] ${h.note} — ${snip}`;
|
|
36
|
+
})
|
|
37
|
+
.join('\n');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @typedef {{
|
|
42
|
+
* dbDir: string,
|
|
43
|
+
* sockPath: string,
|
|
44
|
+
* defaultSlug: () => string,
|
|
45
|
+
* readCards: (dbFile: string) => import('./vault-mcp.mjs').Card[],
|
|
46
|
+
* spawn: () => boolean,
|
|
47
|
+
* version?: string,
|
|
48
|
+
* }} McpOptions
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/** @param {McpOptions} o */
|
|
52
|
+
export function createRpc({ dbDir, sockPath, defaultSlug, readCards, spawn, version = '0.0.0' }) {
|
|
53
|
+
/** @param {string} text */
|
|
54
|
+
const fail = (text) => ({ content: [{ type: 'text', text }], isError: true });
|
|
55
|
+
|
|
56
|
+
/** @param {Record<string, any>} args */
|
|
57
|
+
async function search(args) {
|
|
58
|
+
const { query, k = 5 } = args;
|
|
59
|
+
if (typeof query !== 'string' || !query.trim()) return fail('query must be a non-empty string');
|
|
60
|
+
if (!Number.isInteger(k) || k < 1 || k > 20) return fail('k must be an integer from 1 to 20');
|
|
61
|
+
const slug = args.slug ?? defaultSlug();
|
|
62
|
+
if (!isIndexedSlug(dbDir, slug))
|
|
63
|
+
return fail(`no index for ${slug}. Indexed: ${indexedSlugs(dbDir).join(', ') || 'none'}`);
|
|
64
|
+
const sem = await askServe(sockPath, { q: query, k, slug }, 1500);
|
|
65
|
+
if (sem?.error) return fail(String(sem.error));
|
|
66
|
+
if (Array.isArray(sem?.results))
|
|
67
|
+
return { content: [{ type: 'text', text: formatHits(sem.results) }] };
|
|
68
|
+
const reason = spawn() ? 'search server unavailable' : 'could not start search server';
|
|
69
|
+
const hits = keywordSearch(
|
|
70
|
+
readCards(path.join(dbDir, `semantic-${slug}-${MODEL_KEY}.db`)),
|
|
71
|
+
query,
|
|
72
|
+
k,
|
|
73
|
+
);
|
|
74
|
+
const text = `keyword only: ${reason}\n${formatHits(hits)}`;
|
|
75
|
+
return { content: [{ type: 'text', text }] };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param {any} msg
|
|
80
|
+
* @returns {Promise<object | null>} null for a notification
|
|
81
|
+
*/
|
|
82
|
+
return async function handle(msg) {
|
|
83
|
+
const id = msg?.id;
|
|
84
|
+
if (
|
|
85
|
+
msg?.jsonrpc !== '2.0' ||
|
|
86
|
+
typeof msg.method !== 'string' ||
|
|
87
|
+
(id !== undefined && typeof id !== 'string' && !Number.isInteger(id))
|
|
88
|
+
)
|
|
89
|
+
return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'invalid request' } };
|
|
90
|
+
if (id === undefined) return null;
|
|
91
|
+
/** @param {number} code @param {string} message */
|
|
92
|
+
const error = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
|
|
93
|
+
const params = msg.params ?? {};
|
|
94
|
+
/** @type {object} */
|
|
95
|
+
let result;
|
|
96
|
+
if (msg.method === 'initialize') {
|
|
97
|
+
const asked = params.protocolVersion;
|
|
98
|
+
result = {
|
|
99
|
+
protocolVersion: VERSIONS.includes(asked) ? asked : VERSIONS[0],
|
|
100
|
+
capabilities: { tools: {} },
|
|
101
|
+
serverInfo: { name: 'claude-memory', version },
|
|
102
|
+
};
|
|
103
|
+
} else if (msg.method === 'ping') result = {};
|
|
104
|
+
else if (msg.method === 'tools/list') result = { tools: [TOOL] };
|
|
105
|
+
else if (msg.method === 'tools/call') {
|
|
106
|
+
if (params.name !== TOOL.name) return error(-32602, 'unknown tool');
|
|
107
|
+
const args = params.arguments === undefined ? {} : params.arguments;
|
|
108
|
+
if (!args || typeof args !== 'object' || Array.isArray(args))
|
|
109
|
+
return error(-32602, 'arguments must be an object');
|
|
110
|
+
try {
|
|
111
|
+
result = await search(args);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
result = fail(String(/** @type {Error} */ (e).message ?? e));
|
|
114
|
+
}
|
|
115
|
+
} else return error(-32601, 'method not found');
|
|
116
|
+
return { jsonrpc: '2.0', id, result };
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* @param {NodeJS.ReadableStream} input
|
|
122
|
+
* @param {NodeJS.WritableStream} output
|
|
123
|
+
* @param {McpOptions} opts
|
|
124
|
+
*/
|
|
125
|
+
export function serveStdio(input, output, opts) {
|
|
126
|
+
const handle = createRpc(opts);
|
|
127
|
+
const rl = readline.createInterface({ input });
|
|
128
|
+
rl.on('line', async (line) => {
|
|
129
|
+
if (!line.trim()) return;
|
|
130
|
+
let msg;
|
|
131
|
+
try {
|
|
132
|
+
msg = JSON.parse(line);
|
|
133
|
+
} catch {
|
|
134
|
+
const error = { code: -32700, message: 'parse error' };
|
|
135
|
+
output.write(JSON.stringify({ jsonrpc: '2.0', id: null, error }) + '\n');
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const reply = await handle(msg);
|
|
139
|
+
if (reply) output.write(JSON.stringify(reply) + '\n');
|
|
140
|
+
});
|
|
141
|
+
return rl;
|
|
142
|
+
}
|