Saves what each turn teaches straight into a Graphiti knowledge graph: a Haiku check after every turn, a cached fork writes the episode

Saves what a Claude Code session learns straight into a Graphiti knowledge graph, a little after every turn, instead of in one big batch at the next session start.
This depends on a Graphiti MCP server connected to Claude Code. Without one it does nothing useful, but the pattern (cheap judge, cached fork, MCP write) is easy to point at another store.
After each answered turn of the main thread, in the background:
SKIP, LEARNING: <what> (reusable across projects) or PROJECT: <what> (specific to this project). Most turns are SKIP.search_memory_facts) for what the judge flagged.$.model.fork replays the session's own transcript from the prompt cache, so it writes with the full context at a fraction of the price. It gets the facts the graph already holds and answers skip (already known), correction (the episode states what it replaces) or new, with a title and a short self-contained markdown body.add_memory tool: learnings to learningGroup, project facts to project_<name>.Claude Code's own file-based auto-memory is mirrored too: each Write or Edit of a file under ~/.claude/projects/<project>/memory/ replaces that file's episode (project-memory: <project>/<file>) in the project's group. The episode id is a UUID v5 of the group and file name, so one file is always one episode, and it is written into the file's frontmatter as knowledge_id. This needs a server whose add_memory treats a given uuid as "create or replace"; plain Graphiti only accepts the uuid of an existing episode.
The status line shows the last save. Nothing is added to the conversation.
A project can put a .claude/memory.json in its root. The plugin uses the nearest one at or above the session's folder, so a session started in a subfolder still lands in the project's group.
{
"group": "project_myapp",
"save": "Architecture decisions, deploy setup, where things live.",
"skip": "UI tweaks. Credentials.",
"recall": true
}
| Key | Meaning |
|---|---|
group | group_id for this project's facts and its auto-memory files. Without it: project_<folder name> |
save, skip | Plain-text guidance the judge gets with every turn |
recall | Reserved for recall; not used yet |
/knowledge-memory shows which file is in use.
The episode is written with the session's own MCP connection, so it goes through your permission rules. Allow the tool once, or every save will ask:
{ "permissions": { "allow": ["mcp__knowledge__add_memory"] } }
(Use your server's name in place of knowledge.)
/knowledge-memory: what was saved this session and the last result/knowledge-memory now: judge the last turn now/knowledge-memory save <what>: save something now, without the judge; the writer checks the graph the same way and picks learning or project itself| Option | Default | Meaning |
|---|---|---|
server | knowledge | The Graphiti MCP server's name as /mcp lists it |
learningGroup | learning | group_id for cross-project learnings |
judgeModel | haiku | The model that judges each turn |
mirrorAutoMemory | true | Mirror auto-memory file writes to the graph |
One small judge call per turn (the last exchange, capped at 12k characters). On a flagged turn, one fork that reads the conversation from the prompt cache and writes a few hundred tokens. Graphiti's own entity extraction runs on the server, on whatever model it is configured with.
hooks/register.ts 379 lines1// knowledge-memory: saves what a session learns straight into a Graphiti
2// knowledge graph, a little after every turn, instead of in bulk at the next
3// session start.
4//
5// After each main-thread turn:
6// 1. A small model (Haiku by default) reads the last exchange and answers
7// SKIP, LEARNING: <what> (reusable across projects) or PROJECT: <what>
8// (specific to this project).
9// 2. Only when it is not SKIP, the graph is searched for what the judge
10// flagged, and a tool-less $.model.fork gets the facts it already holds.
11// The fork replays the session's own transcript from the prompt cache, so
12// it has the full context at a fraction of the price. It answers skip
13// (already known), correction (states what it replaces) or new, and
14// drafts the episode.
15// 3. The episode goes to the graph's MCP server through $.mcp.call:
16// `learningGroup` for learnings, `project_<name>` for project facts.
17// "/knowledge-memory save <what>" runs step 2-3 on demand, without the judge.
18//
19// A project can steer it with .claude/memory.json, found by walking up from the
20// session's folder: `group` names the project's group, `save` and `skip` guide
21// the judge. Without one the group comes from the folder name.
22//
23// It also mirrors Claude Code's file-based auto-memory: every Write or Edit of
24// a file under ~/.claude/projects/<project>/memory/ replaces that file's one
25// episode in the graph. The episode id is derived from the group and file name,
26// and written into the file's frontmatter as knowledge_id.
27
28import type { EngineInterface, Register, SessionMessage } from 'claude-code'
29
30const JUDGE = `You decide whether one turn of a coding session taught something worth keeping in a long-term knowledge graph.
31
32Answer LEARNING when the turn established something reusable beyond this project: a root cause found while debugging, a tool or API gotcha, a working technique, a decision with its reason, a correction of a wrong assumption.
33Answer PROJECT when it established a lasting fact about this project: its setup, a constraint, a decision, where something lives, how it is deployed.
34Answer SKIP for routine work, questions, plans not yet carried out, chit-chat, anything only this conversation needs, and anything listed under "already saved".
35
36The turn may come with this project's own guidance on what to save and skip; follow it.
37
38Answer with exactly one line: "LEARNING: <what to save, under 20 words>", "PROJECT: <what to save, under 20 words>" or "SKIP".`
39
40// `ask` says why the writer runs: a classifier's flag, or the user's own /knowledge-memory save
41const writerPrompt = (ask: string, known: string, manual: boolean) => `[knowledge-memory] This message is from the knowledge-memory plugin, not the user. Do not use tools; answer in text only.
42
43${ask}
44
45The knowledge graph already holds these facts on the subject (found by searching for it; the date is when each was saved, "expired" means a later fact replaced it):
46<known>
47${known || '(nothing found)'}
48</known>
49
50Decide first:
51- "skip" when the graph already says this, in other words or not.
52- "correction" when it contradicts or updates a fact listed above. Write the episode so it states the new fact and what it replaces ("X, not Y as saved earlier").
53- "new" otherwise.
54
55Write the episode self-contained, for a future session without this conversation: the context, what was found or decided, the fix or the reason, and concrete names (tools, files, commands, versions, hosts). Leave out filler and the story of the conversation.
56
57Reply with only a JSON object: {"action": "new" | "correction" | "skip", ${manual ? '"kind": "learning" (reusable beyond this project) | "project" (about this project), ' : ''}"name": "<title under 80 characters>", "body": "<markdown, 3 to 15 lines>"}. With "skip", name and body may be empty.`
58
59type Saved = { at: number; group: string; name: string }
60type Settings = { path: string; group?: string; save?: string; skip?: string; recall?: boolean }
61
62let server = 'knowledge'
63let learningGroup = 'learning'
64let judgeModel = 'haiku'
65let mirrorAutoMemory = true
66
67let saved: Saved[] = [] // this session's episodes, newest last
68let lastResult = 'nothing yet'
69let isBusy = false
70let isPending = false
71
72// "C--Dev-RagBase2" -> "Dev-RagBase2" -> "RagBase2"; the same rule the old sync hook used
73export const projectName = (dirName: string): string =>
74 dirName.replace(/^[A-Z]--/, '').replace(/^(dev|Users-[^-]+)-/, '') || dirName
75
76const projectSlug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')
77
78// Where .claude/memory.json may be, nearest first: "C:\Dev\lab" -> C:\Dev\lab\.claude\memory.json, C:\Dev\..., C:\...
79export const settingsPaths = (dir: string): string[] => {
80 const sep = dir.includes('\\') ? '\\' : '/'
81 return ancestors(dir).map(d => [d, '.claude', 'memory.json'].join(sep))
82}
83
84// A folder and the folders above it, nearest first: "C:\Dev\lab" -> C:\Dev\lab, C:\Dev, C:
85function ancestors(dir: string): string[] {
86 const sep = dir.includes('\\') ? '\\' : '/'
87 const parts = dir.replace(/[\\/]+$/, '').split(/[\\/]/)
88 return parts.map((_, i) => parts.slice(0, parts.length - i).join(sep))
89}
90
91// The folder at or above cwd that a ~/.claude/projects/<slug> folder belongs to. Going from the slug back to a
92// folder is ambiguous ("Dev-lab" may be Dev\lab or Dev-lab), so match against the session's own folders instead.
93export const projectRoot = (cwd: string, slug: string): string | null =>
94 ancestors(cwd).find(d => projectSlug(d) === slug) ?? null
95
96export const parseSettings = (path: string, text: string): Settings => {
97 const json = JSON.parse(text) as Record<string, unknown>
98 const str = (k: string) => (typeof json[k] === 'string' && json[k] ? (json[k] as string) : undefined)
99 return { path, group: str('group'), save: str('save'), skip: str('skip'), recall: json.recall !== false }
100}
101
102// The nearest .claude/memory.json at or above the session's folder (or the given one)
103async function projectSettings($: EngineInterface, dir?: string): Promise<Settings | null> {
104 for (const path of settingsPaths(dir ?? (await $.session.cwd()))) {
105 if (!(await $.fs.exists(path))) continue
106 try {
107 return parseSettings(path, await $.fs.read(path))
108 } catch {
109 return null // a broken file falls back to the folder name rather than guessing
110 }
111 }
112 return null
113}
114
115const projectGroup = async ($: EngineInterface, settings: Settings | null, dir?: string) =>
116 settings?.group ?? `project_${projectName(projectSlug(dir ?? (await $.session.cwd())))}`
117
118// ~/.claude/projects/<dir>/memory/<file>.md, either slash
119const AUTO_MEMORY = /[\\/]\.claude[\\/]projects[\\/]([^\\/]+)[\\/]memory[\\/]([^\\/]+\.md)$/i
120
121export const autoMemoryFile = (path: string) => {
122 const m = AUTO_MEMORY.exec(path)
123 return m && m[2] !== 'MEMORY.md' ? { dir: m[1]!, project: projectName(m[1]!), file: m[2]! } : null
124}
125
126// A slash command's own rows (its record and output) are no exchange to judge
127const isCommandRow = (m: SessionMessage) => /^\s*<(local-)?command-/.test(m.text)
128
129export const lastExchange = (all: SessionMessage[]) => {
130 const messages = all.filter(m => !isCommandRow(m))
131 const start = messages.findLastIndex(m => m.role === 'user' && m.text.trim() !== '' && !m.toolResults?.length)
132 const text = messages
133 .slice(Math.max(0, start))
134 .flatMap(m => [...(m.text.trim() ? [`${m.role.toUpperCase()}: ${m.text.trim()}`] : []), ...m.toolUses.map(t => `TOOL: ${t.tool}`)])
135 .join('\n')
136 return text.length > 12000 ? `${text.slice(0, 4000)}\n…\n${text.slice(-8000)}` : text
137}
138
139export const parseVerdict = (text: string) => {
140 const m = /^(LEARNING|PROJECT):\s*(.+)$/m.exec(text.trim())
141 return m ? { kind: m[1] as 'LEARNING' | 'PROJECT', what: m[2]!.trim() } : null
142}
143
144type Episode = { action: 'new' | 'correction'; kind?: 'LEARNING' | 'PROJECT'; name: string; body: string }
145
146// null when the writer decided to skip
147export const parseEpisode = (text: string): Episode | null => {
148 const json = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)) as Record<string, unknown>
149 const str = (k: string) => (typeof json[k] === 'string' ? (json[k] as string).trim() : '')
150 const action = str('action') === 'correction' ? 'correction' : str('action') === 'skip' ? 'skip' : 'new'
151 const kind = str('kind') === 'learning' ? 'LEARNING' : str('kind') === 'project' ? 'PROJECT' : undefined
152 const name = str('name').slice(0, 120)
153 const body = str('body')
154 return action !== 'skip' && name && body ? { action, kind, name, body } : null
155}
156
157// The text of an MCP tool result, parsed as the JSON the knowledge server answers with
158const mcpJson = (r: { content?: unknown }): any => {
159 const text = (Array.isArray(r.content) ? r.content : []).map((c: any) => (typeof c?.text === 'string' ? c.text : '')).join('')
160 return text ? JSON.parse(text) : {}
161}
162
163// What the graph already says about a subject, one fact per line, for the writer to check against
164async function knownFacts($: EngineInterface, query: string, groups: string[]): Promise<string> {
165 try {
166 // An automated check is no use of a memory: don't let it count against decay. A server without access
167 // tracking may reject the argument, so ask again without it.
168 const args = { query, group_ids: groups, max_facts: 8 }
169 let r = await $.mcp.call(server, 'search_memory_facts', { ...args, track_access: false })
170 if (r.isError) r = await $.mcp.call(server, 'search_memory_facts', args)
171 if (r.isError) return ''
172 const facts = (mcpJson(r).facts ?? []) as { fact?: string; created_at?: string; expired_at?: string | null }[]
173 return facts
174 .filter(f => f.fact)
175 .map(f => `- ${(f.created_at ?? '').slice(0, 10)} ${f.fact}${f.expired_at ? ' (expired)' : ''}`)
176 .join('\n')
177 } catch {
178 return '' // no check is better than no save
179 }
180}
181
182async function addEpisode($: EngineInterface, args: { name: string; body: string; group: string; source: string; uuid?: string; max?: number }) {
183 const r = await $.mcp.call(server, 'add_memory', {
184 name: args.name,
185 episode_body: args.body.slice(0, args.max ?? 5000),
186 group_id: args.group,
187 source: 'text',
188 source_description: args.source,
189 ...(args.uuid ? { uuid: args.uuid } : {}),
190 })
191 if (r.isError) throw new Error(`add_memory on "${server}" failed`)
192 saved = [...saved, { at: await $.clock.now(), group: args.group, name: args.name }].slice(-20)
193}
194
195// The judge: does the last turn hold something worth keeping? Kept apart so another classifier can replace it.
196async function judge($: EngineInterface, settings: Settings | null): Promise<{ kind: 'LEARNING' | 'PROJECT'; what: string } | string> {
197 const exchange = lastExchange(await $.session.messages())
198 if (exchange.length < 200) return 'skipped: short turn'
199 const already = saved.map(s => `- ${s.name}`).join('\n') || '(none)'
200 const guidance = [settings?.save && `Save: ${settings.save}`, settings?.skip && `Skip: ${settings.skip}`].filter(Boolean).join('\n')
201 const verdict = await $.model.complete({
202 model: judgeModel,
203 system: JUDGE,
204 prompt: `${guidance ? `<project_guidance>\n${guidance}\n</project_guidance>\n\n` : ''}<already_saved>\n${already}\n</already_saved>\n\n<turn>\n${exchange}\n</turn>`,
205 maxTokens: 60,
206 timeoutMs: 20_000,
207 })
208 if (!verdict.isAnswered) return `judge failed: ${verdict.reason}`
209 return parseVerdict(verdict.text) ?? `skipped: judge said "${verdict.text.trim().slice(0, 200)}"`
210}
211
212// The writer: a fork with the whole conversation checks the graph's facts and writes one episode
213async function write($: EngineInterface, settings: Settings | null, ask: { kind?: 'LEARNING' | 'PROJECT'; what: string; manual: boolean }): Promise<string> {
214 const group = await projectGroup($, settings)
215 const known = await knownFacts($, ask.what, [learningGroup, group])
216 const why = ask.manual
217 ? `The user asked to save this to the knowledge graph: ${ask.what}`
218 : `A classifier flagged the latest turn for the knowledge graph as a ${ask.kind!.toLowerCase()}: ${ask.what}`
219 const reply = await $.model.fork({ prompt: writerPrompt(why, known, ask.manual) })
220 if (!reply.isAnswered) return `writer failed: ${reply.reason}`
221 let episode: Episode | null
222 try {
223 episode = parseEpisode(reply.text)
224 } catch {
225 return 'writer did not answer with JSON'
226 }
227 if (!episode) return 'skipped by the writer: already known or nothing to keep'
228
229 const kind = ask.kind ?? episode.kind ?? 'PROJECT'
230 const target = kind === 'LEARNING' ? learningGroup : group
231 const project = projectName(projectSlug(await $.session.cwd()))
232 await addEpisode($, { ...episode, group: target, source: `knowledge-memory | Project: ${project}${episode.action === 'correction' ? ' | correction' : ''}` })
233 const what = `${episode.action === 'correction' ? 'correction ' : ''}saved to ${target}: ${episode.name}`
234 $.ui.status(`🧠 ${what}`)
235 return what
236}
237
238async function considerTurn($: EngineInterface): Promise<string> {
239 const settings = await projectSettings($)
240 const flagged = await judge($, settings)
241 return typeof flagged === 'string' ? flagged : write($, settings, { ...flagged, manual: false })
242}
243
244// /knowledge-memory save <hint>: no judge, the writer saves what the user pointed at
245async function saveHint($: EngineInterface, hint: string): Promise<string> {
246 return write($, await projectSettings($), { what: hint, manual: true })
247}
248
249// One run at a time; a turn that ends during a run is considered once it finishes
250async function consider($: EngineInterface, hint?: string): Promise<void> {
251 if (isBusy) {
252 isPending = true
253 return
254 }
255 isBusy = true
256 try {
257 lastResult = hint ? await saveHint($, hint) : await considerTurn($)
258 } catch (err) {
259 lastResult = `failed: ${err instanceof Error ? err.message : String(err)}`
260 } finally {
261 isBusy = false
262 if (isPending) {
263 isPending = false
264 void consider($)
265 }
266 }
267}
268
269// UUID v5 (URL namespace) of a key: the same memory file always maps to the same episode
270export async function episodeUuid(key: string): Promise<string> {
271 const ns = '6ba7b8119dad11d180b400c04fd430c8'.match(/../g)!.map(h => parseInt(h, 16))
272 const data = new Uint8Array([...ns, ...new TextEncoder().encode(key)])
273 const b = new Uint8Array(await crypto.subtle.digest('SHA-1', data)).slice(0, 16)
274 b[6] = (b[6]! & 0x0f) | 0x50
275 b[8] = (b[8]! & 0x3f) | 0x80
276 const hex = [...b].map(x => x.toString(16).padStart(2, '0')).join('')
277 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
278}
279
280// The file with `knowledge_id: <id>` in its frontmatter (under metadata: when there is one), or null when it
281// already has it or has no frontmatter
282export const withKnowledgeId = (text: string, id: string): string | null => {
283 const eol = text.includes('\r\n') ? '\r\n' : '\n'
284 const lines = text.split(eol)
285 const end = lines.indexOf('---', 1)
286 if (lines[0] !== '---' || end < 0) return null
287 const at = (re: RegExp) => lines.findIndex((l, i) => i > 0 && i < end && re.test(l))
288 const existing = at(/^\s*knowledge_id:/)
289 if (existing >= 0) {
290 const line = lines[existing]!.replace(/knowledge_id:.*$/, `knowledge_id: ${id}`)
291 if (line === lines[existing]) return null
292 lines[existing] = line
293 return lines.join(eol)
294 }
295 const meta = at(/^metadata:\s*$/)
296 if (meta < 0) lines.splice(end, 0, `knowledge_id: ${id}`)
297 else lines.splice(meta + 1, 0, `${/^(\s+)\S/.exec(lines[meta + 1] ?? '')?.[1] ?? ' '}knowledge_id: ${id}`)
298 return lines.join(eol)
299}
300
301// One episode per memory file, replaced on every write; the file carries the episode's id
302async function mirror($: EngineInterface, path: string): Promise<void> {
303 const hit = autoMemoryFile(path)
304 if (!hit) return
305 // The memory folder of a project at or above the session's folder follows that project's settings, wherever the
306 // session has cd'd to since; another project's keeps its folder name
307 const root = projectRoot(await $.session.cwd(), hit.dir)
308 const group = root ? await projectGroup($, await projectSettings($, root), root) : `project_${hit.project}`
309 const id = await episodeUuid(`knowledge-memory:${group}/${hit.file}`)
310 let body = await $.fs.read(path)
311 const tagged = withKnowledgeId(body, id)
312 if (tagged !== null) {
313 await $.fs.write(path, tagged)
314 body = tagged
315 }
316 await addEpisode($, {
317 name: `project-memory: ${hit.project}/${hit.file}`,
318 body,
319 group,
320 source: `Project: ${hit.project} | File: ${hit.file}`,
321 uuid: id,
322 max: 50_000,
323 })
324 lastResult = `mirrored ${hit.project}/${hit.file} as ${id}`
325}
326
327export const register: Register = (on, options) => {
328 server = String(options.server || 'knowledge')
329 learningGroup = String(options.learningGroup || 'learning')
330 judgeModel = String(options.judgeModel || 'haiku')
331 mirrorAutoMemory = options.mirrorAutoMemory !== false
332
333 on('session.start', async ($, e, next) => {
334 await $.command.register({
335 name: 'knowledge-memory',
336 description: 'Show what knowledge-memory saved this session; "now" considers the last turn now; "save <what>" saves it',
337 argumentHint: '[now | save <what>]',
338 })
339 return next(e)
340 })
341
342 // After each answered main-thread turn, in the background
343 on('turn.complete', async ($, e, next) => {
344 const result = await next(e)
345 if (e.agentId === undefined && e.reason === 'answer') void consider($)
346 return result
347 })
348
349 // Mirror auto-memory writes to the graph once the write has landed
350 on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
351 const result = await next(e)
352 if (mirrorAutoMemory && !result.isError) void mirror($, e.file_path).catch(() => { lastResult = 'mirror failed' })
353 return result
354 }).catch(($, e, next) => next(e)) // never stand between Claude and a write
355
356 on('command.run', { command: 'knowledge-memory' }, async ($, e) => {
357 const args = (e.args ?? '').trim()
358 const hint = /^save\s+([\s\S]+)$/.exec(args)?.[1]?.trim()
359 if (args === 'now' || hint) {
360 if (isBusy) return { text: 'A run is already considering the last turn; /knowledge-memory shows its result.' }
361 await consider($, hint)
362 return { text: lastResult }
363 }
364 if (args === 'save') return { text: 'Say what to save: /knowledge-memory save <what>' }
365 const lines = saved.map(s => `- [${s.group}] ${s.name}`)
366 const settings = await projectSettings($)
367 return {
368 text: [
369 `Judge ${judgeModel}, server "${server}", learnings to "${learningGroup}".`,
370 settings
371 ? `Project settings: ${settings.path}, project facts to "${await projectGroup($, settings)}".`
372 : `No .claude/memory.json here; project facts to "${await projectGroup($, null)}".`,
373 lines.length ? `Saved this session:\n${lines.join('\n')}` : 'Nothing saved this session yet.',
374 `Last: ${lastResult}`,
375 ].join('\n'),
376 }
377 })
378}
379