SLOPSHOPPER

cortexdb-live

CortexDB inside Claude Code: haiku-planned auto-recall shown above the prompt, the brain on the status line, and durable facts captured while the session is…

bandcommandtoaststatusmodelprocess
★ 468v2.139.0MITupdated 2026-10-24liliang-cn/cortexdb/plugins/cortexdb-live
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cortexdb-live
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /cortexdb-show ⎿ cortexdb-live: The last prompt recalled nothing. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ cortexdb-live: 🧠 local brain · ⚠ unreachable: undefined is not an object (evaluating 'result.content.find')
README

CortexDB

Go Reference CI codecov License: MIT

AI memory and a knowledge graph in one SQLite file. Pure Go, no service to run, works without an embedding model.

The CortexDB live view

Install

Go librarygo get github.com/liliang-cn/cortexdb/v2
Claude Code/plugin marketplace add liliang-cn/cortexdb, then /plugin install cortexdb@cortexdb
Codexcodex plugin marketplace add liliang-cn/cortexdb && codex plugin add cortexdb@cortexdb
Claude Code mod (optional)/plugin install cortexdb-live@cortexdb
DeepSeek Harnessdsh plugin --profile web add "github:liliang-cn/cortexdb#semver:^2&path:/plugins/dsh-cortexdb-memory" (guide)
Obsidianunzip a release's cortexdb-obsidian.zip into <vault>/.obsidian/plugins/ (guide)
Shared-brain servergo install github.com/liliang-cn/cortexdb/v2/cmd/cortexdb-grpc@latest
Clientscargo add cortexdb-client · pip install cortexdb-client · npm install cortexdb-client

Use

db, _ := cortexdb.Open(cortexdb.DefaultConfig("brain.db"))
defer db.Close()
brain := db.KnowledgeMemory()
_, _ = brain.Remember(ctx, cortexdb.KnowledgeMemoryRememberRequest{MemoryID: "alice-tabs", UserID: "alice", Scope: "user", Content: "Alice prefers tabs."})
rec, _ := brain.Recall(ctx, cortexdb.KnowledgeMemoryRecallRequest{Query: "what does Alice prefer?", UserID: "alice"})
fmt.Println(rec.ContextPack.Text)

The plugin gives Claude Code and Codex one global brain at ~/.cortexdb/cortexdb.db, /remember, /recall and an auto-recall hook. A session starts with an index of what the brain knows about its project, an agent about to open a file is told what happened to it before, and a session's durable facts are captured with <private> text and credentials kept out. Point several agents or machines at one cortexdb-grpc and they share the same memory and graph.

In Codex, review and trust the plugin hooks in /hooks to activate automatic recall. See the plugin guide for setup and cortexdb-mcp --doctor --self-test diagnostics (v2.119.0+).

Claude Code mod

cortexdb-live is an optional mod that runs inside Claude Code on top of the cortexdb plugin. Install it after the plugin:

/plugin install cortexdb-live@cortexdb

The mod calls three of the plugin's tools itself, and a hook gets no permission prompt, so allow them once in ~/.claude/settings.json (not needed in bypass mode):

"permissions": {
  "allow": [
    "mcp__plugin_cortexdb_cortexdb__knowledge_memory_recall",
    "mcp__plugin_cortexdb_cortexdb__graph_statistics",
    "mcp__plugin_cortexdb_cortexdb__memory_save"
  ]
}

Without them the status line names the missing rules.

  • Planned recall. Before the brain is searched, haiku turns each prompt into keywords in Chinese and English, aliases, entity names and a retrieval mode. A bare "ok" or "go ahead" searches nothing. The band above the prompt shows what was recalled; expand it to see the plan and every hit. Hide lasts until the next recall; /cortexdb-show brings the hidden one back.
  • Status line. Which brain the session uses, its node count and how long the last recall took, or why the brain can't be reached.
  • Capture. 90 seconds after a session goes idle, haiku distils the new part of the conversation into durable memories (auto:<session>:<slug>). Each later pass replaces a memory under the same slug rather than adding a copy. Older memories a new one makes untrue (a host moved, a decision reversed) are marked superseded: kept, but no longer recalled as current.

Haiku runs on Claude Code's own model access, so no API key is needed. Language: /config → cortexdb-live → language (auto, zh, en). The mod honours the plugin's own switches: cortexdb-recall --disable and cortexdb-session-end --disable turn recall and capture off for both. While the mod runs, the plugin's shell recall and capture hooks stand down, so nothing is done twice. Codex keeps those hooks. Mods are an early-access Claude Code feature.

What's inside

  • Vectors (HNSW, IVF, flat, binary codes), FTS5 full-text search, hybrid and graph retrieval
  • EmbeddedConfig for small devices: an SQ8 index, bounded SQLite caches, snapshots that survive a power cut — 100k 768-d vectors open in 0.28 s with a 193 MB heap
  • RAG knowledge, scoped agent memory, context packs with sources
  • RDF 1.2 knowledge graph: SPARQL 1.1/1.2, RDFS + OWL 2 RL inference, SHACL Core + SHACL-SPARQL, RDF/XML import — passing the W3C SPARQL 1.1/1.2, RDF 1.2 (Turtle, TriG, N-Triples, N-Quads, RDF/XML) and SHACL test suites; RDFS and OWL 2 RL are covered by the repo's own tests — and read-only Cypher
  • Palantir-style ontology with governed actions
  • 100+ tools, in-process or over MCP
  • serve_graph_3d: a live 3D view to find, ask, query and expand, on desktop or phone — or the same brain as a library, each memory a book on its project's shelf
  • import_agent_memory: bring in what Claude Code, Codex and DeepSeek Harness already remember — memory notes, CLAUDE.md / AGENTS.md, Codex's memories, and optionally past sessions distilled into memories — into a local or shared brain
  • Change feed: every committed write, in order, exactly once
  • SQLite by default, PostgreSQL + pgvector with a postgres:// DSN

Environment

VariableMeaning
CORTEXDB_PATHDatabase file (default ~/.cortexdb/cortexdb.db)
CORTEXDB_REMOTEUse a shared cortexdb-grpc at host:port (plaintext) or https://host (TLS, behind a proxy) instead of a local file
CORTEXDB_GRPC_TOKENBearer token for that server
CORTEXDB_GRPC_ADDRServer listen address (default 127.0.0.1:47821)
CORTEXDB_EMBED_BASE_URL / CORTEXDB_EMBED_API_KEYcortexdb-mcp-stdio: OpenAI-compatible embeddings endpoint and its key (fall back to OPENAI_BASE_URL / OPENAI_API_KEY); unset = lexical mode
OPENAI_BASE_URL / OPENAI_API_KEYServer: the embeddings endpoint and key (cortexdb-grpc reads only these, not CORTEXDB_EMBED_BASE_URL); unset = lexical mode
CORTEXDB_EMBED_MODEL / CORTEXDB_EMBED_DIMEmbedding model and dimension, for both (default text-embedding-3-small / 1536)
CORTEXDB_REVIEW_GATEServer and cortexdb-mcp-stdio: 1 leaves proposed and rejected documents and memories out of search and recall (default off; a curation filter, not access control)
CORTEXDB_SLOW_MSServer: log calls slower than this, with the time each stage took (default 1000, 0 = none)
CORTEXDB_TRACE / CORTEXDB_TRACE_FILEServer: log every call; also append the records to a JSON-lines file

Docs

Website · Guide (full feature reference) · Examples · Changelog · 中文

License

MIT

