@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,316 @@
1
+ // Merging duplicate vault notes into one survivor: /memory:prune step 2.
2
+ //
3
+ // Logic half; the CLI entry is scripts/memory-merge.mjs. Redundant notes MOVE to
4
+ // `<vault>/.trash/pruned-<date>/`, never unlink: auto mode refuses an unlink of a vault note.
5
+ //
6
+ // Tests: node --test scripts/lib/memory-merge.test.mjs
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { FENCE, INLINE_CODE, linkTargets } from '../../hooks/lib/memory-link-lint.mjs';
10
+ import { frontmatter } from './memory-mark.mjs';
11
+
12
+ const SKIP = new Set(['.git', '.trash']);
13
+ // Vault root, not `.trash/`: a redirect outlives an emptied trash, as the lesson lives on in the survivor.
14
+ export const REDIRECTS = '.merge-redirects.jsonl';
15
+ const ALIAS = /^_Also asked as: (.*?)\.?_[ \t]*$/m;
16
+
17
+ /** @param {string} s */
18
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
19
+
20
+ /** How Obsidian resolves a link target: `[[ Folder/Name.md ]]` is `name`. @param {string} t */
21
+ export const linkKey = (t) => path.basename(t.trim()).replace(/\.md$/i, '').toLowerCase();
22
+
23
+ /** `[[target`, in any form Obsidian resolves to `name`. @param {string} name */
24
+ const linkHead = (name) => `\\[\\[\\s*(?:[^\\]|#\\n]*/)?${esc(name)}(?:\\.md)?\\s*(?=[\\]|#])`;
25
+
26
+ /**
27
+ * Every note under the vault, by name. `.git` and `.trash` are not the vault.
28
+ *
29
+ * @param {string} vault
30
+ * @returns {Map<string, string[]>}
31
+ */
32
+ export function noteIndex(vault) {
33
+ /** @type {Map<string, string[]>} */
34
+ const out = new Map();
35
+ /** @type {string[]} */
36
+ const stack = [vault];
37
+ while (stack.length) {
38
+ const dir = /** @type {string} */ (stack.pop());
39
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
40
+ const full = path.join(dir, e.name);
41
+ if (e.isDirectory()) {
42
+ if (!SKIP.has(e.name)) stack.push(full);
43
+ } else if (e.name.endsWith('.md')) {
44
+ const name = e.name.slice(0, -3);
45
+ out.set(name, [...(out.get(name) ?? []), full]);
46
+ }
47
+ }
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /**
53
+ * @param {string} body
54
+ * @returns {string[]}
55
+ */
56
+ export function aliasesOf(body) {
57
+ const m = body.match(ALIAS);
58
+ return m
59
+ ? m[1]
60
+ .split(/,\s*/)
61
+ .map((s) => s.trim())
62
+ .filter(Boolean)
63
+ : [];
64
+ }
65
+
66
+ /**
67
+ * @param {string[][]} lists
68
+ * @returns {string[]}
69
+ */
70
+ function unionAliases(lists) {
71
+ /** @type {Map<string, string>} */
72
+ const seen = new Map();
73
+ for (const a of lists.flat()) if (!seen.has(a.toLowerCase())) seen.set(a.toLowerCase(), a);
74
+ return [...seen.values()];
75
+ }
76
+
77
+ /**
78
+ * @param {string} raw
79
+ * @returns {[string, string]}
80
+ */
81
+ function split(raw) {
82
+ const fm = /** @type {RegExpMatchArray} */ (raw.match(/^---\n[\s\S]*?\n---\n/))[0];
83
+ return [fm, raw.slice(fm.length)];
84
+ }
85
+
86
+ /**
87
+ * Every link to a `rename` key (lowercased) pointed at its value. Code is left alone, as Obsidian
88
+ * leaves it: a `[[x]]` inside backticks is not a link.
89
+ *
90
+ * @param {string} text
91
+ * @param {Map<string, string>} rename
92
+ * @returns {string}
93
+ */
94
+ export function rewriteLinks(text, rename) {
95
+ /** @type {[number, number][]} */
96
+ const code = [...text.matchAll(FENCE), ...text.matchAll(INLINE_CODE)].map((m) => [
97
+ /** @type {number} */ (m.index),
98
+ /** @type {number} */ (m.index) + m[0].length,
99
+ ]);
100
+ const re = new RegExp([...rename.keys()].map(linkHead).join('|'), 'gi');
101
+ return text.replace(re, (m, /** @type {number} */ at) =>
102
+ code.some(([a, b]) => at >= a && at < b) ? m : `[[${rename.get(linkKey(m.slice(2)))}`,
103
+ );
104
+ }
105
+
106
+ /**
107
+ * The survivor's links to itself, which a rewrite creates: the distiller's back-link and
108
+ * supersede marker, then any other `[[self]]` reduced to its text.
109
+ *
110
+ * @param {string} text
111
+ * @param {string} self
112
+ * @returns {string}
113
+ */
114
+ export function dropSelfLinks(text, self) {
115
+ const s = esc(self);
116
+ return text
117
+ .replace(new RegExp(`^[ \\t]*Supersedes a claim in \\[\\[${s}\\]\\]\\.[ \\t]*\\n`, 'gm'), '')
118
+ .replace(new RegExp(` ?Supersedes a claim in \\[\\[${s}\\]\\]\\.`, 'g'), '')
119
+ .replace(new RegExp(` by \\[\\[${s}\\]\\]`, 'g'), '')
120
+ .replace(
121
+ new RegExp(`${linkHead(self)}(?:#[^\\]|]*)?(?:\\|([^\\]]*))?\\]\\]`, 'gi'),
122
+ (_, label) => label ?? self,
123
+ )
124
+ .replace(/\n{3,}/g, '\n\n');
125
+ }
126
+
127
+ /**
128
+ * The survivor's new text: its body, each redundant body under a `**Merged**` line, then one
129
+ * alias line holding the union.
130
+ *
131
+ * @param {string} survivorRaw
132
+ * @param {{ name: string, raw: string }[]} redundant
133
+ * @returns {string}
134
+ */
135
+ export function mergeText(survivorRaw, redundant) {
136
+ const [fm, body] = split(survivorRaw);
137
+ const aliases = [aliasesOf(body)];
138
+ let out = body.replace(ALIAS, '').trimEnd() + '\n';
139
+ for (const r of redundant) {
140
+ const [rfm, rbody] = split(r.raw);
141
+ aliases.push(aliasesOf(rbody));
142
+ const title = rfm.match(/^title: "?(.*?)"?$/m)?.[1] || rbody.match(/^## (.*)$/m)?.[1] || r.name;
143
+ const date = rfm.match(/^date: (\S+)/m)?.[1] || r.name.match(/^\d{4}-\d{2}-\d{2}/)?.[0];
144
+ const text = rbody
145
+ .replace(/^## .*\n/m, '')
146
+ .replace(ALIAS, '')
147
+ .trim();
148
+ out += `\n**Merged ${date ? `${date} ` : ''}(${title}):**\n\n${text}\n`;
149
+ }
150
+ const union = unionAliases(aliases);
151
+ if (union.length) out += `\n_Also asked as: ${union.join(', ')}._\n`;
152
+ return fm + out;
153
+ }
154
+
155
+ /**
156
+ * @typedef {{ name: string, file: string }} Note
157
+ * @typedef {{ survivor: Note, redundant: Note[] }} Group
158
+ * @typedef {{ groups: Group[], edits: string[], moves: { from: string, to: string }[] }} Plan
159
+ */
160
+
161
+ /**
162
+ * Resolve and check the WHOLE plan before anything is written. Throws one error listing every
163
+ * problem: a missing or ambiguous name, a name used twice, a cross-folder group, a note with no
164
+ * frontmatter, or a trash path already taken.
165
+ *
166
+ * @param {string} vault
167
+ * @param {readonly (readonly string[])[]} groups `[survivor, ...redundant]` per group
168
+ * @param {string} today YYYY-MM-DD
169
+ * @returns {Plan}
170
+ */
171
+ export function planMerge(vault, groups, today) {
172
+ const index = noteIndex(vault);
173
+ /** @type {string[]} */
174
+ const errors = [];
175
+ /** @type {Set<string>} */
176
+ const used = new Set();
177
+ /** @param {string} arg @returns {Note | null} */
178
+ const resolve = (arg) => {
179
+ const name = path.basename(arg).replace(/\.md$/, '');
180
+ if (used.has(name)) errors.push(`named twice in the plan: ${name}`);
181
+ used.add(name);
182
+ const hits = index.get(name) ?? [];
183
+ if (hits.length !== 1) {
184
+ errors.push(`${hits.length ? 'ambiguous' : 'not found in the vault'}: ${name}`);
185
+ return null;
186
+ }
187
+ if (frontmatter(fs.readFileSync(hits[0], 'utf8')) === null)
188
+ errors.push(`no frontmatter, refusing to edit: ${hits[0]}`);
189
+ return { name, file: hits[0] };
190
+ };
191
+
192
+ /** @type {Group[]} */
193
+ const out = [];
194
+ const moves = [];
195
+ for (const g of groups) {
196
+ if (g.length < 2) {
197
+ errors.push(`a group needs a survivor and at least one redundant note: ${g.join(' ')}`);
198
+ continue;
199
+ }
200
+ const survivor = resolve(g[0]);
201
+ const redundant = g.slice(1).map(resolve);
202
+ if (!survivor || redundant.some((r) => !r)) continue;
203
+ const notes = /** @type {Note[]} */ (redundant);
204
+ for (const r of notes) {
205
+ if (path.dirname(r.file) !== path.dirname(survivor.file)) {
206
+ errors.push(`cross-folder, refusing: ${r.name} is not beside ${survivor.name}`);
207
+ continue;
208
+ }
209
+ const rel = path.relative(vault, path.dirname(r.file));
210
+ const to = path.join(vault, '.trash', `pruned-${today}`, rel, `${r.name}.md`);
211
+ if (fs.existsSync(to)) errors.push(`already in the trash, move it out first: ${to}`);
212
+ moves.push({ from: r.file, to });
213
+ }
214
+ out.push({ survivor, redundant: notes });
215
+ }
216
+ if (errors.length) throw new Error(errors.join('\n'));
217
+
218
+ const names = new Set(out.flatMap((g) => g.redundant.map((r) => r.name.toLowerCase())));
219
+ const gone = new Set(moves.map((m) => m.from));
220
+ const edits = new Set(out.map((g) => g.survivor.file));
221
+ for (const files of index.values())
222
+ for (const f of files) if (!gone.has(f) && linksTo(f, names)) edits.add(f);
223
+ return { groups: out, edits: [...edits], moves };
224
+ }
225
+
226
+ /** @param {string} file @param {Set<string>} names */
227
+ const linksTo = (file, names) =>
228
+ [...linkTargets(fs.readFileSync(file, 'utf8'))].some((t) => names.has(linkKey(t)));
229
+
230
+ /**
231
+ * Write the plan: fold each group into its survivor, point every inbound link at the survivor,
232
+ * move the redundant notes to the trash. Returns the files still linking to a moved note.
233
+ *
234
+ * @param {string} vault
235
+ * @param {Plan} plan
236
+ * @returns {string[]}
237
+ */
238
+ export function applyMerge(vault, plan) {
239
+ /** @type {Map<string, string>} */
240
+ const rename = new Map();
241
+ for (const g of plan.groups) {
242
+ const redundant = g.redundant.map((r) => ({ ...r, raw: fs.readFileSync(r.file, 'utf8') }));
243
+ fs.writeFileSync(
244
+ g.survivor.file,
245
+ mergeText(fs.readFileSync(g.survivor.file, 'utf8'), redundant),
246
+ );
247
+ for (const r of g.redundant) rename.set(r.name.toLowerCase(), g.survivor.name);
248
+ }
249
+ const survivors = new Map(plan.groups.map((g) => [g.survivor.file, g.survivor.name]));
250
+ for (const f of plan.edits) {
251
+ let text = rewriteLinks(fs.readFileSync(f, 'utf8'), rename);
252
+ const self = survivors.get(f);
253
+ if (self) text = dropSelfLinks(text, self);
254
+ fs.writeFileSync(f, text);
255
+ }
256
+ for (const m of plan.moves) {
257
+ fs.mkdirSync(path.dirname(m.to), { recursive: true });
258
+ fs.renameSync(m.from, m.to);
259
+ }
260
+ fs.appendFileSync(
261
+ path.join(vault, REDIRECTS),
262
+ plan.groups
263
+ .flatMap((g) =>
264
+ g.redundant.map((r) =>
265
+ JSON.stringify({
266
+ from: r.name,
267
+ to: g.survivor.name,
268
+ dir: path.relative(vault, path.dirname(r.file)),
269
+ }),
270
+ ),
271
+ )
272
+ .join('\n') + '\n',
273
+ );
274
+ const gone = new Set(rename.keys());
275
+ return [...noteIndex(vault).values()].flat().filter((f) => linksTo(f, gone));
276
+ }
277
+
278
+ /**
279
+ * Every merge so far, `from` → `to`. A later line for the same `from` wins. `dirs` keeps only
280
+ * merges made in those vault-relative folders: names are unique per vault only at merge time, so
281
+ * another project's later merge of the same name must not redirect this one's.
282
+ *
283
+ * @param {string} vault
284
+ * @param {ReadonlySet<string>} [dirs]
285
+ * @returns {Map<string, string>}
286
+ */
287
+ export function readRedirects(vault, dirs) {
288
+ /** @type {Map<string, string>} */
289
+ const out = new Map();
290
+ const file = path.join(vault, REDIRECTS);
291
+ if (!fs.existsSync(file)) return out;
292
+ for (const l of fs.readFileSync(file, 'utf8').split('\n').filter(Boolean)) {
293
+ try {
294
+ const { from, to, dir } = JSON.parse(l);
295
+ if (typeof from !== 'string' || typeof to !== 'string') continue;
296
+ if (!dirs || dirs.has(dir)) out.set(from, to);
297
+ } catch {}
298
+ }
299
+ return out;
300
+ }
301
+
302
+ /**
303
+ * A name that is no longer a note, followed through every merge to the note that holds it now.
304
+ * Unchanged when it is still a note or the chain ends nowhere, so a restored note wins.
305
+ *
306
+ * @param {string} name
307
+ * @param {ReadonlySet<string>} known
308
+ * @param {ReadonlyMap<string, string>} redirects
309
+ * @returns {string}
310
+ */
311
+ export function redirect(name, known, redirects) {
312
+ let n = name;
313
+ for (let i = 0; i < redirects.size && !known.has(n) && redirects.has(n); i++)
314
+ n = /** @type {string} */ (redirects.get(n));
315
+ return known.has(n) ? n : name;
316
+ }
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ // Candidate eval questions, mined from Claude Code transcripts. No entry twin: `--mine` is a mode of
3
+ // scripts/memory-eval.mjs, its only caller. Separate from memory-eval.mjs because it shares nothing
4
+ // with it — that file scores retrieval, this one parses an append log another program writes.
5
+ //
6
+ // Transcripts are the one source nobody could have fitted to a result: prompts typed months before
7
+ // any tuning run (#87). Under 15 chars is "ok", "do 1"; over 400 is a pasted log, a document rather
8
+ // than a question. The pool behind both bounds is dated once in
9
+ // docs/decisions/2026-08-24-eval-harness-design.md and grows with use, so re-run `--mine`.
10
+ export const MINE_MIN = 15;
11
+ export const MINE_MAX = 400;
12
+
13
+ // Plumbing, not speech: the harness threads tool results and reminders as user turns, and `Caveat:`
14
+ // is Claude Code's own resumed-session banner.
15
+ const MINE_NOISE = /Caveat:|tool_result|system-reminder/;
16
+
17
+ /**
18
+ * A parsed record -> the human's prompt, or null. Split from the line form so the caller can count
19
+ * TURNS without parsing twice; lines-as-turns overstates the pool by two orders of magnitude.
20
+ * @param {any} o
21
+ * @returns {string|null}
22
+ */
23
+ function mineTurn(o) {
24
+ const t = mineText(o);
25
+ if (t.length < MINE_MIN || t.length > MINE_MAX) return null;
26
+ // Leading character on purpose: `/memory:eval` is a harness instruction, "what does /memory:eval
27
+ // do" is a question, and only the position tells them apart. `<` opens an injected payload.
28
+ if (t.startsWith('/') || t.startsWith('<')) return null;
29
+ if (MINE_NOISE.test(t)) return null;
30
+ return t;
31
+ }
32
+
33
+ /**
34
+ * The speech in a record, normalised, or '' when it carries none. Empty is what separates a HUMAN
35
+ * turn from a tool result — both arrive as `type: user`, and counting tool results as turns
36
+ * overstated the pool tenfold.
37
+ * @param {any} o
38
+ * @returns {string}
39
+ */
40
+ function mineText(o) {
41
+ const c = o.message?.content;
42
+ // Content is a bare string on older transcripts and a content-block array on newer ones. Only
43
+ // `text` blocks are speech; a `tool_result` block in the same array is the harness talking.
44
+ const raw =
45
+ typeof c === 'string'
46
+ ? c
47
+ : Array.isArray(c)
48
+ ? c
49
+ .filter((p) => p?.type === 'text' && typeof p.text === 'string')
50
+ .map((p) => p.text)
51
+ .join(' ')
52
+ : '';
53
+ return raw.trim().replace(/\s+/g, ' ');
54
+ }
55
+
56
+ /**
57
+ * A human turn at all? The split makes the dropped count mean "a human said this and we rejected
58
+ * it" rather than "this file has assistant records in it".
59
+ * @param {any} o @returns {boolean}
60
+ */
61
+ const isUserTurn = (o) => o?.type === 'user' && !o.isMeta && mineText(o) !== '';
62
+
63
+ /**
64
+ * One JSONL line -> the human's prompt, or null. Null rather than a throw: an append log can be
65
+ * truncated mid-write, and one bad tail line must not cost the rest of the file.
66
+ * @param {string} line @returns {string|null}
67
+ */
68
+ export function minePrompt(line) {
69
+ const o = mineParse(line);
70
+ return o && isUserTurn(o) ? mineTurn(o) : null;
71
+ }
72
+
73
+ /** @param {string} line @returns {any} */
74
+ function mineParse(line) {
75
+ if (!line.trim()) return null;
76
+ try {
77
+ return JSON.parse(line);
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Fold transcript lines into a candidate set, deduplicating on the prompt text.
85
+ *
86
+ * `seen` is the caller's because deduplication has to span FOLDERS: the same sessions appear under
87
+ * more than one cwd-slug when a home directory is renamed. Two such folders yield 142 candidates
88
+ * each and 142 between them (2026-09-05), so a per-folder Set doubles the apparent pool.
89
+ * @param {Iterable<string>} lines
90
+ * @param {Set<string>} seen mutated
91
+ * @returns {{ lines: number, turns: number, kept: number }}
92
+ */
93
+ export function minePrompts(lines, seen) {
94
+ let count = 0,
95
+ turns = 0,
96
+ kept = 0;
97
+ for (const l of lines) {
98
+ count++;
99
+ const o = mineParse(l);
100
+ if (!o || !isUserTurn(o)) continue;
101
+ turns++;
102
+ const q = mineTurn(o);
103
+ if (!q || seen.has(q)) continue;
104
+ seen.add(q);
105
+ kept++;
106
+ }
107
+ return { lines: count, turns, kept };
108
+ }
@@ -0,0 +1,207 @@
1
+ // Staging proposals for the promotion step (#96): `--propose` in memory-semantic.mjs turns a
2
+ // consolidationGaps() result into a file under `<vault>/Staging/<slug>/`, sibling to `permanent/`,
3
+ // never inside it. Drafting the actual synthesis stays a human/LLM job for /memory:synthesize —
4
+ // this only emits the skeleton and the evidence that made the cluster a candidate.
5
+ //
6
+ // Logic half; the CLI entry is scripts/memory-semantic.mjs's --propose flag.
7
+ // Tests: node --test scripts/lib/memory-promote.test.mjs
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { checkDraftStatus } from './memory-adopt.mjs';
11
+
12
+ // Sentinel pair, same convention GRAPH_REPORT.md uses: everything after @generated:end is
13
+ // hand-maintained and a re-propose must carry it forward verbatim.
14
+ export const GEN_START =
15
+ '<!-- @generated:start — overwritten by --propose on rerun; do NOT hand-edit inside this block -->';
16
+ export const GEN_END = '<!-- @generated:end -->';
17
+
18
+ /** @param {string} vault @param {string} slug @returns {string} */
19
+ export function stagingDir(vault, slug) {
20
+ return path.join(vault, 'Staging', slug);
21
+ }
22
+
23
+ /**
24
+ * Deterministic candidate id: the alphabetically-first member's stem. Not a stable identity across
25
+ * reruns if cluster membership shifts — /memory:synthesize is instructed to `mv` the file to its
26
+ * real topic slug once drafted, so this name is temporary by design.
27
+ *
28
+ * @param {readonly { note: string }[]} members
29
+ * @returns {string}
30
+ */
31
+ export function proposalSlug(members) {
32
+ const first = [...members].map((m) => m.note).sort()[0];
33
+ return `candidate-${first}`;
34
+ }
35
+
36
+ /**
37
+ * @param {{ members: readonly { note: string, layer: string, mtime?: number }[], best: { note: string | null, s: number }, typical: number }} gap
38
+ * @param {string} slug
39
+ * @returns {string}
40
+ */
41
+ export function renderProposal(gap, slug) {
42
+ const created = new Date().toISOString().slice(0, 10);
43
+ const memberLines = gap.members
44
+ .slice()
45
+ .sort((a, b) => a.note.localeCompare(b.note))
46
+ .map((m) => ` - "[[${m.note}]] (${m.layer})"`)
47
+ .join('\n');
48
+ // Age is the third quantity the candidate rule can read off the cluster scan, alongside size and
49
+ // the permanent/ gap, without inventing an age THRESHOLD nobody has calibrated. NOT a content-edit
50
+ // date: the indexer's `mtime` column is the OS mtime at last index run, bumped on the "touched"
51
+ // fast path even when the hash proves content is byte-identical (a git clone/checkout/vault-sync
52
+ // resets it for every file at once) — labelled "touched", not "changed", so it isn't read as one.
53
+ // Omitted, not zero, when the caller has no mtime to give (e.g. a unit test fixture).
54
+ const oldestMtime = gap.members.reduce(
55
+ (min, m) => (m.mtime != null && (min == null || m.mtime < min) ? m.mtime : min),
56
+ /** @type {number | null} */ (null),
57
+ );
58
+ const front = [
59
+ '---',
60
+ 'type: promotion-candidate',
61
+ 'status: proposed',
62
+ `created: ${created}`,
63
+ `cluster_size: ${gap.members.length}`,
64
+ `best_permanent_match: ${gap.best.note ?? 'null'}`,
65
+ `best_permanent_score: ${gap.best.s.toFixed(3)}`,
66
+ `typical_member_score: ${gap.typical.toFixed(3)}`,
67
+ ...(oldestMtime == null
68
+ ? []
69
+ : [`oldest_member_touched: ${new Date(oldestMtime).toISOString().slice(0, 10)}`]),
70
+ 'members:',
71
+ memberLines,
72
+ '---',
73
+ ].join('\n');
74
+ const body = [
75
+ GEN_START,
76
+ '',
77
+ `## ${slug} — untitled promotion candidate`,
78
+ '',
79
+ '_Draft this with `/memory:synthesize` — cite every claim, mark unsourced synthesis explicitly.',
80
+ 'Add the permanent shape around this frontmatter (`type: permanent`, `confidence`, dates,',
81
+ '`_Also asked as:_`) when drafting, but KEEP the `members:` field byte-for-byte — it is how a',
82
+ 'later --propose recognises this proposal after it gets renamed, not something a reader needs.',
83
+ '/memory:adopt refuses a note still shaped like this one._',
84
+ '',
85
+ GEN_END,
86
+ '',
87
+ '## Notes (hand-maintained — survives regeneration)',
88
+ '',
89
+ ].join('\n');
90
+ return `${front}\n\n${body}`;
91
+ }
92
+
93
+ /**
94
+ * The note names a proposal's frontmatter `members:` list carries — order-independent identity for
95
+ * a cluster, so a proposal survives being renamed away from its `candidate-*` filename (see
96
+ * proposeStagingNotes: /memory:synthesize renames the file once drafted, and looking it up by name
97
+ * alone would miss it there).
98
+ * @param {string} raw
99
+ * @returns {Set<string>}
100
+ */
101
+ export function memberNamesOf(raw) {
102
+ const fm = raw.match(/^---\n([\s\S]*?)\n---\n/)?.[1] ?? '';
103
+ const names = new Set();
104
+ for (const m of fm.matchAll(/\[\[([^\]]+)\]\]/g)) names.add(m[1]);
105
+ return names;
106
+ }
107
+
108
+ /**
109
+ * Find whichever file in `dir` already covers this exact member set, whatever it's named — a
110
+ * renamed, drafted proposal for the same cluster included. Exact set equality only: a cluster whose
111
+ * membership has since changed is treated as a new candidate rather than guessed at.
112
+ * @param {string} dir
113
+ * @param {ReadonlySet<string>} wanted
114
+ * @returns {{ file: string, raw: string } | null}
115
+ */
116
+ export function findExistingProposal(dir, wanted) {
117
+ let names;
118
+ try {
119
+ names = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
120
+ } catch {
121
+ return null;
122
+ }
123
+ for (const file of names) {
124
+ const raw = fs.readFileSync(path.join(dir, file), 'utf8');
125
+ const have = memberNamesOf(raw);
126
+ if (have.size === wanted.size && [...wanted].every((n) => have.has(n))) return { file, raw };
127
+ }
128
+ return null;
129
+ }
130
+
131
+ /**
132
+ * Carry forward everything after @generated:end from an UNDRAFTED skeleton (a human can append to
133
+ * its "## Notes" section before drafting) when a later --propose regenerates the evidence block.
134
+ * Never called on a drafted note — see proposeStagingNotes, which skips those entirely, because
135
+ * /memory:synthesize's draft lives BEFORE the marker (replacing frontmatter through it), the exact
136
+ * region this function always regenerates. No sentinel found means nothing to preserve.
137
+ *
138
+ * @param {string} existingRaw
139
+ * @param {string} freshRaw
140
+ * @returns {string}
141
+ */
142
+ export function mergeProposal(existingRaw, freshRaw) {
143
+ const existingIdx = existingRaw.indexOf(GEN_END);
144
+ const freshIdx = freshRaw.indexOf(GEN_END);
145
+ if (existingIdx === -1 || freshIdx === -1) return freshRaw;
146
+ const trailing = existingRaw.slice(existingIdx + GEN_END.length);
147
+ return freshRaw.slice(0, freshIdx + GEN_END.length) + trailing;
148
+ }
149
+
150
+ /** @typedef {{ file: string, status: 'written'|'updated'|'unchanged'|'drafted', members: number, bestScore: string }} ProposeResult */
151
+
152
+ /**
153
+ * Write (or update) a staging proposal per gap. Never touches `permanent/`, and never touches a
154
+ * proposal /memory:synthesize has already drafted (or anything not shaped like this module's own
155
+ * skeleton) — regenerating it would overwrite the draft, since the draft occupies the same
156
+ * frontmatter-through-marker region a fresh render always replaces.
157
+ *
158
+ * @param {string} vault
159
+ * @param {string} slug
160
+ * @param {readonly { members: readonly { note: string, layer: string, mtime?: number }[], best: { note: string | null, s: number }, typical: number }[]} gaps
161
+ * @returns {ProposeResult[]}
162
+ */
163
+ export function proposeStagingNotes(vault, slug, gaps) {
164
+ const dir = stagingDir(vault, slug);
165
+ fs.mkdirSync(dir, { recursive: true });
166
+ /** @type {ProposeResult[]} */
167
+ const out = [];
168
+ for (const gap of gaps) {
169
+ const topic = proposalSlug(gap.members);
170
+ const deterministicFile = `${topic}.md`;
171
+ const deterministicFull = path.join(dir, deterministicFile);
172
+ const wanted = new Set(gap.members.map((m) => m.note));
173
+ // Look for the SAME cluster under any name first — /memory:synthesize renames the file once
174
+ // drafted, so a lookup keyed only on the fresh candidate-slug path would miss a renamed,
175
+ // already-drafted proposal and mint a duplicate skeleton beside it. Falling back to the exact
176
+ // deterministic path keeps the original safety net for anything sitting there that the member
177
+ // search didn't recognize (e.g. no parseable `members:` list at all).
178
+ const found =
179
+ findExistingProposal(dir, wanted) ??
180
+ (fs.existsSync(deterministicFull)
181
+ ? { file: deterministicFile, raw: fs.readFileSync(deterministicFull, 'utf8') }
182
+ : null);
183
+ const file = found?.file ?? deterministicFile;
184
+ const full = path.join(dir, file);
185
+ const fresh = renderProposal(gap, topic);
186
+
187
+ if (found && checkDraftStatus(found.raw) !== 'undrafted') {
188
+ out.push({
189
+ file,
190
+ status: 'drafted',
191
+ members: gap.members.length,
192
+ bestScore: gap.best.s.toFixed(3),
193
+ });
194
+ continue;
195
+ }
196
+ let final = fresh;
197
+ /** @type {ProposeResult['status']} */
198
+ let status = 'written';
199
+ if (found) {
200
+ final = mergeProposal(found.raw, fresh);
201
+ status = final === found.raw ? 'unchanged' : 'updated';
202
+ }
203
+ if (status !== 'unchanged') fs.writeFileSync(full, final);
204
+ out.push({ file, status, members: gap.members.length, bestScore: gap.best.s.toFixed(3) });
205
+ }
206
+ return out;
207
+ }