@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,219 @@
1
+ // Pure decision logic for the UserPromptSubmit recall hook. The entry (hooks/memory-recall.mjs)
2
+ // owns stdin, the socket, node:sqlite and stdout; everything here takes rows and strings as values,
3
+ // so the gates, the ranking and the log-record shapes are testable without an index, a resident
4
+ // server, or a runtime that even has node:sqlite.
5
+ //
6
+ // Never import scripts/lib/memory-semantic.mjs here: this module is imported STATICALLY by
7
+ // hooks/memory-recall.mjs, above the fail-open try and above the recallEnabled() gate, so
8
+ // everything reachable from here runs on every prompt of every session, armed or not, uncatchably.
9
+ // memory-semantic.mjs's module scope does console.log(...) + process.exit(1) on an unknown model —
10
+ // uncatchable here, and hooks.json's `|| exit 0` turns that into a context-injecting no-op on every
11
+ // prompt, disarmed installs included.
12
+ //
13
+ // Equivalence proof for the 2026-08-19 swap off this module's own stopword/tokeniser/BM25 fork, and
14
+ // the module-init cost measurements behind choosing lexical.mjs over memory-semantic.mjs:
15
+ // docs/architecture.md H6 (~line 526) and B1 (~line 432).
16
+ import { CARD, bm25, lexTokens } from '../../scripts/lib/lexical.mjs';
17
+
18
+ export const MAX_NOTES = 4;
19
+ export const MAX_CHARS = 900; // ~250 tokens
20
+ // ponytail: gate is corpus-scaled, ~14 halves false fires — docs/decisions/2026-08-19-recall-gate-calibration.md
21
+ export const MIN_SCORE = 6.0;
22
+ export const MIN_PROMPT = 25; // one-word prompts have no retrievable intent
23
+ // Cosine needs its own gate — MIN_SCORE above is BM25-scaled and means nothing here. Calibrated
24
+ // 2026-08-15 on 5 on-topic and 5 deliberately off-topic prompts: on-topic 0.495-0.736, off-topic
25
+ // 0.351-0.506. The bands OVERLAP, so no threshold is clean; 0.55 rejects all 5 off-topic and admits
26
+ // 4 of 5 on-topic. Erring toward silence is the design rule. Sample is 10 prompts — treat it as a
27
+ // starting point, and read the abstain rate in the log rather than trusting this number.
28
+ export const MIN_COS = 0.55;
29
+
30
+ // Re-exported so the entry's SELECT can bind the card sentinel instead of spelling it out. That
31
+ // bare literal was the last unbound consumer (R4 in docs/architecture.md); it is gone as of
32
+ // 2026-08-19 because the SQL now sits behind this module.
33
+ export { CARD };
34
+
35
+ /**
36
+ * @typedef {{ note: string, layer: string, project?: string, text?: string | null, score: number }} Hit
37
+ * @typedef {{ note: string, layer: string, project?: string, text?: string | null, score?: number }} ServerHit
38
+ * @typedef {{ note: string, layer: string, text: string | null }} Card
39
+ * @typedef {{
40
+ * abstained: boolean,
41
+ * reason?: string,
42
+ * top?: string | null,
43
+ * score?: number,
44
+ * injected?: number,
45
+ * chars?: number,
46
+ * via?: string,
47
+ * ms?: number,
48
+ * k?: number,
49
+ * notes?: string[],
50
+ * }} LogEntry
51
+ * @typedef {{ entry: LogEntry, output: string | null }} Decision
52
+ */
53
+
54
+ // `k` and `notes` are the arm's CANDIDATES — the top MAX_NOTES by score, in render order, BEFORE
55
+ // renderLines applied anything of its own. `injected` is what actually reached the prompt, so the
56
+ // injected notes are `notes.slice(0, injected)`.
57
+ //
58
+ // `k > injected` therefore means renderLines stopped early, and WHICH of its two stops is
59
+ // arm-dependent: the semantic arm renders floorless over already-gated hits, so there it is the
60
+ // character budget; the keyword arm passes a trailing weak-hit floor (MIN_SCORE / 2) that
61
+ // renderLines checks BEFORE the budget, and its candidates are the top 4 of the whole corpus with
62
+ // only `scored[0]` gated — so there it is usually the floor. Do not read it as "the budget".
63
+ // Both keys follow `score`'s discipline: an arm with no candidates omits them rather than logging
64
+ // `0` and `[]`, which would read like a measurement of nothing instead of the absence of one.
65
+ // `ms` is stamped by the entry, which owns the clock; the arms stay pure and untimed.
66
+
67
+ export const HEADER =
68
+ 'Possibly relevant vault notes (retrieved, not verified — open one before relying on it):';
69
+
70
+ // Vault text was distilled from transcripts that can hold fetched pages, so it is data and must not
71
+ // carry markup Claude Code would read as its own. INVISIBLE goes first so a zero-width char hidden
72
+ // inside a tag name cannot shield the tag from the second pass.
73
+ // ponytail: non-Cf invisibles are a named list; a new lookalike filler must be added by hand.
74
+ const INVISIBLE = /[\p{Cf}\u034F\u115F\u1160\u2800\u3164\uFE00-\uFE0F\uFFA0\u{E0100}-\u{E01EF}]/gu;
75
+ const HARNESS_TAG =
76
+ /<(?=\/?(?:system-reminder|command-(?:name|message|args)|(?:local-command|bash)-[a-z]+|task-notification|user-prompt-submit-hook)\b)/gi;
77
+ /** @param {string} s */
78
+ export const defuse = (s) => s.replace(INVISIBLE, '').replace(HARNESS_TAG, '‹');
79
+
80
+ /** @param {readonly string[]} lines */
81
+ export const brief = (lines) => `${HEADER}\n${lines.join('\n')}`;
82
+
83
+ /** Copilot CLI injects only a rewritten prompt (#217). @param {Record<string, unknown>} p @param {string} out */
84
+ export const recallOutput = (p, out) =>
85
+ typeof p.transformedPrompt === 'string'
86
+ ? JSON.stringify({ modifiedTransformedPrompt: `${out}\n\n${p.transformedPrompt}` })
87
+ : out;
88
+
89
+ // Both arms render identically; only the trailing-weak-hit floor differs, so it is the one
90
+ // parameter. `floor` is BM25-scaled for the keyword arm and absent for the semantic one.
91
+ /**
92
+ * @param {readonly Hit[]} hits
93
+ * @param {number} [floor]
94
+ * @returns {{ lines: string[], used: number }}
95
+ */
96
+ export function renderLines(hits, floor = -Infinity) {
97
+ /** @type {string[]} */
98
+ const lines = [];
99
+ let used = 0;
100
+ for (const r of hits) {
101
+ if (r.score < floor) break; // trailing weak hits add noise, not context
102
+ const first = defuse((r.text ?? '').split('\n').slice(1).join(' '))
103
+ .replace(/\s+/g, ' ')
104
+ .trim();
105
+ const where = r.project ? `${r.layer} · ${defuse(r.project)}` : r.layer;
106
+ const line = `- [[${defuse(r.note)}]] (${where}): ${first.slice(0, 150)}`;
107
+ if (used + line.length > MAX_CHARS) break; // strict >: a brief of exactly MAX_CHARS fits
108
+ lines.push(line);
109
+ used += line.length;
110
+ }
111
+ return { lines, used };
112
+ }
113
+
114
+ // null means FALL THROUGH to the keyword arm, and it is the answer for more than just an error: a
115
+ // server reply of `{"results":[]}`, `{"results":null}` or unparseable output all land here, and the
116
+ // hook then answers from BM25 rather than abstaining. Anything else is a decision — `{ entry }` is
117
+ // the JSONL record, `output` is stdout or null.
118
+ /**
119
+ * @param {readonly ServerHit[] | null | undefined} results
120
+ * @returns {Decision | null}
121
+ */
122
+ export function semanticArm(results) {
123
+ if (!results?.length) return null;
124
+ const hits = /** @type {Hit[]} */ (
125
+ results.filter((r) => /** @type {number} */ (r.score) >= MIN_COS).slice(0, MAX_NOTES)
126
+ );
127
+ if (!hits.length) {
128
+ return {
129
+ // `score` is deliberately not defaulted: a hit with no score field must leave the key out of
130
+ // the JSON entirely rather than log a 0 that reads like a real measurement.
131
+ entry: {
132
+ abstained: true,
133
+ reason: 'low confidence (semantic)',
134
+ top: results[0]?.note,
135
+ score: results[0]?.score,
136
+ via: 'server',
137
+ },
138
+ output: null,
139
+ };
140
+ }
141
+ const { lines, used } = renderLines(hits);
142
+ // Only reachable if the very first line already exceeds MAX_CHARS, which needs a ~700-char note
143
+ // name because the body is sliced to 150. Effectively dead; kept because falling through is the
144
+ // safe reading of it, not because it has ever been observed (2026-08-19).
145
+ if (!lines.length) return null;
146
+ return {
147
+ entry: {
148
+ abstained: false,
149
+ injected: lines.length,
150
+ chars: used,
151
+ top: hits[0].note,
152
+ score: hits[0].score,
153
+ via: 'server',
154
+ k: hits.length,
155
+ notes: hits.map((h) => h.note),
156
+ },
157
+ output: brief(lines),
158
+ };
159
+ }
160
+
161
+ // The keyword arm always decides — it is the fallback, so it has nothing to fall through to.
162
+ // Its log records carry NO `via` field, and that absence is the only thing telling the two arms
163
+ // apart in the log. It is a contract, not an oversight.
164
+ /**
165
+ * @param {readonly Card[]} cards
166
+ * @param {string} prompt
167
+ * @returns {Decision}
168
+ */
169
+ export function keywordArm(cards, prompt) {
170
+ if (!cards.length) return { entry: { abstained: true, reason: 'empty index' }, output: null };
171
+
172
+ const qt = [...new Set(lexTokens(prompt))];
173
+ if (!qt.length) return { entry: { abstained: true, reason: 'no content words' }, output: null };
174
+
175
+ // `?? ''` is not defensive padding: chunks.text has no NOT NULL (scripts/memory-semantic.mjs's
176
+ // CREATE TABLE), and lexTokens does s.toLowerCase() with no guard, so one NULL row would throw out
177
+ // of the keyword arm. It fails open either way — the entry's outer catch exits 0 — but it would
178
+ // take the whole arm down and log nothing, where every other empty-content path here logs a
179
+ // reason. Unreachable today; the schema is what makes it reachable tomorrow (2026-08-19, #29).
180
+ const docs = cards.map((c) => ({ ...c, toks: lexTokens(c.text ?? '') }));
181
+ // k1/b PINNED, not left to bm25()'s defaults. MIN_SCORE below and its MIN_SCORE/2 trailing floor
182
+ // are absolute BM25 values calibrated at 1.2/0.75 — the arithmetic recall used to inline. Sharing
183
+ // the function means a tune made for the CLI's fusion arm would otherwise rescale both gates
184
+ // silently, and no test asserts an absolute score.
185
+ const scores = bm25(docs, qt, 1.2, 0.75);
186
+ const scored = docs
187
+ .map((d, i) => ({ note: d.note, layer: d.layer, text: d.text, score: scores[i] }))
188
+ .sort((a, b) => b.score - a.score);
189
+
190
+ if (!scored.length || scored[0].score < MIN_SCORE) {
191
+ return {
192
+ entry: {
193
+ abstained: true,
194
+ reason: 'low confidence',
195
+ top: scored[0]?.note ?? null,
196
+ score: +(scored[0]?.score ?? 0).toFixed(2),
197
+ },
198
+ output: null,
199
+ };
200
+ }
201
+
202
+ const cand = scored.slice(0, MAX_NOTES);
203
+ const { lines, used } = renderLines(cand, MIN_SCORE / 2);
204
+ const considered = { k: cand.length, notes: cand.map((c) => c.note) };
205
+ if (!lines.length)
206
+ return { entry: { abstained: true, reason: 'budget', ...considered }, output: null };
207
+
208
+ return {
209
+ entry: {
210
+ abstained: false,
211
+ injected: lines.length,
212
+ chars: used,
213
+ top: scored[0].note,
214
+ score: +scored[0].score.toFixed(2),
215
+ ...considered,
216
+ },
217
+ output: brief(lines),
218
+ };
219
+ }
@@ -0,0 +1,103 @@
1
+ // Oh My Pi (omp) extension: runs the commands hooks/hooks.json names through opencode.mjs's fire(),
2
+ // with a Claude-shaped payload that carries `harness: 'omp'`. Loaded through package.json
3
+ // `omp.extensions`. API: omp 19.0.1 docs/extensions.md, docs/usage.md#harnesses.
4
+
5
+ import path from 'node:path';
6
+ import { fire, toolName } from './opencode.mjs';
7
+
8
+ /**
9
+ * @param {{ fire?: import('./opencode.mjs').Fire }} [deps]
10
+ */
11
+ export function createExtension({ fire: run = fire } = {}) {
12
+ /** @param {any} pi */
13
+ return (pi) => {
14
+ /** @type {Map<string, Promise<string>>} */
15
+ const started = new Map();
16
+ /** @param {any} ctx */
17
+ const sid = (ctx) => String(ctx.sessionManager.getSessionId());
18
+ /** @param {any} ctx @param {string} event */
19
+ const base = (ctx, event) => ({
20
+ harness: 'omp',
21
+ session_id: sid(ctx),
22
+ cwd: String(ctx.cwd),
23
+ hook_event_name: event,
24
+ });
25
+ // Factories are rebound to every subagent; the memory belongs to the main session only.
26
+ /** @param {any} ctx */
27
+ const sub = (ctx) => ctx.agent?.kind === 'sub';
28
+
29
+ /** @type {{ session_id: string, cwd: string } | undefined} */
30
+ let current;
31
+ // `/new`, resume and fork name only the outgoing file, and shutdown ends only the incoming
32
+ // session, so the outgoing one gets its SessionEnd here.
33
+ /** @param {any} e @param {any} ctx */
34
+ const start = async (e, ctx) => {
35
+ if (sub(ctx)) return;
36
+ const prev = e?.previousSessionFile;
37
+ if (prev && current && current.session_id !== sid(ctx)) {
38
+ started.delete(current.session_id);
39
+ await run('SessionEnd', {
40
+ ...base(ctx, 'SessionEnd'),
41
+ ...current,
42
+ transcript_path: String(prev),
43
+ });
44
+ }
45
+ current = { session_id: sid(ctx), cwd: String(ctx.cwd) };
46
+ started.set(
47
+ sid(ctx),
48
+ run('SessionStart', { ...base(ctx, 'SessionStart'), source: 'startup' }),
49
+ );
50
+ };
51
+ pi.on('session_start', start);
52
+ pi.on('session_switch', start);
53
+
54
+ // The returned message persists in the session, so session-start context rides along once.
55
+ pi.on('before_agent_start', async (/** @type {any} */ e, /** @type {any} */ ctx) => {
56
+ if (e.reason !== 'prompt' || sub(ctx)) return;
57
+ const first = started.get(sid(ctx));
58
+ started.delete(sid(ctx));
59
+ const brief = run('UserPromptSubmit', {
60
+ ...base(ctx, 'UserPromptSubmit'),
61
+ prompt: String(e.prompt ?? ''),
62
+ });
63
+ const text = (await Promise.all([first ?? '', brief])).filter(Boolean).join('\n\n');
64
+ if (text) return { message: { customType: 'claude-memory', content: text, display: false } };
65
+ });
66
+
67
+ pi.on('tool_result', async (/** @type {any} */ e, /** @type {any} */ ctx) => {
68
+ const file = e.input?.path;
69
+ if (e.isError || sub(ctx) || typeof file !== 'string') return;
70
+ const tool = toolName(e.toolName);
71
+ const text = await run(
72
+ 'PostToolUse',
73
+ {
74
+ ...base(ctx, 'PostToolUse'),
75
+ tool_name: tool,
76
+ tool_input: { file_path: path.resolve(String(ctx.cwd), file) },
77
+ },
78
+ tool,
79
+ );
80
+ if (text) return { additionalContext: text };
81
+ });
82
+
83
+ // Never fires for subagents. Returns nothing, so it never asks omp for another turn.
84
+ pi.on('session_stop', async (/** @type {any} */ e, /** @type {any} */ ctx) => {
85
+ const file = e.session_file ?? ctx.sessionManager.getSessionFile();
86
+ if (file)
87
+ await run('Stop', {
88
+ ...base(ctx, 'Stop'),
89
+ transcript_path: file,
90
+ stop_hook_active: e.stop_hook_active === true,
91
+ });
92
+ });
93
+
94
+ // A 2 s budget; the distill gate detaches its worker in well under that.
95
+ pi.on('session_shutdown', async (/** @type {unknown} */ _e, /** @type {any} */ ctx) => {
96
+ const file = ctx.sessionManager.getSessionFile();
97
+ if (!sub(ctx) && file)
98
+ await run('SessionEnd', { ...base(ctx, 'SessionEnd'), transcript_path: file });
99
+ });
100
+ };
101
+ }
102
+
103
+ export default createExtension();
@@ -0,0 +1,231 @@
1
+ // opencode v2 server plugin: runs the commands hooks/hooks.json names, with a Claude-shaped payload
2
+ // that carries `harness: 'opencode'`, and maps their stdout onto opencode's hooks. Loaded through
3
+ // opencode/index.js. API: `@opencode/plugin` 2.4.4, docs/usage.md#harnesses.
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { spawn } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { stateDir } from './paths.mjs';
10
+
11
+ const ROOT = fileURLToPath(new URL('../..', import.meta.url));
12
+
13
+ /** @typedef {{ command: string, timeout?: number }} HookCommand */
14
+ /** @typedef {(event: string, payload: Record<string, unknown>, tool?: string) => Promise<string>} Fire */
15
+
16
+ /**
17
+ * The commands hooks.json runs for `event`, matcher applied to `tool` as Claude Code applies it.
18
+ *
19
+ * @param {string} event
20
+ * @param {string} [tool]
21
+ * @returns {HookCommand[]}
22
+ */
23
+ export function commands(event, tool) {
24
+ const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, 'hooks/hooks.json'), 'utf8'));
25
+ return (manifest.hooks[event] ?? [])
26
+ .filter(
27
+ (/** @type {{ matcher?: string }} */ g) =>
28
+ !g.matcher || new RegExp(`^(?:${g.matcher})$`).test(tool ?? ''),
29
+ )
30
+ .flatMap((/** @type {{ hooks: HookCommand[] }} */ g) => g.hooks);
31
+ }
32
+
33
+ /**
34
+ * The context a hook's stdout carries: either output JSON shape, or plain text.
35
+ *
36
+ * @param {string} stdout
37
+ */
38
+ export function contextText(stdout) {
39
+ const t = stdout.trim();
40
+ try {
41
+ const o = JSON.parse(t);
42
+ if (o && typeof o === 'object')
43
+ return String(o.hookSpecificOutput?.additionalContext ?? o.additionalContext ?? '');
44
+ } catch {}
45
+ return t;
46
+ }
47
+
48
+ /**
49
+ * One hook command, payload on stdin. Resolves its stdout, or '' on any failure: a hook must never
50
+ * break the session.
51
+ *
52
+ * @param {HookCommand} hook
53
+ * @param {Record<string, unknown>} payload
54
+ * @returns {Promise<string>}
55
+ */
56
+ export function runHook(hook, payload) {
57
+ return new Promise((resolve) => {
58
+ let out = '';
59
+ const child = spawn('sh', ['-c', hook.command], {
60
+ cwd: String(payload.cwd ?? ROOT),
61
+ env: { ...process.env, CLAUDE_PLUGIN_ROOT: ROOT },
62
+ stdio: ['pipe', 'pipe', 'ignore'],
63
+ detached: true,
64
+ });
65
+ // A grandchild keeps stdout open after `sh` dies, so `close` may never come: kill the whole
66
+ // group and answer now.
67
+ const timer = setTimeout(
68
+ () => {
69
+ try {
70
+ if (child.pid) process.kill(-child.pid, 'SIGKILL');
71
+ } catch {}
72
+ resolve('');
73
+ },
74
+ (hook.timeout ?? 10) * 1000,
75
+ );
76
+ child.stdout.setEncoding('utf8');
77
+ child.stdout.on('data', (d) => (out += d));
78
+ child.on('error', () => {
79
+ clearTimeout(timer);
80
+ resolve('');
81
+ });
82
+ child.on('close', (code) => {
83
+ clearTimeout(timer);
84
+ resolve(code === 0 ? out : '');
85
+ });
86
+ child.stdin.on('error', () => {});
87
+ child.stdin.end(JSON.stringify(payload));
88
+ });
89
+ }
90
+
91
+ /** Never rejects: a missing or broken manifest must not fail the model request. @type {Fire} */
92
+ export async function fire(event, payload, tool) {
93
+ try {
94
+ const outs = await Promise.all(commands(event, tool).map((h) => runHook(h, payload)));
95
+ return outs.map(contextText).filter(Boolean).join('\n\n');
96
+ } catch {
97
+ return '';
98
+ }
99
+ }
100
+
101
+ /** `write` and `opencode.tool.edit` alike become Claude's `Write` / `Edit`. @param {string} tool */
102
+ export function toolName(tool) {
103
+ const n = String(tool).split('.').pop() ?? '';
104
+ return n.charAt(0).toUpperCase() + n.slice(1);
105
+ }
106
+
107
+ /** @param {unknown} content @returns {unknown[]} */
108
+ const asParts = (content) =>
109
+ Array.isArray(content) ? content : content ? [{ type: 'text', text: String(content) }] : [];
110
+
111
+ /**
112
+ * The session's messages as JSONL, one `SessionMessageInfo` per line, which the distiller reads.
113
+ * Rewritten on every call, so the newest copy is what a worker reads.
114
+ * ponytail: one file per session, never pruned; a detached worker may still read it after
115
+ * SessionEnd. Add it to retention if `run/opencode/` ever grows enough to notice.
116
+ *
117
+ * @param {string} sessionID
118
+ * @param {readonly unknown[]} messages
119
+ */
120
+ export function writeTranscript(sessionID, messages) {
121
+ const dir = path.join(stateDir('run'), 'opencode');
122
+ fs.mkdirSync(dir, { recursive: true });
123
+ const file = path.join(dir, `${sessionID.replace(/[^\w-]/g, '_')}.jsonl`);
124
+ // A worker from the previous idle may still be reading the old copy.
125
+ fs.writeFileSync(`${file}.tmp`, messages.map((m) => JSON.stringify(m)).join('\n') + '\n');
126
+ fs.renameSync(`${file}.tmp`, file);
127
+ return file;
128
+ }
129
+
130
+ /**
131
+ * @param {{ fire?: Fire }} [deps]
132
+ */
133
+ export function createPlugin({ fire: run = fire } = {}) {
134
+ return {
135
+ id: 'claude-memory',
136
+ /** @param {any} ctx */
137
+ async setup(ctx) {
138
+ const cwd = String(ctx.location?.directory ?? process.cwd());
139
+ /** @type {Map<string, Promise<string>>} */
140
+ const started = new Map();
141
+ /** @type {Map<string, string>} */
142
+ const briefs = new Map();
143
+ /** @type {Set<string>} */
144
+ const seen = new Set();
145
+ /** @param {string} sid @param {string} event */
146
+ const base = (sid, event) => ({
147
+ harness: 'opencode',
148
+ session_id: sid,
149
+ cwd,
150
+ hook_event_name: event,
151
+ });
152
+
153
+ // `prompt` edits persist as the user's message, so recall only runs here; `context` injects.
154
+ await ctx.session.hook('prompt', async (/** @type {any} */ e) => {
155
+ const prompt = String(e.prompt?.text ?? '');
156
+ briefs.set(
157
+ e.sessionID,
158
+ await run('UserPromptSubmit', { ...base(e.sessionID, 'UserPromptSubmit'), prompt }),
159
+ );
160
+ });
161
+
162
+ // Runs on every model request and touches only the outgoing call, so the text is pushed
163
+ // each time; the SessionStart hooks themselves run once per session.
164
+ await ctx.session.hook('context', async (/** @type {any} */ e) => {
165
+ if (!started.has(e.sessionID))
166
+ started.set(
167
+ e.sessionID,
168
+ run('SessionStart', { ...base(e.sessionID, 'SessionStart'), source: 'startup' }),
169
+ );
170
+ for (const text of [await started.get(e.sessionID), briefs.get(e.sessionID)])
171
+ if (text) e.system.push({ type: 'text', text });
172
+ });
173
+
174
+ await ctx.tool.hook('execute.after', async (/** @type {any} */ e) => {
175
+ const file = e.input?.path ?? e.input?.filePath;
176
+ if (e.status !== 'completed' || typeof file !== 'string') return;
177
+ const tool = toolName(e.tool);
178
+ const text = await run(
179
+ 'PostToolUse',
180
+ {
181
+ ...base(e.sessionID, 'PostToolUse'),
182
+ tool_name: tool,
183
+ tool_input: { file_path: path.resolve(cwd, file) },
184
+ },
185
+ tool,
186
+ );
187
+ if (text)
188
+ e.result = {
189
+ ...e.result,
190
+ content: [...asParts(e.result?.content), { type: 'text', text }],
191
+ };
192
+ });
193
+
194
+ /** @param {string} sid @param {string} event */
195
+ const distill = async (sid, event) => {
196
+ try {
197
+ const transcript = writeTranscript(sid, await ctx.session.context({ sessionID: sid }));
198
+ await run(event, { ...base(sid, event), transcript_path: transcript });
199
+ } catch {}
200
+ };
201
+
202
+ // No session-end event exists: an idle turn is Claude's Stop (gated hard by the distiller),
203
+ // and plugin unload stands in for SessionEnd.
204
+ const ac = new AbortController();
205
+ let hasStatus = false;
206
+ (async () => {
207
+ try {
208
+ for await (const ev of ctx.event.subscribe({
209
+ types: ['session.status', 'session.idle'],
210
+ signal: ac.signal,
211
+ })) {
212
+ const sid = ev.data?.sessionID;
213
+ // A build that sends `session.status` also sends the older `session.idle` for one turn.
214
+ if (ev.type === 'session.status') hasStatus = true;
215
+ else if (hasStatus) continue;
216
+ if (!sid || (ev.type === 'session.status' && ev.data.status?.type !== 'idle')) continue;
217
+ seen.add(sid);
218
+ await distill(sid, 'Stop');
219
+ }
220
+ } catch {}
221
+ })();
222
+
223
+ return async () => {
224
+ ac.abort();
225
+ await Promise.all([...seen].map((sid) => distill(sid, 'SessionEnd')));
226
+ };
227
+ },
228
+ };
229
+ }
230
+
231
+ export default createPlugin();