Source 2 files
hooks/register.tsx 1053 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register } from 'claude-code'
3
4import type { CaptureMark, CapturedMemory, HitOrigin, HitWhy, Recall, RecallHit, RecallPlan } from '../types'
5
6const last = atom({ plugin: 'cortexdb-live', key: 'last' } as const, null)
7const isOpen = atom({ plugin: 'cortexdb-live', key: 'isOpen' } as const, false)
8const isHidden = atom({ plugin: 'cortexdb-live', key: 'isHidden' } as const, false)
9const captureMark = atom({ plugin: 'cortexdb-live', key: 'capture' } as const, null)
10
11// The server the cortexdb plugin's manifest starts. Inside that plugin
12// $.mcp.connect answers with it; from a mod of its own it is this name.
13const FALLBACK_SERVER = 'plugin:cortexdb:cortexdb'
14// The shell hook's block starts with this; when the recall here answered, that
15// one is the same question asked twice.
16const SHELL_HEADER = 'Relevant CortexDB memories for this prompt'
17const TOP_K = 3
18const SNIPPET = 220
19// Planning is worth a second, not more: past this the lexical plan stands in.
20const PLAN_TIMEOUT_MS = 2500
21// A recall runs before every prompt: past this the prompt goes on without it.
22const RECALL_BUDGET_MS = 6000
23const STATS_EVERY_MS = 5 * 60 * 1000
24const CONNECT_RETRY_MS = 5 * 1000
25// session.end gets 1.5 s, too little for a model call, so a session is
26// captured while it is idle instead: this long after its last turn.
27const CAPTURE_IDLE_MS = 90 * 1000
28const CAPTURE_MIN_USER_TURNS = 2
29const PLANNER = 'haiku'
30const SHOW_COMMAND = 'cortexdb-show'
31
32const STRINGS = {
33  zh: {
34    recalled: (n: number) => `🧠 已召回 ${n} 条`,
35    detail: (m: number, k: number, s: string) => `(记忆 ${m} · 知识 ${k} · ${s}s)`,
36    expand: '展开',
37    collapse: '收起',
38    hide: '隐藏',
39    memory: '记忆',
40    knowledge: '知识',
41    query: '查询',
42    entities: '实体',
43    project: '项目',
44    why: '依据',
45    via: { semantic: '语义', keyword: '关键词', hybrid: '语义+关键词', graph: '图谱' },
46    matched: '命中',
47    from: '来源',
48    session: '会话',
49    key: 'key',
50    nodes: (n: string) => `${n} 节点`,
51    recallTime: (s: string) => `召回 ${s}s`,
52    skipped: '这条不用召回',
53    unreachable: '连不上',
54    recallFailed: '召回失败',
55    denied: (tools: string) => `没有调用 CortexDB 工具的权限,请在 settings.json 的 permissions.allow 里允许:${tools}`,
56    local: '本地大脑',
57    captured: (n: number, retired: number) => `CortexDB 记下了 ${n} 条新记忆${retired > 0 ? `,替换了 ${retired} 条过时的` : ''}`,
58    showCommand: '重新显示上一条 prompt 的 CortexDB 召回结果(隐藏之后用)',
59    shown: '已在输入框上方重新显示召回结果。',
60    nothingShown: '上一条 prompt 没有召回到内容。',
61  },
62  en: {
63    recalled: (n: number) => `🧠 Recalled ${n}`,
64    detail: (m: number, k: number, s: string) => ` (memories ${m} · knowledge ${k} · ${s}s)`,
65    expand: 'Expand',
66    collapse: 'Collapse',
67    hide: 'Hide',
68    memory: 'memory',
69    knowledge: 'knowledge',
70    query: 'Query',
71    entities: 'Entities',
72    project: 'Project',
73    why: 'why',
74    via: { semantic: 'semantic', keyword: 'keyword', hybrid: 'semantic+keyword', graph: 'graph' },
75    matched: 'matched',
76    from: 'from',
77    session: 'session',
78    key: 'key',
79    nodes: (n: string) => `${n} nodes`,
80    recallTime: (s: string) => `recall ${s}s`,
81    skipped: 'no recall needed',
82    unreachable: 'unreachable',
83    recallFailed: 'recall failed',
84    denied: (tools: string) => `not allowed to call CortexDB tools; allow them in settings.json permissions.allow: ${tools}`,
85    local: 'local brain',
86    captured: (n: number, retired: number) => `CortexDB saved ${n} new memories${retired > 0 ? `, retired ${retired} outdated` : ''}`,
87    showCommand: "Show what CortexDB recalled for the last prompt again (after Hide)",
88    shown: 'The recall is shown above the prompt again.',
89    nothingShown: 'The last prompt recalled nothing.',
90  },
91}
92
93type Lang = keyof typeof STRINGS
94type Brain = { where?: string; nodes?: number; error?: string; recallMs?: number; skipped?: boolean }
95
96let server: string | undefined
97let lang: Lang = 'en'
98let brain: Brain = {}
99let idleTimer: { cancel: () => void } | undefined
100let isCapturing = false
101// Recorded on every memory a capture writes, so a recall can say which machine
102// and which project a memory came from.
103let host: string | undefined
104
105const t = () => STRINGS[lang]
106
107// zh when anything the person chose says Chinese; an explicit Claude Code
108// language setting that says something else wins over the locale.
109async function resolveLang($: EngineInterface, options: PluginOptions): Promise<Lang> {
110  if (options.language === 'zh' || options.language === 'en') return options.language
111  const isZh = (value: unknown) => typeof value === 'string' && /^zh|chinese|中文|汉语|简体|繁體/i.test(value.trim())
112  // Claude Code's own language row reads English until someone sets it, so
113  // only a Chinese value there decides; anything else falls to the locale.
114  const setting = (await $.config.list().catch(() => [])).find(row => row.key === 'language')?.value
115  if (isZh(setting)) return 'zh'
116  for (const value of [await $.env.get('LC_ALL'), await $.env.get('LC_MESSAGES'), await $.env.get('LANG')]) {
117    if (isZh(value)) return 'zh'
118  }
119  // macOS keeps the UI language here, while Terminal's LANG often says en_US.
120  const apple = await $.process.run(['defaults', 'read', '-g', 'AppleLanguages']).catch(() => undefined)
121  const first = apple?.exitCode === 0 ? apple.stdout.match(/[A-Za-z]{2,3}(-[A-Za-z0-9]+)*/)?.[0] : undefined
122  return isZh(first) ? 'zh' : 'en'
123}
124
125async function serverOf($: EngineInterface) {
126  if (server) return server
127  const own = await $.mcp.connect('cortexdb').catch(() => undefined)
128  server = own?.isConnected ? own.server : FALLBACK_SERVER
129  return server
130}
131
132// A reply that is not JSON is the host's, not the server's: Claude Code
133// swaps a tool result past its token limit for a line of text that starts
134// "Error:" and does not flag it as an error. Its opening words say which.
135class NotJSON extends Error {
136  constructor(tool: string, readonly reply: string) {
137    super(`${tool}: ${reply.slice(0, 120).replace(/\s+/g, ' ') || 'empty reply'}`)
138  }
139  get tooLarge() {
140    return /exceeds maximum allowed tokens/i.test(this.reply)
141  }
142}
143
144async function callTool($: EngineInterface, tool: string, args: Record<string, unknown>) {
145  const result = await $.mcp.call(await serverOf($), tool, args)
146  const text = result.content.find(block => block.type === 'text')?.text ?? ''
147  if (result.isError) throw new Error(text.slice(0, 200) || `${tool} failed`)
148  try {
149    return JSON.parse(text) as unknown
150  } catch {
151    throw new NotJSON(tool, text)
152  }
153}
154
155function showStatus($: EngineInterface) {
156  const parts = [`🧠 ${brain.where ?? t().local}`]
157  if (brain.error) parts.push(`⚠ ${brain.error}`)
158  else {
159    if (brain.nodes !== undefined) parts.push(t().nodes(brain.nodes.toLocaleString('en-US')))
160    if (brain.skipped) parts.push(t().skipped)
161    else if (brain.recallMs !== undefined) parts.push(t().recallTime((brain.recallMs / 1000).toFixed(1)))
162  }
163  $.ui.status(parts.join(' · '))
164}
165
166async function refreshStats($: EngineInterface) {
167  try {
168    const stats = (await callTool($, 'graph_statistics', {})) as { node_count?: number }
169    brain = { ...brain, nodes: stats.node_count, error: undefined }
170  } catch (err) {
171    if (isConnecting(err)) {
172      // The session starts before its MCP servers finish connecting: the
173      // first ask can come too early, which says nothing about the brain.
174      $.clock.after(CONNECT_RETRY_MS, () => void refreshStats($))
175      return
176    }
177    brain = { ...brain, error: isDenied(err) ? t().denied(TOOLS_TO_ALLOW) : `${t().unreachable}: ${messageOf(err)}` }
178  }
179  showStatus($)
180}
181
182// The switches `cortexdb-recall` and `cortexdb-session-end` write, shared with
183// the shell hooks so one command turns a feature off everywhere.
184async function sentinel($: EngineInterface, name: 'autorecall' | 'autocapture') {
185  const cache = (await $.env.get('XDG_CACHE_HOME')) ?? `${await $.env.get('HOME')}/.cache`
186  try {
187    return String(await $.fs.read(`${cache}/cortexdb/${name}`)).trim()
188  } catch {
189    return undefined
190  }
191}
192
193// --- recall -----------------------------------------------------------------
194
195const PLAN_SYSTEM = `You plan a lookup in a long-term memory and knowledge-graph store that a coding assistant keeps across sessions: user preferences, project decisions, deployments, hosts, versions, lessons.
196
197Given the user's new message, the project the session works in and the recent conversation, answer with JSON only:
198{"skip":false,"query":"...","keywords":["..."],"alternate_queries":["..."],"entity_names":["..."],"retrieval_mode":"auto"}
199
200- skip: true only when the message needs nothing remembered: a bare acknowledgement or go-ahead ("ok", "好", "发", "继续", "👌") whose subject the previous reply already settles.
201- The message often points into the conversation instead of naming its subject: 这个, 那个, 它, 上面, 刚才, 按建议, 这个修复, this, that, it, the fix, the suggestion. Resolve every such pointer from the recent conversation and name the concrete thing it means (project, component, bug, command, file). A lookup that keeps the bare pointer word finds nothing, or finds the wrong project.
202- query: the message restated as a self-contained lookup that names its subject and, when the message is about the work in it, the project.
203- keywords: up to 12 terms the stored text would contain: names, project and host names, versions, abbreviations, synonyms, and BOTH Chinese and English forms of each concept.
204- alternate_queries: up to 3 other phrasings.
205- entity_names: up to 6 exact names of concrete things (projects, services, hosts, people, tools), the project among them when the message is about it.
206- retrieval_mode: "graph" for relational questions (who uses X, what X depends on, how A relates to B), else "auto".`
207
208type PlanReply = {
209  skip?: boolean
210  query?: string
211  keywords?: string[]
212  alternate_queries?: string[]
213  entity_names?: string[]
214  retrieval_mode?: string
215}
216
217type Planned = { args: Record<string, unknown>; plan: RecallPlan; skip: boolean }
218
219// What a message is said against: the project the session works in and the
220// last few turns. "这个修复前后可以验证吗" names nothing by itself; asked
221// bare, it recalls whatever other project once fixed and verified something.
222type Situation = { project?: string; turns: Message[] }
223
224const RECENT_TURNS = 4
225
226async function situationOf($: EngineInterface, prompt: string): Promise<Situation> {
227  let project: string | undefined
228  try {
229    const root = await $.session.root()
230    // A session started in the home directory works in no project.
231    if (root && root !== (await $.env.get('HOME'))) project = root.split('/').filter(Boolean).at(-1)
232  } catch {
233    // A build without session.root: no project to name.
234  }
235  const history = await $.session.messages().catch(() => [])
236  const turns = (Array.isArray(history) ? history : [])
237    .map(m => ({ ...m, text: m.text.replace(NOISE, '').trim() }))
238    .filter(m => (m.role === 'user' || m.role === 'assistant') && m.text !== '')
239  // The prompt being answered may already be the last turn.
240  if (turns.at(-1)?.role === 'user' && turns.at(-1)?.text === prompt) turns.pop()
241  return { project, turns: turns.slice(-RECENT_TURNS) }
242}
243
244const conversationOf = (s: Situation) =>
245  s.turns.map(m => `${m.role === 'user' ? 'USER' : 'ASSISTANT'}: ${clip(m.text, m.role === 'user' ? 300 : 800)}`).join('\n\n')
246
247// The fallback when no plan came back: the message with the project and the
248// start of the last reply after it, so the embedding lands near what the
249// conversation is about and not near every other project's "fix" and "verify".
250// The server embeds the query alone, so the context has to be in it.
251const situated = (prompt: string, s: Situation) => {
252  const previous = s.turns.filter(m => m.role === 'assistant').at(-1)?.text
253  const lines = [s.project ? `Project: ${s.project}` : '', previous ? `Context: ${clip(oneLine(previous), 300)}` : '']
254  const context = lines.filter(Boolean).join('\n')
255  return context ? `${prompt}\n\n${context}` : prompt
256}
257
258async function planRecall($: EngineInterface, prompt: string): Promise<Planned> {
259  const started = await $.clock.now()
260  const situation = await situationOf($, prompt)
261  const project = situation.project ? [situation.project] : []
262  const lexical = [...new Set([...keywordsOf(prompt), ...project])]
263  const query = situated(prompt, situation)
264  const fallback: Planned = {
265    args: { query, keywords: lexical, ...(project.length > 0 ? { entity_names: project } : {}) },
266    plan: { by: 'lexical', query, keywords: lexical, entities: project, mode: 'auto', ms: 0, project: situation.project },
267    skip: false,
268  }
269
270  const conversation = conversationOf(situation)
271  const reply = await $.model.complete({
272    model: PLANNER,
273    system: PLAN_SYSTEM,
274    prompt: [
275      situation.project ? `Project: ${situation.project}` : '',
276      conversation ? `Recent conversation (oldest first):\n${conversation}` : '',
277      `New user message:\n${clip(prompt, 2000)}`,
278    ]
279      .filter(Boolean)
280      .join('\n\n'),
281    maxTokens: 500,
282    timeoutMs: PLAN_TIMEOUT_MS,
283  })
284  if (!reply.isAnswered) return fallback
285  const planned = parseJSON<PlanReply>(reply.text)
286  if (!planned) return fallback
287
288  const keywords = [...new Set([...strings(planned.keywords, 12), ...lexical])].slice(0, 24)
289  const entities = strings(planned.entity_names, 6)
290  const mode = planned.retrieval_mode === 'graph' || planned.retrieval_mode === 'lexical' ? planned.retrieval_mode : 'auto'
291  const asked = typeof planned.query === 'string' && planned.query.trim() !== '' ? planned.query : query
292  return {
293    args: {
294      query: asked,
295      keywords,
296      alternate_queries: strings(planned.alternate_queries, 3),
297      entity_names: entities,
298      retrieval_mode: mode,
299    },
300    plan: {
301      by: 'haiku',
302      query: asked,
303      keywords: strings(planned.keywords, 12),
304      entities,
305      mode,
306      ms: (await $.clock.now()) - started,
307      project: situation.project,
308    },
309    skip: planned.skip === true,
310  }
311}
312
313async function recall($: EngineInterface, prompt: string): Promise<Recall | 'skip'> {
314  const started = await $.clock.now()
315  const { args, plan, skip } = await planRecall($, prompt)
316  if (skip) return 'skip'
317  const asked = { ...args, top_k_memories: TOP_K, top_k_knowledge: TOP_K, graph_light: true }
318  // A hit that is one long document can take the whole reply past the host's
319  // limit. The index of the same recall is a line per hit: it loses who wrote
320  // each one, and keeps the recall.
321  const payload = (await callTool($, 'knowledge_memory_recall', asked).catch(err => {
322    if (err instanceof NotJSON && err.tooLarge) return callTool($, 'knowledge_memory_recall', { ...asked, detail: 'index' })
323    throw err
324  })) as RecallPayload
325  const terms = [...plan.keywords, ...plan.entities]
326  const memoryMode = payload.memory_decision?.effective_mode
327  const knowledgeMode = payload.knowledge_decision?.effective_mode
328  const hits: RecallHit[] = [
329    ...(payload.memories ?? []).map(m => {
330      const content = m.memory?.content ?? ''
331      return {
332        kind: 'memory' as const,
333        title: m.memory?.id ?? '',
334        snippet: snippetOf(content),
335        why: { ...memoryVia(m, memoryMode), matched: matchedIn(content, terms) },
336        origin: memoryOrigin(m.memory),
337      }
338    }),
339    ...(payload.knowledge ?? payload.results ?? []).map(k => ({
340      kind: 'knowledge' as const,
341      title: k.title || k.knowledge_id || '',
342      snippet: snippetOf(k.snippet ?? ''),
343      why: { ...knowledgeVia(k, knowledgeMode), matched: matchedIn(`${k.title ?? ''} ${k.snippet ?? ''}`, terms) },
344      origin: knowledgeOrigin(k),
345    })),
346  ].filter(hit => hit.snippet !== '')
347  return { hits, ms: (await $.clock.now()) - started, plan }
348}
349
350// The plan's terms a hit actually contains: the part of "why this came back"
351// a person can check by reading the line.
352const matchedIn = (text: string, terms: string[]) => {
353  const lower = text.toLowerCase()
354  return [...new Set(terms.filter(term => term.length >= 2 && lower.includes(term.toLowerCase())))].slice(0, 4)
355}
356
357// The retrievers that found a memory, as the brain names them, with the raw
358// similarity when meaning was one of them. The hit's score is that similarity
359// after importance and recency boosts, so it is never shown as one. A brain
360// before v2.134 names neither: its decision says which mode ran.
361const memoryVia = (m: MemoryHit, mode: string | undefined): Omit<HitWhy, 'matched'> => {
362  const via = m.via ?? []
363  const vector = typeof m.similarity === 'number' && m.similarity > 0 ? { vector: m.similarity } : {}
364  if (via.includes('semantic') && via.includes('keyword')) return { via: 'hybrid', ...vector }
365  if (via.includes('semantic')) return { via: 'semantic', ...vector }
366  if (via.includes('graph')) return { via: 'graph' }
367  if (via.includes('keyword')) return { via: 'keyword' }
368  if (mode === 'graph') return { via: 'graph' }
369  return { via: mode === 'lexical' ? 'keyword' : 'semantic' }
370}
371
372// The retriever that found a knowledge hit, read off the scores each one gave
373// it. The fused score beside them only orders the list.
374const knowledgeVia = (k: KnowledgeHit, mode: string | undefined): Omit<HitWhy, 'matched'> => {
375  const vector = k.vector_score && k.vector_score > 0 ? k.vector_score : undefined
376  const lexical = k.lexical_score && k.lexical_score > 0 ? k.lexical_score : undefined
377  if (vector !== undefined && lexical !== undefined) return { via: 'hybrid', vector, lexical }
378  if (vector !== undefined) return { via: 'semantic', vector }
379  if (lexical !== undefined) return { via: 'keyword', lexical }
380  if (mode === 'graph') return { via: 'graph' }
381  return { via: mode === 'lexical' ? 'keyword' : 'semantic' }
382}
383
384// The single shared token every client of an unkeyed brain speaks with names
385// nobody in particular, so it is left out rather than shown on every line.
386const SHARED_KEY = 'legacy-token'
387
388const text = (value: unknown) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined)
389
390const compact = (origin: HitOrigin): HitOrigin | undefined => {
391  const kept = Object.fromEntries(Object.entries(origin).filter(([, v]) => v !== undefined)) as HitOrigin
392  return Object.keys(kept).length > 0 ? kept : undefined
393}
394
395const memoryOrigin = (m: RecallMemory | undefined) => {
396  const meta = m?.metadata ?? {}
397  const writer = text(meta.written_by)
398  return compact({
399    date: text(meta.date) ?? text(m?.created_at)?.slice(0, 10),
400    writer: writer === SHARED_KEY ? undefined : writer,
401    source: text(meta.source),
402    model: text(meta.model),
403    agent: text(meta.agent),
404    host: text(meta.host),
405    project: text(meta.project),
406    session: text(meta.session)?.slice(0, 8),
407  })
408}
409
410const knowledgeOrigin = (k: KnowledgeHit) => {
411  const meta = k.metadata ?? {}
412  const writer = text(meta.written_by)
413  return compact({
414    date: (text(meta.updated) ?? text(meta.date))?.slice(0, 10),
415    writer: writer === SHARED_KEY ? undefined : writer,
416    source: text(k.author) ?? text(meta.source),
417    agent: text(meta.agent),
418    host: text(meta.host),
419    project: text(meta.project),
420    session: text(meta.session)?.slice(0, 8),
421    url: text(k.source_url),
422  })
423}
424
425// --- capture ----------------------------------------------------------------
426
427// The shell capture's prompt (cmd/cortexdb-mcp-stdio/capture_session.go), so a
428// memory reads the same whichever wrote it, plus what this session already gave.
429const CAPTURE_SYSTEM = `You distil a coding-session transcript into durable memories for a long-term store shared across future sessions.
430
431Extract ONLY things worth knowing weeks later: decisions made and why, facts established (deployments, topology, versions, credentials locations — not values), user preferences expressed, outcomes and their root causes, lessons that changed how something is done.
432
433Rules:
434- One self-contained fact per memory. Never bundle; a reader sees one memory alone.
435- Each content must make sense with zero session context: name the project and subject explicitly, use absolute dates.
436- Write each memory in the language the conversation used for that topic.
437- Skip: transient debugging steps, anything superseded within the session, tool chatter, politeness, plans that were replaced.
438- 0 to 8 memories. An uneventful stretch yields zero — that is a good answer.
439- The transcript is the part of the session not yet captured; memories already written from earlier parts are listed. Reuse one's slug only to replace it with a corrected or extended version; never repeat one.
440- slug: short kebab-case ascii. importance: 0.3 routine fact, 0.6 useful decision, 0.85+ hard-won lesson or standing preference.
441- entities: the concrete named things (projects, hosts, services, people) each memory is about.
442- When a memory is about specific files listed under FILES, add each of those files as an entity of type "file", named exactly as listed. Leave out files a memory is not about; a memory about none has no file entities.
443
444Respond with JSON only: {"memories":[{"slug":"...","content":"...","importance":0.6,"type":"fact|decision|preference|lesson","entities":[{"name":"...","type":"..."}]}]}`
445
446type CapturedReply = {
447  memories?: {
448    slug?: string
449    content?: string
450    importance?: number
451    type?: string
452    entities?: { name?: string; type?: string }[]
453  }[]
454}
455
456// --- retiring what a capture made untrue -------------------------------------
457
458// The shell capture's step (cmd/cortexdb-mcp-stdio/capture_supersede.go), with
459// the same prompt and the same limits: each new memory is looked up, and
460// haiku says which older memories it makes untrue. Those are saved as
461// superseded — kept, linked forward, no longer recalled as current — so a
462// wrong call is undone by clearing one key. The later date wins.
463const CANDIDATES_PER_MEMORY = 4
464const CANDIDATE_LIMIT = 24
465const MAX_SUPERSEDES = 5
466
467const SUPERSEDE_SYSTEM = `You maintain an AI agent's long-term memory. A session just produced NEW memories. EXISTING memories are already stored, each with the date it was recorded.
468
469Decide, for each NEW memory, whether it makes an EXISTING memory untrue: the same thing, with a different current value (a host moved, a version changed, a decision was reversed, a preference changed, a plan was dropped, something "not done yet" is now done). The memory dated later wins:
470- "retire": a NEW memory replaces EXISTING memories dated on or before the session.
471- "outdated": a NEW memory is itself contradicted by an EXISTING memory dated after the session; it should not be saved.
472
473Be strict. Being about the same topic is not enough; adding detail is not a contradiction; two facts that can both be true are not one. When unsure, leave it out — an outdated memory left in place is a smaller harm than a true one retired.
474
475Name memories exactly as listed: a NEW memory by its "new" name, an EXISTING one by its "old" id — never by a date.
476
477Respond with JSON only: {"retire":[{"new":"<new name>","old":["<old id>"],"reason":"..."}],"outdated":[{"new":"<new name>","by":"<old id>"}]}`
478
479type Fresh = { slug: string; content: string; entities: { name: string; type: string }[] }
480type Candidate = { id: string; content: string; date: string }
481type Retirement = { retire: Map<string, string[]>; reason: Map<string, string>; outdated: Set<string> }
482
483const noRetirement = (): Retirement => ({ retire: new Map(), reason: new Map(), outdated: new Set() })
484
485// A memory speaks for the day of its session when it says, else the day it
486// was stored. One with neither is never compared: no one can say which is later.
487const dateOf = (memory: { metadata?: { date?: unknown }; created_at?: string }) => {
488  const date = typeof memory.metadata?.date === 'string' ? memory.metadata.date : memory.created_at ?? ''
489  return /^\d{4}-\d{2}-\d{2}/.test(date) ? date.slice(0, 10) : ''
490}
491
492async function candidatesFor($: EngineInterface, fresh: Fresh[], ownPrefix: string) {
493  const seen = new Set<string>()
494  const out: Candidate[] = []
495  for (const m of fresh) {
496    let payload: RecallPayload
497    try {
498      payload = (await callTool($, 'knowledge_memory_recall', {
499        query: clip(m.content, 400),
500        entity_names: m.entities.map(e => e.name),
501        top_k_memories: CANDIDATES_PER_MEMORY,
502        disable_knowledge: true,
503        graph_light: true,
504      })) as RecallPayload
505    } catch {
506      continue // finding nothing to retire is the safe failure
507    }
508    for (const hit of payload.memories ?? []) {
509      const id = hit.memory?.id ?? ''
510      const date = hit.memory ? dateOf(hit.memory) : ''
511      // This session's own memories are rewritten by slug, not superseded.
512      if (id === '' || date === '' || seen.has(id) || id.startsWith(ownPrefix)) continue
513      seen.add(id)
514      out.push({ id, content: hit.memory?.content ?? '', date })
515      if (out.length >= CANDIDATE_LIMIT) return out
516    }
517  }
518  return out
519}
520
521type RetireReply = {
522  retire?: { new?: string; old?: unknown; reason?: string }[]
523  outdated?: { new?: string; by?: string }[]
524}
525
526// Models embellish names ("later-deploy (2026-11-02)"); read back only the
527// names that were given, never one made up or a date.
528const nameIn = (said: string, names: string[]) => {
529  const s = said.trim()
530  let best = ''
531  for (const n of names) {
532    if (s === n) return n
533    if (n.length > best.length && (s.startsWith(`${n} `) || s.startsWith(`${n}(`) || s.includes(`"${n}"`))) best = n
534  }
535  return best
536}
537
538async function planRetirement($: EngineInterface, fresh: Fresh[], ownPrefix: string, session: string) {
539  const plan = noRetirement()
540  const candidates = await candidatesFor($, fresh, ownPrefix)
541  if (fresh.length === 0 || candidates.length === 0) return plan
542  const prompt = [
543    `The session is dated ${session}.`,
544    '',
545    'NEW memories:',
546    ...fresh.map(m => `- new ${JSON.stringify(m.slug)}: ${clip(m.content, 400)}`),
547    '',
548    'EXISTING memories:',
549    ...candidates.map(c => `- old ${JSON.stringify(c.id)}, recorded ${c.date}: ${clip(c.content.trim(), 400)}`),
550  ].join('\n')
551  const reply = await $.model.complete({ model: PLANNER, system: SUPERSEDE_SYSTEM, prompt, maxTokens: 1500, timeoutMs: 60 * 1000 })
552  if (!reply.isAnswered) return plan
553  const out = parseJSON<RetireReply>(reply.text)
554  if (!out) return plan
555
556  const slugs = fresh.map(m => m.slug)
557  const ids = candidates.map(c => c.id)
558  const byId = new Map(candidates.map(c => [c.id, c]))
559  for (const o of out.outdated ?? []) {
560    const slug = nameIn(o.new ?? '', slugs)
561    const later = byId.get(nameIn(o.by ?? '', ids))
562    if (slug && later && later.date > session) plan.outdated.add(slug)
563  }
564  let budget = MAX_SUPERSEDES
565  const retired = new Set<string>()
566  for (const r of out.retire ?? []) {
567    const slug = nameIn(r.new ?? '', slugs)
568    if (!slug || plan.outdated.has(slug)) continue
569    const chosen = strings(r.old, CANDIDATE_LIMIT)
570      .map(said => nameIn(said, ids))
571      .filter(id => {
572        const c = byId.get(id)
573        if (!c || retired.has(id) || c.date > session || budget === 0) return false
574        retired.add(id)
575        budget -= 1
576        return true
577      })
578    if (chosen.length === 0) continue
579    plan.retire.set(slug, [...(plan.retire.get(slug) ?? []), ...chosen])
580    if (r.reason?.trim()) plan.reason.set(slug, clip(r.reason.trim(), 300))
581  }
582  return plan
583}
584
585type Message = { role: string; text: string; toolUses: readonly unknown[] }
586
587const keyOf = (m: Message) => `${m.role}:${m.toolUses.length}:${m.text.slice(0, 160)}`
588
589async function capture($: EngineInterface) {
590  if (isCapturing || (await sentinel($, 'autocapture'))?.startsWith('off')) return
591  isCapturing = true
592  try {
593    const sessionId = await $.session.id()
594    const history = await $.session.messages()
595    if (!Array.isArray(history) || history.length === 0) return
596    const kept = await read($, captureMark)
597    const mark: CaptureMark = kept?.sessionId === sessionId ? kept : { sessionId, lastKey: '', memories: [] }
598    const from = mark.lastKey === '' ? -1 : history.map(keyOf).lastIndexOf(mark.lastKey)
599    const fresh = history.slice(from + 1)
600
601    let root = ''
602    try {
603      root = await $.session.root()
604    } catch {
605      // A build without session.root, or one that cannot name it: the digest
606      // keeps absolute paths.
607    }
608    const { digest, userTurns } = digestOf(fresh, root)
609    const home = await $.env.get('HOME')
610    const project = root && root !== home ? root.split('/').filter(Boolean).at(-1) : undefined
611    if (userTurns < CAPTURE_MIN_USER_TURNS) return
612
613    const already = mark.memories.map(m => `- ${m.slug}: ${clip(m.content, 300)}`).join('\n')
614    const reply = await $.model.complete({
615      model: PLANNER,
616      system: CAPTURE_SYSTEM,
617      prompt: `Today is ${today()}.\n\nAlready captured from this session:\n${already || '(none)'}\n\nTranscript not yet captured:\n${digest}`,
618      maxTokens: 3000,
619      timeoutMs: 90 * 1000,
620    })
621    if (!reply.isAnswered) return
622    const out = parseJSON<CapturedReply>(reply.text)
623    if (!out) return
624
625    // Stable per session and slug, as the shell capture's: capturing again
626    // replaces a memory instead of stacking a second copy.
627    const ownPrefix = `auto:${sessionId.slice(0, 8)}:`
628    const drafts: (Fresh & { importance?: number; type?: string })[] = []
629    for (const m of out.memories ?? []) {
630      const content = (m.content ?? '').trim()
631      const slug = slugOf(m.slug || content)
632      if (content === '' || slug === '') continue
633      const entities = (m.entities ?? [])
634        .map(entity => ({ name: (entity.name ?? '').trim(), type: entity.type ?? '' }))
635        .filter(entity => entity.name !== '')
636      drafts.push({ slug, content, entities, importance: m.importance, type: m.type })
637    }
638    // Failing here saves everything and retires nothing, as capture always did.
639    const plan = await planRetirement($, drafts, ownPrefix, today()).catch(noRetirement)
640
641    const written: CapturedMemory[] = []
642    let retiredCount = 0
643    for (const m of drafts) {
644      if (plan.outdated.has(m.slug)) continue
645      const supersedes = plan.retire.get(m.slug) ?? []
646      const reason = plan.reason.get(m.slug)
647      await callTool($, 'memory_save', {
648        memory_id: ownPrefix + m.slug,
649        scope: 'global',
650        content: m.content,
651        importance: Math.min(1, Math.max(0, m.importance ?? 0.5)),
652        metadata: {
653          source: 'auto-capture',
654          agent: 'claude-code',
655          session: sessionId,
656          ...(project ? { project } : {}),
657          ...(host ? { host } : {}),
658          date: today(),
659          type: m.type || 'fact',
660          model: PLANNER,
661          ...(reason ? { supersede_reason: reason } : {}),
662        },
663        entities: m.entities,
664        ...(supersedes.length > 0 ? { supersedes } : {}),
665      })
666      written.push({ slug: m.slug, content: m.content })
667      retiredCount += supersedes.length
668    }
669
670    const end = fresh.at(-1)
671    const memories = [...mark.memories.filter(m => !written.some(w => w.slug === m.slug)), ...written]
672    await update($, captureMark, () => ({ sessionId, lastKey: end ? keyOf(end) : mark.lastKey, memories }))
673    if (written.length > 0) $.ui.toast(t().captured(written.length, retiredCount))
674  } catch (err) {
675    $.ui.log(`cortexdb-live: capture failed: ${messageOf(err)}`)
676  } finally {
677    isCapturing = false
678  }
679}
680
681function scheduleCapture($: EngineInterface) {
682  idleTimer?.cancel()
683  idleTimer = $.clock.after(CAPTURE_IDLE_MS, () => void capture($))
684}
685
686// --- hooks ------------------------------------------------------------------
687
688export const register: Register = (on, options) => {
689  on('session.start', async ($, e, next) => {
690    lang = await resolveLang($, options)
691    const remote = await $.env.get('CORTEXDB_REMOTE')
692    const path = await $.env.get('CORTEXDB_PATH')
693    brain = { where: remote ? remote.replace(/:\d+$/, '') : path ? path.split('/').pop() : undefined }
694    // The plugin's shell hooks stand down for a session this module answers.
695    await $.env.set('CORTEXDB_RECALL_BY_MOD', '1')
696    await $.env.set('CORTEXDB_CAPTURE_BY_MOD', '1')
697    await $.command.register({ name: SHOW_COMMAND, description: t().showCommand })
698    const named = await $.process.run(['hostname', '-s']).catch(() => undefined)
699    host = named?.exitCode === 0 ? named.stdout.trim() || undefined : undefined
700    void refreshStats($)
701    $.clock.every(STATS_EVERY_MS, () => void refreshStats($))
702    return next(e)
703  })
704
705  // Hide lasts until the next recall; this brings back the one hidden now.
706  on('command.run', { command: SHOW_COMMAND }, async $ => {
707    const found = await read($, last)
708    if (!found || found.hits.length === 0) return { text: t().nothingShown }
709    await update($, isHidden, () => false)
710    await update($, isOpen, () => true)
711    return { text: t().shown }
712  })
713
714  on('classic.UserPromptSubmit', async ($, e, next) => {
715    const prompt = e.prompt.trim()
716    const asked =
717      prompt !== '' && (await sentinel($, 'autorecall'))?.startsWith('on')
718        ? Promise.race([
719            recall($, prompt).catch(err => {
720              brain = { ...brain, error: isDenied(err) ? t().denied(TOOLS_TO_ALLOW) : `${t().recallFailed}: ${messageOf(err)}` }
721              return undefined
722            }),
723            $.clock.sleep(RECALL_BUDGET_MS).then(() => undefined),
724          ])
725        : Promise.resolve(undefined)
726
727    const [result, found] = await Promise.all([next(e), asked])
728    if (!found) {
729      showStatus($)
730      return result
731    }
732
733    const others = (result.additionalContext ?? []).filter(text => !text.startsWith(SHELL_HEADER))
734    if (found === 'skip') {
735      brain = { ...brain, error: undefined, skipped: true }
736      showStatus($)
737      await update($, last, () => null)
738      return { ...result, additionalContext: others }
739    }
740
741    brain = { ...brain, error: undefined, skipped: false, recallMs: found.ms }
742    if (brain.nodes === undefined) void refreshStats($)
743    showStatus($)
744    await update($, last, () => found)
745    await update($, isHidden, () => false)
746    const mine = contextOf(found.hits)
747    return { ...result, additionalContext: mine ? [...others, mine] : others }
748  }).catch(($, e, next) => next(e))
749
750  on('turn.complete', ($, e, next) => {
751    if (e.agentId === undefined) scheduleCapture($)
752    return next(e)
753  })
754
755  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
756    const found = await read($, last)
757    if (e.props.hasSurvey || !found || found.hits.length === 0 || (await read($, isHidden))) {
758      return next(e)
759    }
760
761    const { Box, Button, Text } = $.ui.resolve(e)
762    const s = t()
763    const open = await read($, isOpen)
764    const memories = found.hits.filter(hit => hit.kind === 'memory').length
765    const knowledge = found.hits.length - memories
766    const plan = found.plan
767
768    return (
769      <Box flexDirection="column">
770        <Box flexDirection="row" gap={1}>
771          <Text>
772            {s.recalled(found.hits.length)}
773            <Text dimColor>{s.detail(memories, knowledge, (found.ms / 1000).toFixed(1))}</Text>
774          </Text>
775          <Button key="toggle" plain label={open ? s.collapse : s.expand} onPress={() => update($, isOpen, v => !v)} />
776          <Button key="hide" plain label={s.hide} onPress={() => update($, isHidden, () => true)} />
777        </Box>
778        {open && (
779          <Text wrap="truncate-end" dimColor>
780            {'  '}
781            {s.query} ({plan.by}): {plan.keywords.join(' · ')}
782            {plan.entities.length > 0 ? ` | ${s.entities}: ${plan.entities.join(', ')}` : ''}
783          </Text>
784        )}
785        {open && plan.query && (
786          <Text wrap="truncate-end" dimColor>
787            {'  '}
788            {plan.project ? `${s.project} ${plan.project} · ` : ''}
789            {oneLine(plan.query)}
790          </Text>
791        )}
792        {open &&
793          found.hits.flatMap(hit => {
794            const explained = explainOf(hit, s)
795            return [
796              <Text wrap="truncate-end" dimColor>
797                {'  '}
798                {hit.kind === 'memory' ? s.memory : s.knowledge} <Text bold>{hit.title}</Text> {hit.snippet}
799              </Text>,
800              ...(explained
801                ? [
802                    <Text wrap="truncate-end" dimColor>
803                      {'      '}
804                      {explained}
805                    </Text>,
806                  ]
807                : []),
808            ]
809          })}
810      </Box>
811    )
812  })
813}
814
815// --- text -------------------------------------------------------------------
816
817type RecallMemory = { id?: string; content?: string; metadata?: Record<string, unknown>; created_at?: string }
818
819type KnowledgeHit = {
820  knowledge_id?: string
821  title?: string
822  snippet?: string
823  author?: string
824  source_url?: string
825  vector_score?: number
826  lexical_score?: number
827  metadata?: Record<string, string>
828}
829
830type MemoryHit = { memory?: RecallMemory; score?: number; similarity?: number; via?: string[] }
831
832type RecallPayload = {
833  memory_decision?: { effective_mode?: string }
834  knowledge_decision?: { effective_mode?: string }
835  memories?: MemoryHit[]
836  knowledge?: KnowledgeHit[]
837  results?: KnowledgeHit[]
838}
839
840// The text the model reads: the same block the shell hook writes, so an agent
841// sees one thing whichever of the two answered.
842// Cut whole lines from the end under the budget the shell hook keeps
843// (hook_budget.go): an oversized block reaches the model as a short preview.
844const CONTEXT_BUDGET = 9000
845const contextOf = (hits: RecallHit[]) => {
846  if (hits.length === 0) return ''
847  const header = `${SHELL_HEADER} (retrieved automatically — verify before relying on them):`
848  const footer = '(If this exchange states a durable preference, decision, or fact, save it with memory_save / knowledge_save.)'
849  const all = hits.map(hit => {
850    const trail = trailOf(hit)
851    return `- ${hit.title}${trail ? ` [${trail}]` : ''}: ${hit.snippet}`
852  })
853  let kept = all
854  let note = ''
855  const size = (parts: string[]) => parts.reduce((n, p) => n + [...p].length + 1, 0)
856  while (kept.length > 0 && size([header, footer, note, ...kept]) > CONTEXT_BUDGET) {
857    kept = kept.slice(0, -1)
858    note = `(${all.length - kept.length} more not shown here; ask CortexDB for them with knowledge_memory_recall.)`
859  }
860  return [header, ...kept, ...(note ? [note] : []), footer].join('\n')
861}
862
863// Where a hit came from and why it came back, as one bracket the model can
864// weigh before relying on it: the date, who wrote it, from which session and
865// project, and the retriever's score. The same words the shell hook writes.
866const trailOf = (hit: RecallHit) => {
867  const o = hit.origin ?? {}
868  const by = [o.agent, o.source, o.model ? `(${o.model})` : undefined].filter(Boolean).join(' ')
869  const parts = [
870    o.date,
871    by || undefined,
872    o.writer ? `key ${o.writer}` : undefined,
873    o.host ? `host ${o.host}` : undefined,
874    o.project ? `project ${o.project}` : undefined,
875    o.session ? `session ${o.session}` : undefined,
876    o.url,
877    hit.why ? scoreOf(hit.why, VIA_EN) : undefined,
878  ]
879  return parts.filter(Boolean).join(' · ')
880}
881
882const VIA_EN = STRINGS.en.via
883
884const scoreOf = (why: HitWhy, via: Record<HitWhy['via'], string>) => {
885  const n = (v: number) => v.toFixed(2)
886  if (why.via === 'hybrid' && why.vector !== undefined && why.lexical !== undefined) {
887    return `${via.semantic} ${n(why.vector)} + ${via.keyword} ${n(why.lexical)}`
888  }
889  if (why.via === 'hybrid' && why.vector !== undefined) return `${via.semantic} ${n(why.vector)} + ${via.keyword}`
890  const score = why.vector ?? why.lexical
891  return score === undefined ? via[why.via] : `${via[why.via]} ${n(score)}`
892}
893
894// The band's second line under a hit: why it came back, then where from.
895const explainOf = (hit: RecallHit, s: (typeof STRINGS)[Lang]) => {
896  const why = hit.why
897    ? [scoreOf(hit.why, s.via), hit.why.matched.length > 0 ? `${s.matched} ${hit.why.matched.join(' / ')}` : undefined]
898        .filter(Boolean)
899        .join(' · ')
900    : ''
901  const o = hit.origin ?? {}
902  const from = [
903    [o.agent, o.source, o.model ? `(${o.model})` : undefined].filter(Boolean).join(' ') || undefined,
904    o.writer ? `${s.key} ${o.writer}` : undefined,
905    o.host,
906    o.project ? `${s.project} ${o.project}` : undefined,
907    o.session ? `${s.session} ${o.session}` : undefined,
908    o.url,
909    o.date,
910  ]
911    .filter(Boolean)
912    .join(' · ')
913  return [why ? `${s.why} ${why}` : '', from ? `${s.from} ${from}` : ''].filter(Boolean).join('  ')
914}
915
916// The shell capture's digestTranscript: what the person typed and what the
917// assistant said, injected machinery stripped, head kept and the tail favoured.
918const NOISE =
919  /<(system-reminder|local-command-caveat|command-name|command-message|command-args|local-command-stdout|task-notification)>[\s\S]*?<\/\1>|\[SYSTEM NOTIFICATION[^\]]*\][\s\S]*/g
920
921// The shell capture's scrubForCapture (cmd/cortexdb-mcp-stdio/scrub.go): text
922// between <private> tags never reaches the model, and credentials in the shapes
923// they are issued in become [REDACTED] before anything is distilled or stored.
924const PRIVATE = /<private>[\s\S]*?(?:<\/private>|$)/gi
925const SECRETS = [
926  /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g,
927  /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g,
928  /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}/g,
929  /\bgithub_pat_[A-Za-z0-9_]{22,}/g,
930  /\bglpat-[A-Za-z0-9_-]{20,}/g,
931  /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
932  /\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
933  /\bAIza[0-9A-Za-z_-]{35}/g,
934  /\bnpm_[A-Za-z0-9]{36}/g,
935  /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/gi,
936]
937const ASSIGNED_SECRET =
938  /\b([A-Za-z0-9_]*(?:password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_]*)(\s*[:=]\s*)("[^"\s]{6,}"|'[^'\s]{6,}'|[^\s"',;]{6,})/gi
939const scrubForCapture = (text: string) =>
940  SECRETS.reduce((t, re) => t.replace(re, '[REDACTED]'), text.replace(PRIVATE, '')).replace(ASSIGNED_SECRET, '$1$2[REDACTED]')
941
942// The files a session read and modified, named from the project root, as the
943// shell capture's FILES block (cmd/cortexdb-mcp-stdio/files.go): the model
944// links each memory to the ones it is about.
945const FILE_TOOLS = new Set(['Read', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
946const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
947const filesOf = (messages: readonly Message[], root: string) => {
948  const modified: string[] = []
949  const read: string[] = []
950  const prefix = root.endsWith('/') ? root : `${root}/`
951  for (const m of messages) {
952    for (const use of m.toolUses as { tool?: string; input?: Record<string, unknown> }[]) {
953      const tool = use?.tool ?? ''
954      const raw = use?.input?.file_path ?? use?.input?.notebook_path
955      if (!FILE_TOOLS.has(tool) || typeof raw !== 'string' || raw === '') continue
956      const name = root && raw.startsWith(prefix) ? raw.slice(prefix.length) : raw
957      const list = EDIT_TOOLS.has(tool) ? modified : read
958      if (!list.includes(name) && modified.length + read.length < 40) list.push(name)
959    }
960  }
961  const onlyRead = read.filter(f => !modified.includes(f)).sort()
962  if (modified.length + onlyRead.length === 0) return ''
963  return [
964    'FILES (paths from the repository root)',
965    ...(modified.length ? [`modified: ${modified.join(', ')}`] : []),
966    ...(onlyRead.length ? [`read: ${onlyRead.join(', ')}`] : []),
967    '',
968    '',
969  ].join('\n')
970}
971
972const digestOf = (messages: readonly Message[], root = '') => {
973  const lines: string[] = []
974  let userTurns = 0
975  for (const m of messages) {
976    if (m.role === 'user') {
977      const text = scrubForCapture(m.text.replace(NOISE, '')).trim()
978      if (text === '') continue
979      userTurns += 1
980      lines.push(`USER: ${clip(text, 2000)}`)
981    } else {
982      const text = scrubForCapture(m.text).trim()
983      if (text !== '') lines.push(`ASSISTANT: ${clip(text, 1200)}`)
984    }
985  }
986  const head = 6000
987  const tail = 22000
988  const all = lines.join('\n')
989  const body = all.length > head + tail ? `${all.slice(0, head)}\n[...trimmed...]\n${all.slice(-tail)}` : all
990  return { digest: filesOf(messages, root) + body, userTurns }
991}
992
993// Models fence JSON on a whim and the odd reply loses its last closer.
994function parseJSON<T>(raw: string): T | undefined {
995  const start = raw.indexOf('{')
996  const end = raw.lastIndexOf('}')
997  if (start < 0) return undefined
998  const body = raw.slice(start, end > start ? end + 1 : undefined)
999  for (const candidate of [body, `${body}}`, `${body}]}`, `${body}}]}`]) {
1000    try {
1001      return JSON.parse(candidate) as T
1002    } catch {
1003      // try the next repair
1004    }
1005  }
1006  return undefined
1007}
1008
1009const strings = (list: unknown, max: number) =>
1010  Array.isArray(list) ? list.filter((s): s is string => typeof s === 'string' && s.trim() !== '').slice(0, max) : []
1011
1012const oneLine = (text: string) => text.split(/\s+/).filter(Boolean).join(' ')
1013
1014const snippetOf = (content: string) => clip(content.split(/\s+/).filter(Boolean).join(' '), SNIPPET)
1015
1016const clip = (text: string, max: number) => {
1017  const chars = Array.from(text)
1018  return chars.length <= max ? text : `${chars.slice(0, max).join('').trim()}…`
1019}
1020
1021const slugOf = (text: string) =>
1022  text
1023    .toLowerCase()
1024    .replace(/[^a-z0-9]+/g, '-')
1025    .replace(/^-+|-+$/g, '')
1026    .slice(0, 60)
1027
1028const today = () => new Date().toISOString().slice(0, 10)
1029
1030const messageOf = (err: unknown) => String((err as Error)?.message ?? err).slice(0, 80)
1031
1032// A call the module makes goes through the session's permission rules like
1033// the model's, and a hook has no prompt to ask with: without an allow rule the
1034// call is denied, which says nothing about the brain itself.
1035const isConnecting = (err: unknown) => /no connected MCP tool/i.test(String((err as Error)?.message ?? err))
1036
1037const isDenied = (err: unknown) => /refused|denied|permission/i.test(String((err as Error)?.message ?? err))
1038
1039// The tools this module calls, as permissions.allow spells them.
1040const TOOLS_TO_ALLOW = ['knowledge_memory_recall', 'graph_statistics', 'memory_save']
1041  .map(tool => `mcp__plugin_cortexdb_cortexdb__${tool}`)
1042  .join(', ')
1043
1044// The shell hook's keywordsFromPrompt: letter and digit runs, lowercased,
1045// deduped, two characters or more; a CJK run stays one token.
1046const keywordsOf = (prompt: string) => {
1047  const seen = new Set<string>()
1048  for (const word of prompt.toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
1049    if (Array.from(word).length >= 2) seen.add(word)
1050  }
1051  return [...seen]
1052}
1053
types/index.d.ts 48 lines
1/** Which retriever found a hit, and how strongly. score is that retriever's own, not the fused rank value. */
2export type HitWhy = { via: 'semantic' | 'keyword' | 'hybrid' | 'graph'; vector?: number; lexical?: number; matched: string[] }
3
4/** Who wrote a hit and where it came from, as far as the store recorded it. */
5export type HitOrigin = {
6  date?: string
7  /** The key the brain authenticated the save with. */
8  writer?: string
9  source?: string
10  model?: string
11  agent?: string
12  host?: string
13  project?: string
14  session?: string
15  url?: string
16}
17
18export type RecallHit = { kind: 'memory' | 'knowledge'; title: string; snippet: string; why?: HitWhy; origin?: HitOrigin }
19
20/** query is what was asked after the conversation resolved the message; project is the session's. */
21export type RecallPlan = {
22  by: 'haiku' | 'lexical'
23  query: string
24  keywords: string[]
25  entities: string[]
26  mode: string
27  ms: number
28  project?: string
29}
30
31export type Recall = { hits: RecallHit[]; ms: number; plan: RecallPlan }
32
33export type CapturedMemory = { slug: string; content: string }
34
35/** How far this session has been captured: the last message read, and what it wrote. */
36export type CaptureMark = { sessionId: string; lastKey: string; memories: CapturedMemory[] }
37
38declare module 'claude-code' {
39  interface PluginState {
40    'cortexdb-live': {
41      last: Recall | null
42      isOpen: boolean
43      isHidden: boolean
44      capture: CaptureMark | null
45    }
46  }
47}
48