@kolivri/memoreal-mcp 1.0.2 → 1.1.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.
@@ -1,14 +1,67 @@
1
- import { execFileSync } from "node:child_process"
2
- import { readFileSync } from "node:fs"
1
+ import { fileURLToPath, pathToFileURL } from "node:url"
2
+ import { existsSync, readFileSync } from "node:fs"
3
3
  import { join } from "node:path"
4
4
  import { homedir } from "node:os"
5
+ import { execFileSync } from "node:child_process"
6
+ import { createHash } from "node:crypto"
7
+
8
+ let nsModule = null
9
+ {
10
+ const candidates = [
11
+ fileURLToPath(new URL("../bin/memoreal-ns.mjs", import.meta.url)),
12
+ join(process.env.MEMOREAL_HOME || process.env.HOME || process.env.USERPROFILE || homedir(), ".memoreal", "bin", "memoreal-ns.mjs"),
13
+ join(process.env.MEMORIA_HOME || process.env.HOME || process.env.USERPROFILE || homedir(), ".memoria", "bin", "memoreal-ns.mjs"),
14
+ ]
15
+ for (const c of candidates) {
16
+ if (c && existsSync(c)) {
17
+ try { nsModule = await import(pathToFileURL(c).href); if (nsModule) break } catch {}
18
+ }
19
+ }
20
+ }
21
+
22
+ export const MEMOREAL_CLIENT_VERSION = nsModule?.MEMOREAL_CLIENT_VERSION || "1.1.0"
5
23
 
6
24
  export const ONBOARDING_WIZARD_PROMPT =
25
+ '[memoreal-session-start] Memoreal Cloud is not yet connected.\n[memoreal-setup-wizard]\n' +
7
26
  'Polite Onboarding Action: Invite the user in chat to connect their free Memoreal account (1,000 free API calls & memories) in 1 click by calling the connect_account tool (opens Chrome OAuth automatically, zero copy-paste), or share https://memoreal.kolivri.com/connect?tool=opencode (terminal wizard: npx -y @kolivri/memoreal-mcp setup). Never ask the user to paste their raw API key into chat.\n\n' +
8
- 'Drive the 3-Click Interactive In-Chat Wizard using AskUserQuestion (Claude Code) or question (OpenCode & Cursor):\n' +
9
- '- Step 1: Present choice card "Connect in 1 Click via Google / Browser (Recommended)" vs "Skip for this session".\n' +
10
- '- Step 2: Call connect_account({ action: "start" }) (tool: "opencode", client_name: "OpenCode") and present clickable https://memoreal.kolivri.com/connect?code=XXXX-YYYY link with "I clicked Authorize — Verify" card (calling connect_account({ action: "status" })).\n' +
11
- '- Step 3: Once connected, present choice card "Yes — Index repo now (Recommended)" vs "Later".'
27
+ 'Drive the 3-Click Interactive In-Chat Wizard using AskUserQuestion (Claude Code) or question (OpenCode & Cursor):\n- Step 1: Present choice card "Connect in 1 Click via Google / Browser (Recommended)" vs "Skip for this session".\n- Step 2: Call connect_account({ action: "start" }) (tool: "opencode", client_name: "OpenCode") and present clickable https://memoreal.kolivri.com/connect?code=XXXX-YYYY link with "I clicked Authorize — Verify" card (calling connect_account({ action: "status" })).\n- Step 3: Once connected, present choice card "Yes — Index repo now (Recommended)" vs "Later".'
28
+
29
+ export const PLACEHOLDER_KEY_REGEX =
30
+ /^(?:mem_dev_your_key_here|your[-_]?api[-_]?key.*|your[-_]?memoreal[-_]?api[-_]?key.*|placeholder|<[^>]+>|\$\{[^}]+\}|\.\.\.)$/i
31
+
32
+ export function isPlaceholderApiKey(raw) {
33
+ if (typeof raw !== "string") return true
34
+ let str = raw.trim()
35
+ while ((str.startsWith('"') && str.endsWith('"')) || (str.startsWith("'") && str.endsWith("'"))) str = str.slice(1, -1).trim()
36
+ if (!str || str.includes("...") || (str.startsWith("<") && str.endsWith(">")) || (str.startsWith("${") && str.endsWith("}"))) {
37
+ return true
38
+ }
39
+ if (PLACEHOLDER_KEY_REGEX.test(str)) return true
40
+ const lower = str.toLowerCase()
41
+ return (
42
+ lower === "mem_dev_your_key_here" || lower === "your_api_key" || lower === "your-api-key" ||
43
+ lower === "your-memoreal-api-key" || lower === "your_memoreal_api_key" || lower === "placeholder" ||
44
+ lower.includes("your_key_here") || lower.includes("your_api_key") || lower.includes("your-api-key") || lower.includes("your-memoreal-api-key")
45
+ )
46
+ }
47
+
48
+ export const isUnregisteredApiKey = isPlaceholderApiKey
49
+
50
+ export const invalid401Keys = new Set()
51
+ export const wizardKeyBySession = new Map()
52
+
53
+ export function isSecondaryHookSilenced(homeDir) {
54
+ if (process.env.MEMOREAL_FORCE_UNREGISTERED === "1" || process.env.MEMORIA_FORCE_UNREGISTERED === "1") return true
55
+ const { apiKey } = resolveCloudConfig(homeDir)
56
+ return !apiKey || isUnregisteredApiKey(apiKey) || invalid401Keys.has(apiKey)
57
+ }
58
+
59
+ export function buildSetupWizardPrompt(ns = "", { tool = "opencode", clientName = "OpenCode" } = {}) {
60
+ const header = ns ? `[memoreal-setup-wizard] namespace=${ns}` : `[memoreal-setup-wizard]`
61
+ return `${header}\nPolite Onboarding Action: Invite the user in chat to connect their free Memoreal account (1,000 free API calls & memories) in 1 click by calling the connect_account tool (opens Chrome OAuth automatically, zero copy-paste), or share https://memoreal.kolivri.com/connect?tool=${encodeURIComponent(
62
+ tool
63
+ )} (terminal wizard: npx -y @kolivri/memoreal-mcp setup). Never ask the user to paste their raw API key into chat.\n\nDrive the 3-Click Interactive In-Chat Wizard using AskUserQuestion (Claude Code) or question (OpenCode & Cursor):\n- Step 1: Present choice card "Connect in 1 Click via Google / Browser (Recommended)" vs "Skip for this session".\n- Step 2: Call connect_account({ action: "start" }) (tool: "${tool}", client_name: "${clientName}") and present clickable https://memoreal.kolivri.com/connect?code=XXXX-YYYY link with "I clicked Authorize — Verify" card (calling connect_account({ action: "status" })).\n- Step 3: Once connected, present choice card "Yes — Index repo now (Recommended)" vs "Later".`
64
+ }
12
65
 
13
66
  export async function isChildSession(ctx, sessionID, childCache) {
14
67
  if (sessionID && childCache?.has(sessionID)) return childCache.get(sessionID)
@@ -26,99 +79,99 @@ export async function isChildSession(ctx, sessionID, childCache) {
26
79
  }
27
80
  export const isChildSubagentSession = isChildSession
28
81
 
29
- export function isPlaceholderApiKey(raw) {
30
- if (typeof raw !== "string") return true
31
- let str = raw.trim()
32
- while ((str.startsWith('"') && str.endsWith('"')) || (str.startsWith("'") && str.endsWith("'"))) {
33
- str = str.slice(1, -1).trim()
34
- }
35
- if (!str) return true
36
- if (str.includes("...")) return true
37
- if (str.startsWith("<") && str.endsWith(">")) return true
38
- if (str.startsWith("${") && str.endsWith("}")) return true
39
- const lower = str.toLowerCase()
40
- if (
41
- lower === "mem_dev_your_key_here" ||
42
- lower === "your_api_key" ||
43
- lower === "your-api-key" ||
44
- lower === "your-memoreal-api-key" ||
45
- lower === "your_memoreal_api_key" ||
46
- lower === "placeholder" ||
47
- lower.includes("your_key_here") ||
48
- lower.includes("your_api_key") ||
49
- lower.includes("your-api-key") ||
50
- lower.includes("your-memoreal-api-key")
51
- ) {
52
- return true
53
- }
54
- return false
55
- }
56
-
57
82
  const CORRECTION_PATTERNS = [
58
- "don't",
59
- "do not",
60
- "stop",
61
- "never",
62
- "wrong",
63
- "no,",
64
- "no ",
65
- "actually",
66
- "instead",
67
- "not like that",
68
- "that's wrong",
69
- "incorrect",
83
+ "don't", "do not", "stop", "never", "wrong", "no,", "no ", "actually", "instead", "not like that", "that's wrong", "incorrect"
70
84
  ]
71
85
 
72
86
  const SKIP_ENCODE_EXT = /\.(json|lock|sum|toml|yaml|yml|cfg|ini)$|\.env/i
73
- const CODE_FILE_EXT =
74
- /\.(rs|py|ts|tsx|js|jsx|mjs|cjs|go|java|kt|kts|c|h|cc|cpp|hpp|cxx|cs|rb|php|swift|scala|sh|bash|zsh|sql|proto)$/i
75
- const PLAN_PATH_REGEX = /(?:^|\/)prd\/|(\.claude\/plans\/|\.opencode\/plans\/|docs\/.*plan|docs\/.*roadmap|design-log\/)/i
76
- const SYSTEM_SKILL_PATH_REGEX =
77
- /(\/\.claude\/plugins\/|\/\.claude\/skills\/|\/\.agents\/skills\/|\/\.config\/opencode\/)/
87
+ const CODE_FILE_EXT = /\.(rs|py|ts|tsx|js|jsx|mjs|cjs|go|java|kt|kts|c|h|cc|cpp|hpp|cxx|cs|rb|php|swift|scala|sh|bash|zsh|sql|proto)$/i
88
+ const PLAN_PATH_REGEX = /(?:^|[/\\])prd[/\\]|(\.claude[/\\]plans[/\\]|\.opencode[/\\]plans[/\\]|docs[/\\][^\r\n]*plan|docs[/\\][^\r\n]*roadmap|design-log[/\\])/i
89
+ const SYSTEM_SKILL_PATH_REGEX = /([/\\]\.claude[/\\]plugins[/\\]|[/\\]\.claude[/\\]skills[/\\]|[/\\]\.agents[/\\]skills[/\\]|[/\\]\.config[/\\]opencode[/\\]|[/\\]opencode[/\\]skills[/\\]|[/\\]opencode[/\\]plugins[/\\])/
90
+
91
+ const COMPACTION_PROMPT = (ns) =>
92
+ `[memoreal-pre-compact] Context is about to be compressed. Ensure the following are encoded into Memoreal (namespace: ${ns}) so nothing is lost:\n1. (type: episodic) Current task state: what you were working on, what is done, what remains\n2. (type: episodic) Key findings so far: bugs found, root causes identified, decisions made\n3. (type: episodic) Open questions and blockers\n4. (type: semantic) Any code patterns, architecture insights, or facts learned this session\n[memoreal-post-compact] After compression, call build_context with namespace "${ns}" and query "current task, recent progress, findings, decisions, open questions, what was I working on" and token_budget 2048 to restore critical context.`
93
+
94
+ const SESSION_END_PROMPT = (ns) =>
95
+ `[memoreal-session-end] Session is ending. Encode a session summary into Memoreal (namespace: ${ns}) with the following write gate — ONLY encode if the item would change future behavior, represents a commitment, or is a decision worth preserving. Skip transient details.\n1. (type: episodic, salience: 0.7) Session summary: what was the goal, what was accomplished, what remains unfinished\n2. (type: semantic, salience: 0.8) Key decisions made and their rationale — only decisions that affect future work\n3. (type: semantic, salience: 0.8) Lessons learned: mistakes made, corrections received, patterns discovered\n4. (type: semantic, salience: 0.6) Code patterns or architecture insights worth remembering\n5. (type: episodic, salience: 0.5) Open questions and next steps for the next session\nInclude [["source", "session-end"]] in context metadata for each. Then run consolidate on namespace "${ns}".`
96
+
97
+ const CORRECTION_PROMPT = (ns) =>
98
+ `[memoreal-correction] The user appears to be correcting your approach. After addressing the correction, encode the lesson into Memoreal (namespace: ${ns}, type: semantic, salience: 0.9) as a rule: what was wrong, what the correct approach is, and why. This ensures the mistake is never repeated in future sessions.`
99
+
100
+ const PLAN_WRITE_PROMPT = (file, ns) =>
101
+ `\n\n[memoreal-encode-plan] Plan file written: ${file}\nEncode this plan into Memoreal (namespace: ${ns}). Create MULTIPLE memories:\n1. (type: semantic) Plan overview: title, goals, phase structure, and current status\n2. (type: semantic) Key decisions and their rationale from this plan\n3. (type: episodic) Progress snapshot: what phases are done, what is next, what is blocked\n4. (type: semantic) Relationships: other files, systems, or plans referenced in this document\n5. (type: semantic) Knowledge: patterns, techniques, or lessons relevant to executing this plan\n6. (type: episodic) Ideas and open questions found in the plan\n7. (type: semantic) Reflection: what is working well, what is not, what should change in approach\n8. (type: semantic) Dream: replay and consolidate — what patterns emerge across related memories, what connections between ideas were missed, what should be strengthened or let go\n9. (type: semantic) Workflow: how we are working on this plan — tools, processes, patterns that help or hinder\nInclude the file path in context metadata for every memory.`
102
+
103
+ const PLAN_EDIT_PROMPT = (file, ns) =>
104
+ `\n\n[memoreal-encode-plan] Plan file updated: ${file}\nEncode this change into Memoreal (namespace: ${ns}). Create memories for:\n1. (type: episodic) What specifically changed in the plan and why\n2. (type: episodic) Progress update: mark completed items, note new items or phase transitions\n3. (type: semantic) Any new decisions, ideas, or insights from this edit\n4. (type: semantic) New relationships or dependencies added\n5. (type: semantic) Reflection: does this change reveal something about the approach — what is working, what needs rethinking\n6. (type: semantic) Workflow ideas: better ways to work on this plan based on what just happened\nInclude the file path in context metadata.`
105
+
106
+ const DOC_WRITE_PROMPT = (file, ns) =>
107
+ `\n\n[memoreal-encode-doc] Markdown document written: ${file}\nEncode into Memoreal (namespace: ${ns}). Create memories for:\n1. (type: semantic) Document purpose, structure, and key content\n2. (type: semantic) Decisions, patterns, or knowledge worth remembering\n3. (type: episodic) Relationships to other project work and plans\nInclude the file path in context metadata.`
108
+
109
+ const DOC_EDIT_PROMPT = (file, ns) =>
110
+ `\n\n[memoreal-encode-doc] Markdown document edited: ${file}\nEncode the change into Memoreal (namespace: ${ns}):\n1. (type: episodic) What changed and why\n2. (type: semantic) Any new knowledge, decisions, or patterns\nInclude the file path in context metadata.`
111
+
112
+ const TODO_COMPLETED_PROMPT = (ns) =>
113
+ `\n\n[memoreal-update-task] A task was just completed. Encode into Memoreal (namespace: ${ns}). Create memories for:\n1. (type: episodic) What was accomplished and which plan file it relates to\n2. (type: semantic) Lessons learned and knowledge gained from this task\n3. (type: semantic) Reflection: what went well, what was harder than expected, what to do differently next time\n4. (type: semantic) Workflow ideas: any process improvements or tool usage patterns discovered while doing this task`
114
+
115
+ export function derivePathNamespace(cwd) {
116
+ if (nsModule?.deriveNamespaceCrossOs) return nsModule.deriveNamespaceCrossOs(cwd)
117
+ let p = (cwd || process.cwd()).replace(/\\/g, "/")
118
+ p = p.replace(/\/\.local\/share\/opencode\/worktree\/[^/]+\/[^/]+(?:\/.*)?$/, "").replace(/\/\.(worktrees|claude\/worktrees|opencode\/worktrees|codex\/worktrees|cursor\/worktrees)(?:\/.*)?$/, "")
119
+ if (p.length > 1 && !/^[a-zA-Z]:\/$/.test(p)) p = p.replace(/\/+$/, "")
120
+ if (/^[a-zA-Z]:/.test(p)) p = p.replace(/^([a-zA-Z]):\/*/, "$1-")
121
+ return p.replace(/[:/]/g, "-")
122
+ }
123
+
124
+ export function sanitizeLogicalNamespace(raw) {
125
+ if (nsModule?.sanitizeLogicalNamespace) return nsModule.sanitizeLogicalNamespace(raw)
126
+ if (typeof raw !== "string") return ""
127
+ let s = raw.trim()
128
+ if (/^wing:[a-z0-9_-]+$/i.test(s)) return s.toLowerCase()
129
+ s = s.replace(/^(?:[:/]*org:)+/i, "")
130
+ if (s.startsWith("@")) s = s.replace(/^@([^/]+)\/(.+)$/, "$1-$2")
131
+ s = s.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "").toLowerCase()
132
+ if (s.length > 128) {
133
+ const hash = createHash("sha256").update(s).digest("hex").slice(0, 8)
134
+ s = s.slice(0, 119) + "-" + hash
135
+ }
136
+ return s
137
+ }
138
+
139
+ export function resolveOpenCodeNamespaceInfo(cwd, env = process.env) {
140
+ if (nsModule?.resolveProjectNamespaceInfo) return nsModule.resolveProjectNamespaceInfo(cwd, undefined, env)
141
+ return { namespace: derivePathNamespace(cwd), legacyNamespace: null, isCodeProject: false, canonicalRoot: cwd || process.cwd(), source: "fallback", clientVersion: MEMOREAL_CLIENT_VERSION }
142
+ }
78
143
 
79
144
  export function deriveNamespace(cwd) {
80
- let p = cwd || process.cwd()
81
- p = p
82
- .replace(/\/\.worktrees\/.*$/, "")
83
- .replace(/\/\.claude\/worktrees\/.*$/, "")
84
- .replace(/\/\.opencode\/worktrees\/.*$/, "")
85
- return p.replace(/\//g, "-")
145
+ return nsModule?.resolveProjectNamespaceInfo ? nsModule.resolveProjectNamespaceInfo(cwd).namespace : derivePathNamespace(cwd)
86
146
  }
87
147
 
88
148
  function gitOutput(cwd, args) {
89
149
  try {
90
- return execFileSync("git", ["-C", cwd, ...args], {
91
- encoding: "utf8",
92
- stdio: ["ignore", "pipe", "ignore"],
93
- }).trim()
150
+ return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim()
94
151
  } catch {
95
152
  return ""
96
153
  }
97
154
  }
98
155
 
99
- export function resolveCloudConfig(homeDir = process.env.MEMOREAL_HOME || process.env.HOME || homedir()) {
156
+ export function resolveCloudConfig(
157
+ homeDir = process.env.MEMOREAL_HOME || process.env.HOME || process.env.USERPROFILE || homedir()
158
+ ) {
100
159
  const isExplicitHomePassed = arguments.length > 0 && homeDir !== undefined
101
- const resolvedHome = homeDir || process.env.MEMOREAL_HOME || process.env.HOME || homedir()
102
-
103
- const isExplicitEmptyAmbientKey =
104
- !isExplicitHomePassed &&
105
- !process.env.MEMOREAL_HOME &&
106
- "MEMOREAL_API_KEY" in process.env &&
107
- process.env.MEMOREAL_API_KEY === ""
160
+ const resolvedHome = homeDir || process.env.MEMOREAL_HOME || process.env.HOME || process.env.USERPROFILE || homedir()
161
+ const isExplicitEmptyAmbientKey = !isExplicitHomePassed && !process.env.MEMOREAL_HOME && "MEMOREAL_API_KEY" in process.env && process.env.MEMOREAL_API_KEY === ""
108
162
 
109
163
  const fileVars = {}
110
164
  if (!isExplicitEmptyAmbientKey) {
111
- for (const dirName of [".memoreal", ".memoria"]) {
165
+ const configDirs = [join(resolvedHome, ".memoreal"), join(resolvedHome, ".memoria")]
166
+ if (process.env.XDG_CONFIG_HOME) configDirs.push(join(process.env.XDG_CONFIG_HOME, "memoreal"), join(process.env.XDG_CONFIG_HOME, "memoria"))
167
+ for (const dir of configDirs) {
112
168
  try {
113
- const raw = readFileSync(join(resolvedHome, dirName, "config.env"), "utf8")
169
+ const raw = readFileSync(join(dir, "config.env"), "utf8")
114
170
  for (const line of raw.split(/\r?\n/)) {
115
- const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/)
116
- if (!m) continue
117
- let val = m[2].trim()
118
- while ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
119
- val = val.slice(1, -1).trim()
120
- }
121
- if (!(m[1] in fileVars)) {
171
+ const m = line.match(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)\s*$/)
172
+ if (m && !(m[1] in fileVars)) {
173
+ let val = m[2].trim()
174
+ while ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) val = val.slice(1, -1).trim()
122
175
  fileVars[m[1]] = val
123
176
  }
124
177
  }
@@ -126,213 +179,152 @@ export function resolveCloudConfig(homeDir = process.env.MEMOREAL_HOME || proces
126
179
  }
127
180
  }
128
181
 
129
- const rawUrl =
130
- process.env.MEMOREAL_API_URL ||
131
- process.env.MEMORIA_API_URL ||
132
- (!isExplicitEmptyAmbientKey ? (fileVars.MEMOREAL_API_URL || fileVars.MEMORIA_API_URL) : "") ||
133
- process.env.MEMOREAL_URL ||
134
- process.env.MEMORIA_URL ||
135
- (!isExplicitEmptyAmbientKey ? (fileVars.MEMOREAL_URL || fileVars.MEMORIA_URL) : "") ||
136
- "https://memoria.kolivri.com"
182
+ const rawUrl = process.env.MEMOREAL_API_URL || process.env.MEMORIA_API_URL || (!isExplicitEmptyAmbientKey ? (fileVars.MEMOREAL_API_URL || fileVars.MEMORIA_API_URL) : "") || process.env.MEMOREAL_URL || process.env.MEMORIA_URL || (!isExplicitEmptyAmbientKey ? (fileVars.MEMOREAL_URL || fileVars.MEMORIA_URL) : "") || "https://memoria.kolivri.com"
137
183
  const candidateUrl = rawUrl.replace(/\/v1\/mcp\/?$/, "").replace(/\/+$/, "")
138
- const isSafeUrl =
139
- /^https:\/\/[A-Za-z0-9._:-]+(\/[A-Za-z0-9._/-]*)?$/.test(candidateUrl) ||
140
- /^http:\/\/(localhost|127\.0\.0\.1)(:[0-9]+)?(\/[A-Za-z0-9._/-]*)?$/.test(candidateUrl)
184
+ const isSafeUrl = /^https:\/\/[A-Za-z0-9._:-]+(\/[A-Za-z0-9._/-]*)?$/.test(candidateUrl) || /^http:\/\/(localhost|127\.0\.0\.1)(:[0-9]+)?(\/[A-Za-z0-9._/-]*)?$/.test(candidateUrl)
141
185
  const apiUrl = isSafeUrl ? candidateUrl : "https://memoria.kolivri.com"
142
186
 
143
- const envCandidates = [
144
- process.env.MEMOREAL_API_KEY,
145
- process.env.MEMORIA_API_KEY,
146
- process.env.MEMOREAL_KEY,
147
- process.env.MEMORIA_KEY,
148
- ]
149
-
150
- let rawKey = ""
151
- for (const candidate of envCandidates) {
152
- if (candidate && !isPlaceholderApiKey(candidate)) {
153
- rawKey = candidate
154
- break
155
- }
187
+ if (process.env.MEMOREAL_FORCE_UNREGISTERED === "1" || process.env.MEMORIA_FORCE_UNREGISTERED === "1") {
188
+ return { apiUrl, apiKey: "" }
156
189
  }
157
190
 
191
+ const envCandidates = [process.env.MEMOREAL_API_KEY, process.env.MEMORIA_API_KEY, process.env.MEMOREAL_KEY, process.env.MEMORIA_KEY]
192
+ let rawKey = envCandidates.find((c) => c && !isPlaceholderApiKey(c)) || ""
158
193
  if (!rawKey && !isExplicitEmptyAmbientKey) {
159
- const fileCandidates = [
160
- fileVars.MEMOREAL_API_KEY,
161
- fileVars.MEMORIA_API_KEY,
162
- fileVars.MEMOREAL_KEY,
163
- fileVars.MEMORIA_KEY,
164
- ]
165
- for (const candidate of fileCandidates) {
166
- if (candidate && !isPlaceholderApiKey(candidate)) {
167
- rawKey = candidate
168
- break
169
- }
170
- }
194
+ const fileCandidates = [fileVars.MEMOREAL_API_KEY, fileVars.MEMORIA_API_KEY, fileVars.MEMOREAL_KEY, fileVars.MEMORIA_KEY]
195
+ rawKey = fileCandidates.find((c) => c && !isPlaceholderApiKey(c)) || ""
171
196
  }
172
-
173
197
  let apiKey = rawKey.trim()
174
- while ((apiKey.startsWith('"') && apiKey.endsWith('"')) || (apiKey.startsWith("'") && apiKey.endsWith("'"))) {
175
- apiKey = apiKey.slice(1, -1).trim()
176
- }
177
- if (isPlaceholderApiKey(apiKey) || !/^[A-Za-z0-9_.-]+$/.test(apiKey)) {
178
- apiKey = ""
179
- }
180
-
198
+ while ((apiKey.startsWith('"') && apiKey.endsWith('"')) || (apiKey.startsWith("'") && apiKey.endsWith("'"))) apiKey = apiKey.slice(1, -1).trim()
199
+ if (isPlaceholderApiKey(apiKey) || !/^[A-Za-z0-9_.-]+$/.test(apiKey)) apiKey = ""
181
200
  return { apiUrl, apiKey }
182
201
  }
183
202
 
184
203
  export async function fetchSessionStartContext(cwd, homeDir) {
185
204
  const { apiUrl, apiKey } = resolveCloudConfig(homeDir)
186
- if (!apiKey) {
187
- return ONBOARDING_WIZARD_PROMPT
188
- }
205
+ const nsInfo = resolveOpenCodeNamespaceInfo(cwd)
206
+ const ns = nsInfo.namespace
207
+ if (!apiKey) return ONBOARDING_WIZARD_PROMPT
189
208
 
190
- const ns = deriveNamespace(cwd)
191
209
  const branch = gitOutput(cwd, ["branch", "--show-current"])
192
210
  const recent = gitOutput(cwd, ["log", "--oneline", "-3"]).replace(/\n+/g, "; ")
193
211
  const changed = gitOutput(cwd, ["diff", "--name-only", "HEAD"]).replace(/\n+/g, ", ")
194
-
195
212
  const gitParts = []
196
213
  if (branch) gitParts.push(`branch: ${branch}`)
197
214
  if (recent) gitParts.push(`recent commits: ${recent}`)
198
215
  if (changed) gitParts.push(`changed files: ${changed}`)
199
216
 
200
217
  let query = "previous tasks, plans, pending work, key decisions, progress, corrections, lessons learned"
201
- if (gitParts.length > 0) {
202
- query += `, context for ${gitParts.join(", ")}`
218
+ if (gitParts.length > 0) query += `, context for ${gitParts.join(", ")}`
219
+
220
+ const authHeaders = {
221
+ Authorization: `Bearer ${apiKey}`,
222
+ "X-Memoreal-Client-Version": MEMOREAL_CLIENT_VERSION,
223
+ "User-Agent": `@kolivri/memoreal-mcp/${MEMOREAL_CLIENT_VERSION}`,
203
224
  }
225
+ const contextHeaders = { "Content-Type": "application/json", ...authHeaders }
226
+ const postBody = { namespace: ns, query, token_budget: 4096 }
204
227
 
205
- const authHeaders = { Authorization: `Bearer ${apiKey}` }
228
+ if (nsInfo.isCodeProject && nsInfo.legacyNamespace && nsInfo.legacyNamespace !== nsInfo.namespace) {
229
+ contextHeaders["X-Memoreal-Legacy-Namespace"] = nsInfo.legacyNamespace
230
+ contextHeaders["X-Memoreal-Code-Project"] = "1"
231
+ postBody.legacy_namespace = nsInfo.legacyNamespace
232
+ }
206
233
 
207
234
  try {
208
- const healthRes = await fetch(`${apiUrl}/v1/health`, {
209
- headers: authHeaders,
210
- signal: AbortSignal.timeout(3000),
211
- })
212
- if (!healthRes.ok) {
213
- throw new Error(`health status ${healthRes.status}`)
235
+ const healthRes = await fetch(`${apiUrl}/v1/health`, { headers: authHeaders, signal: AbortSignal.timeout(3000) })
236
+ if (healthRes.status === 401) {
237
+ if (apiKey) invalid401Keys.add(apiKey)
238
+ return buildSetupWizardPrompt(ns, { tool: "opencode", clientName: "OpenCode" })
214
239
  }
240
+ if (!healthRes.ok) throw new Error(`health status ${healthRes.status}`)
215
241
  const healthText = await healthRes.text()
216
242
 
217
243
  const ctxRes = await fetch(`${apiUrl}/v1/memories/context`, {
218
244
  method: "POST",
219
- headers: { "Content-Type": "application/json", ...authHeaders },
220
- body: JSON.stringify({ namespace: ns, query, token_budget: 4096 }),
245
+ headers: contextHeaders,
246
+ body: JSON.stringify(postBody),
221
247
  signal: AbortSignal.timeout(5000),
222
248
  })
223
- if (!ctxRes.ok) {
224
- return `[memoreal-session-start] namespace=${ns}. Health: ${healthText}. Call build_context MCP tool with namespace "${ns}" and query "${query}" to load prior context.`
249
+ if (ctxRes.status === 401) {
250
+ if (apiKey) invalid401Keys.add(apiKey)
251
+ return buildSetupWizardPrompt(ns, { tool: "opencode", clientName: "OpenCode" })
225
252
  }
253
+ if (!ctxRes.ok) return `[memoreal-session-start] namespace=${ns}. Health: ${healthText}. Call build_context MCP tool with namespace "${ns}" and query "${query}" to load prior context.`
226
254
  const ctxText = await ctxRes.text()
227
255
  return `[memoreal-session-start] namespace=${ns}\n${healthText}\n---\n${ctxText}`
228
- } catch {
256
+ } catch (err) {
257
+ if (err?.status === 401 || err?.message?.includes("401")) {
258
+ if (apiKey) invalid401Keys.add(apiKey)
259
+ return buildSetupWizardPrompt(ns, { tool: "opencode", clientName: "OpenCode" })
260
+ }
229
261
  return `[memoreal-session-start] namespace=${ns}. Call build_context MCP tool with namespace "${ns}" and query "${query}" and token_budget 4096 to load prior session context.`
230
262
  }
231
263
  }
232
264
 
233
265
  export function buildReadSuffix(file, ns, homeDir) {
234
- if (!resolveCloudConfig(homeDir).apiKey) return ""
235
- if (!file || SYSTEM_SKILL_PATH_REGEX.test(file)) return ""
236
- if (PLAN_PATH_REGEX.test(file) || /\.md$/i.test(file)) {
266
+ if (isSecondaryHookSilenced(homeDir) || !file) return ""
267
+ const norm = file.replace(/\\/g, "/")
268
+ if (SYSTEM_SKILL_PATH_REGEX.test(norm) || SYSTEM_SKILL_PATH_REGEX.test(file)) return ""
269
+ if (PLAN_PATH_REGEX.test(norm) || /\.md$/i.test(norm)) {
237
270
  return `\n\n[memoreal-recall-doc] Reading: ${file}\nRecall related memories from Memoreal (namespace: ${ns}) about this file: prior edits, progress updates, decisions, related plans, ideas, reflections, workflow patterns, consolidated patterns, and context from previous sessions. Show the user what Memoreal knows about this file before proceeding.`
238
271
  }
239
272
  return ""
240
273
  }
241
274
 
242
275
  export function buildWriteSuffix(file, ns, homeDir) {
243
- if (!resolveCloudConfig(homeDir).apiKey) return ""
244
- if (!file || SKIP_ENCODE_EXT.test(file)) return ""
245
- if (PLAN_PATH_REGEX.test(file)) {
246
- return `\n\n[memoreal-encode-plan] Plan file written: ${file}
247
- Encode this plan into Memoreal (namespace: ${ns}). Create MULTIPLE memories:
248
- 1. (type: semantic) Plan overview: title, goals, phase structure, and current status
249
- 2. (type: semantic) Key decisions and their rationale from this plan
250
- 3. (type: episodic) Progress snapshot: what phases are done, what is next, what is blocked
251
- 4. (type: semantic) Relationships: other files, systems, or plans referenced in this document
252
- 5. (type: semantic) Knowledge: patterns, techniques, or lessons relevant to executing this plan
253
- 6. (type: episodic) Ideas and open questions found in the plan
254
- 7. (type: semantic) Reflection: what is working well, what is not, what should change in approach
255
- 8. (type: semantic) Dream: replay and consolidate — what patterns emerge across related memories, what connections between ideas were missed, what should be strengthened or let go
256
- 9. (type: semantic) Workflow: how we are working on this plan — tools, processes, patterns that help or hinder
257
- Include the file path in context metadata for every memory.`
258
- }
259
- if (/\.(md|markdown)$/i.test(file)) {
260
- return `\n\n[memoreal-encode-doc] Markdown document written: ${file}
261
- Encode into Memoreal (namespace: ${ns}). Create memories for:
262
- 1. (type: semantic) Document purpose, structure, and key content
263
- 2. (type: semantic) Decisions, patterns, or knowledge worth remembering
264
- 3. (type: episodic) Relationships to other project work and plans
265
- Include the file path in context metadata.`
266
- }
267
- if (CODE_FILE_EXT.test(file)) {
276
+ if (isSecondaryHookSilenced(homeDir) || !file) return ""
277
+ const norm = file.replace(/\\/g, "/")
278
+ if (SKIP_ENCODE_EXT.test(norm)) return ""
279
+ if (PLAN_PATH_REGEX.test(norm)) return PLAN_WRITE_PROMPT(file, ns)
280
+ if (/\.(md|markdown)$/i.test(norm)) return DOC_WRITE_PROMPT(file, ns)
281
+ if (CODE_FILE_EXT.test(norm)) {
268
282
  return `\n\n[memoreal-encode-code] Code file written: ${file}. Re-encode this code into Memoreal (namespace: ${ns}) so search_code, explain_code, and find_references stay current: encode the key definitions (functions, types, classes) with their signatures, purpose, and notable logic as type semantic memories, salience 0.6, with the file path in context. Search before encoding so dedup can merge near-duplicates. For a full structural re-index of the project, run the memoreal-sync-code skill.`
269
283
  }
270
284
  return `\n\n[memoreal-encode-file] File written: ${file}. Apply write gate: only encode if this file contains a key definition, decision, or pattern worth remembering across sessions. Skip boilerplate. If encoding, use namespace ${ns}, type semantic, salience 0.5. Include file path in context.`
271
285
  }
272
286
 
273
287
  export function buildEditSuffix(file, ns, homeDir) {
274
- if (!resolveCloudConfig(homeDir).apiKey) return ""
275
- if (!file || SKIP_ENCODE_EXT.test(file)) return ""
276
- if (PLAN_PATH_REGEX.test(file)) {
277
- return `\n\n[memoreal-encode-plan] Plan file updated: ${file}
278
- Encode this change into Memoreal (namespace: ${ns}). Create memories for:
279
- 1. (type: episodic) What specifically changed in the plan and why
280
- 2. (type: episodic) Progress update: mark completed items, note new items or phase transitions
281
- 3. (type: semantic) Any new decisions, ideas, or insights from this edit
282
- 4. (type: semantic) New relationships or dependencies added
283
- 5. (type: semantic) Reflection: does this change reveal something about the approach — what is working, what needs rethinking
284
- 6. (type: semantic) Workflow ideas: better ways to work on this plan based on what just happened
285
- Include the file path in context metadata.`
286
- }
287
- if (/\.(md|markdown)$/i.test(file)) {
288
- return `\n\n[memoreal-encode-doc] Markdown document edited: ${file}
289
- Encode the change into Memoreal (namespace: ${ns}):
290
- 1. (type: episodic) What changed and why
291
- 2. (type: semantic) Any new knowledge, decisions, or patterns
292
- Include the file path in context metadata.`
293
- }
294
- if (CODE_FILE_EXT.test(file)) {
288
+ if (isSecondaryHookSilenced(homeDir) || !file) return ""
289
+ const norm = file.replace(/\\/g, "/")
290
+ if (SKIP_ENCODE_EXT.test(norm)) return ""
291
+ if (PLAN_PATH_REGEX.test(norm)) return PLAN_EDIT_PROMPT(file, ns)
292
+ if (/\.(md|markdown)$/i.test(norm)) return DOC_EDIT_PROMPT(file, ns)
293
+ if (CODE_FILE_EXT.test(norm)) {
295
294
  return `\n\n[memoreal-encode-code] Code file edited: ${file}. Re-encode the changed code into Memoreal (namespace: ${ns}): encode the updated definitions and logic (what changed and the new behavior) as type semantic, salience 0.6, with the file path in context, so search_code, explain_code, and find_references reflect the current code. Search before encoding to avoid duplicates. For a full structural re-index, run the memoreal-sync-code skill.`
296
295
  }
297
296
  return `\n\n[memoreal-encode-file] File edited: ${file}. Apply write gate: only encode if this edit represents a meaningful decision, pattern, or lesson. Skip routine changes. If encoding, use namespace ${ns}, type semantic, salience 0.5. Include file path and what changed.`
298
297
  }
299
298
 
300
299
  function buildTodoSuffix(sessionID, todos, previousTodosBySession, ns, homeDir) {
301
- if (!resolveCloudConfig(homeDir).apiKey) return ""
300
+ if (isSecondaryHookSilenced(homeDir)) return ""
302
301
  const prev = previousTodosBySession.get(sessionID) || new Map()
303
302
  const list = Array.isArray(todos) ? todos : []
304
-
305
- let hasNewTask = false
306
- let hasCompletedTask = false
307
-
303
+ let hasNewTask = false, hasCompletedTask = false
308
304
  const nextMap = new Map()
309
305
  for (const t of list) {
310
306
  if (!t?.content) continue
311
307
  const oldStatus = prev.get(t.content)
312
- if (!oldStatus) {
313
- hasNewTask = true
314
- }
315
- if (t.status === "completed" && oldStatus !== "completed") {
316
- hasCompletedTask = true
317
- }
308
+ if (!oldStatus) hasNewTask = true
309
+ if (t.status === "completed" && oldStatus !== "completed") hasCompletedTask = true
318
310
  nextMap.set(t.content, t.status)
319
311
  }
320
312
  previousTodosBySession.set(sessionID, nextMap)
321
-
322
313
  let out = ""
323
- if (hasNewTask) {
324
- out += `\n\n[memoreal-encode-task] A task was just created. Encode it into Memoreal via encode_memory with type "episodic" and namespace "${ns}". Include the task description, status, and which plan file it relates to (if any).`
325
- }
326
- if (hasCompletedTask) {
327
- out += `\n\n[memoreal-update-task] A task was just completed. Encode into Memoreal (namespace: ${ns}). Create memories for:
328
- 1. (type: episodic) What was accomplished and which plan file it relates to
329
- 2. (type: semantic) Lessons learned and knowledge gained from this task
330
- 3. (type: semantic) Reflection: what went well, what was harder than expected, what to do differently next time
331
- 4. (type: semantic) Workflow ideas: any process improvements or tool usage patterns discovered while doing this task`
332
- }
314
+ if (hasNewTask) out += `\n\n[memoreal-encode-task] A task was just created. Encode it into Memoreal via encode_memory with type "episodic" and namespace "${ns}". Include the task description, status, and which plan file it relates to (if any).`
315
+ if (hasCompletedTask) out += TODO_COMPLETED_PROMPT(ns)
333
316
  return out
334
317
  }
335
318
 
319
+ function handleToolSuffix(tool, args, sessionID, previousTodosBySession, ns) {
320
+ const file = args.path || args.filePath || args.file_path || ""
321
+ if (tool === "read") return buildReadSuffix(file, ns)
322
+ if (tool === "write") return buildWriteSuffix(file, ns)
323
+ if (tool === "edit" || tool === "patch") return buildEditSuffix(file, ns)
324
+ if (tool === "todowrite") return buildTodoSuffix(sessionID, args.todos, previousTodosBySession, ns)
325
+ return ""
326
+ }
327
+
336
328
  export const MemorealHooksPlugin = async ({ directory, client } = {}) => {
337
329
  const sessionStartContextCache = new Map()
338
330
  const pendingCorrectionBySession = new Map()
@@ -343,131 +335,64 @@ export const MemorealHooksPlugin = async ({ directory, client } = {}) => {
343
335
  return {
344
336
  "chat.message": async (input, output) => {
345
337
  const sessionID = input?.sessionID
346
- if (await checkChild(sessionID)) return
347
- if (!sessionID) return
348
-
349
- const msg = (output?.parts || [])
350
- .filter((p) => p?.type === "text" && typeof p.text === "string")
351
- .map((p) => p.text)
352
- .join(" ")
353
- .toLowerCase()
354
-
355
- const isCorrection = Boolean(msg && CORRECTION_PATTERNS.some((pat) => msg.includes(pat)))
356
- pendingCorrectionBySession.set(sessionID, isCorrection)
338
+ if (await checkChild(sessionID) || !sessionID) return
339
+ const msg = (output?.parts || []).filter((p) => p?.type === "text" && typeof p.text === "string").map((p) => p.text).join(" ").toLowerCase()
340
+ pendingCorrectionBySession.set(sessionID, Boolean(msg && CORRECTION_PATTERNS.some((pat) => msg.includes(pat))))
357
341
  },
358
-
359
342
  "experimental.chat.system.transform": async (input, output) => {
360
343
  const sessionID = input?.sessionID || "default"
361
344
  if (await checkChild(input?.sessionID)) return
362
345
  const ns = deriveNamespace(directory)
346
+ const currentKey = resolveCloudConfig().apiKey || ""
347
+ const cacheKey = `${sessionID}:${currentKey}`
363
348
 
364
- if (!sessionStartContextCache.has(sessionID)) {
365
- const ctx = await fetchSessionStartContext(directory)
366
- sessionStartContextCache.set(sessionID, ctx)
349
+ if (!sessionStartContextCache.has(cacheKey)) {
350
+ sessionStartContextCache.set(cacheKey, await fetchSessionStartContext(directory))
351
+ wizardKeyBySession.set(sessionID, currentKey)
367
352
  }
368
- const startCtx = sessionStartContextCache.get(sessionID)
353
+ const startCtx = sessionStartContextCache.get(cacheKey)
369
354
  if (startCtx && Array.isArray(output?.system)) {
370
355
  output.system.push(startCtx)
371
- if (startCtx === ONBOARDING_WIZARD_PROMPT) {
372
- sessionStartContextCache.set(sessionID, "")
356
+ if (startCtx === ONBOARDING_WIZARD_PROMPT || startCtx.includes("[memoreal-setup-wizard]")) {
357
+ sessionStartContextCache.set(cacheKey, "")
373
358
  }
374
359
  }
375
-
376
- if (resolveCloudConfig().apiKey) {
360
+ if (!isSecondaryHookSilenced()) {
377
361
  const stopKey = `${sessionID}:stop`
378
362
  const stopCtx = sessionStartContextCache.get(stopKey)
379
363
  if (stopCtx && Array.isArray(output?.system)) {
380
364
  output.system.push(stopCtx)
381
365
  sessionStartContextCache.delete(stopKey)
382
366
  }
383
-
384
367
  if (pendingCorrectionBySession.get(sessionID) && Array.isArray(output?.system)) {
385
- output.system.push(
386
- `[memoreal-correction] The user appears to be correcting your approach. After addressing the correction, encode the lesson into Memoreal (namespace: ${ns}, type: semantic, salience: 0.9) as a rule: what was wrong, what the correct approach is, and why. This ensures the mistake is never repeated in future sessions.`
387
- )
368
+ output.system.push(CORRECTION_PROMPT(ns))
388
369
  }
389
370
  }
390
371
  },
391
-
392
372
  "tool.execute.after": async (input, output) => {
393
- if (await checkChild(input?.sessionID)) return
394
- if (!resolveCloudConfig().apiKey) return
395
- const tool = input?.tool
396
- const args = input?.args || {}
397
- const ns = deriveNamespace(directory)
398
- if (typeof output?.output !== "string") return
399
-
400
- if (tool === "read") {
401
- const file = args.filePath || args.file_path || args.path || ""
402
- output.output += buildReadSuffix(file, ns)
403
- return
404
- }
405
-
406
- if (tool === "write") {
407
- const file = args.filePath || args.file_path || args.path || ""
408
- output.output += buildWriteSuffix(file, ns)
409
- return
410
- }
411
-
412
- if (tool === "edit" || tool === "patch") {
413
- const file = args.filePath || args.file_path || args.path || ""
414
- output.output += buildEditSuffix(file, ns)
415
- return
416
- }
417
-
418
- if (tool === "todowrite") {
419
- const sessionID = input?.sessionID || "default"
420
- output.output += buildTodoSuffix(sessionID, args.todos, previousTodosBySession, ns)
421
- }
373
+ if (await checkChild(input?.sessionID) || isSecondaryHookSilenced() || typeof output?.output !== "string") return
374
+ output.output += handleToolSuffix(input?.tool, input?.args || {}, input?.sessionID || "default", previousTodosBySession, deriveNamespace(directory))
422
375
  },
423
-
424
376
  "experimental.session.compacting": async (input, output) => {
425
- if (await checkChild(input?.sessionID)) return
426
- if (!resolveCloudConfig().apiKey) return
427
- const ns = deriveNamespace(directory)
428
- output.context.push(
429
- `[memoreal-pre-compact] Context is about to be compressed. Ensure the following are encoded into Memoreal (namespace: ${ns}) so nothing is lost:
430
- 1. (type: episodic) Current task state: what you were working on, what is done, what remains
431
- 2. (type: episodic) Key findings so far: bugs found, root causes identified, decisions made
432
- 3. (type: episodic) Open questions and blockers
433
- 4. (type: semantic) Any code patterns, architecture insights, or facts learned this session
434
- [memoreal-post-compact] After compression, call build_context with namespace "${ns}" and query "current task, recent progress, findings, decisions, open questions, what was I working on" and token_budget 2048 to restore critical context.`
435
- )
377
+ if (await checkChild(input?.sessionID) || isSecondaryHookSilenced()) return
378
+ output.context.push(COMPACTION_PROMPT(deriveNamespace(directory)))
436
379
  },
437
-
438
380
  event: async ({ event }) => {
439
381
  if (event?.type === "session.idle") {
440
- const sessionID =
441
- event?.properties?.sessionID ||
442
- event?.properties?.info?.id ||
443
- event?.sessionID ||
444
- "default"
445
382
  const rawSid = event?.properties?.sessionID || event?.properties?.info?.id || event?.sessionID
446
- if (await checkChild(rawSid)) return
447
- if (!resolveCloudConfig().apiKey) return
448
- const ns = deriveNamespace(directory)
449
- sessionStartContextCache.set(
450
- `${sessionID}:stop`,
451
- `[memoreal-session-end] Session is ending. Encode a session summary into Memoreal (namespace: ${ns}) with the following write gate — ONLY encode if the item would change future behavior, represents a commitment, or is a decision worth preserving. Skip transient details.
452
- 1. (type: episodic, salience: 0.7) Session summary: what was the goal, what was accomplished, what remains unfinished
453
- 2. (type: semantic, salience: 0.8) Key decisions made and their rationale — only decisions that affect future work
454
- 3. (type: semantic, salience: 0.8) Lessons learned: mistakes made, corrections received, patterns discovered
455
- 4. (type: semantic, salience: 0.6) Code patterns or architecture insights worth remembering
456
- 5. (type: episodic, salience: 0.5) Open questions and next steps for the next session
457
- Include [["source", "session-end"]] in context metadata for each. Then run consolidate on namespace "${ns}".`
458
- )
383
+ if (await checkChild(rawSid) || isSecondaryHookSilenced()) return
384
+ sessionStartContextCache.set(`${rawSid || "default"}:stop`, SESSION_END_PROMPT(deriveNamespace(directory)))
459
385
  }
460
386
  },
461
387
  }
462
388
  }
463
389
 
390
+ export const MemoriaHooksPlugin = MemorealHooksPlugin
391
+
464
392
  function appendResultText(result, suffix) {
465
393
  if (!result || !suffix) return
466
- if (typeof result.content === "string") {
467
- result.content += suffix
468
- } else if (Array.isArray(result.content)) {
469
- result.content = [...result.content, { type: "text", text: suffix.replace(/^\n+/, "") }]
470
- }
394
+ if (typeof result.content === "string") result.content += suffix
395
+ else if (Array.isArray(result.content)) result.content = [...result.content, { type: "text", text: suffix.replace(/^\n+/, "") }]
471
396
  }
472
397
 
473
398
  export const setup = async (ctx) => {
@@ -480,118 +405,60 @@ export const setup = async (ctx) => {
480
405
 
481
406
  await ctx.session.hook("prompt", async (event) => {
482
407
  const sessionID = event?.sessionID
483
- if (await checkChild(sessionID)) return
484
- if (!sessionID) return
408
+ if (await checkChild(sessionID) || !sessionID) return
485
409
  const msg = (event?.prompt?.text || "").toLowerCase()
486
- const isCorrection = Boolean(msg && CORRECTION_PATTERNS.some((pat) => msg.includes(pat)))
487
- pendingCorrectionBySession.set(sessionID, isCorrection)
410
+ pendingCorrectionBySession.set(sessionID, Boolean(msg && CORRECTION_PATTERNS.some((pat) => msg.includes(pat))))
488
411
  })
489
412
 
490
413
  await ctx.session.hook("context", async (event) => {
491
414
  const sessionID = event?.sessionID || "default"
492
415
  if (await checkChild(event?.sessionID)) return
493
416
  const ns = deriveNamespace(directory)
417
+ const currentKey = resolveCloudConfig().apiKey || ""
418
+ const cacheKey = `${sessionID}:${currentKey}`
494
419
 
495
- if (!sessionStartContextCache.has(sessionID)) {
496
- const startText = await fetchSessionStartContext(directory)
497
- sessionStartContextCache.set(sessionID, startText)
420
+ if (!sessionStartContextCache.has(cacheKey)) {
421
+ sessionStartContextCache.set(cacheKey, await fetchSessionStartContext(directory))
422
+ wizardKeyBySession.set(sessionID, currentKey)
498
423
  }
499
- const startCtx = sessionStartContextCache.get(sessionID)
424
+ const startCtx = sessionStartContextCache.get(cacheKey)
500
425
  if (startCtx && Array.isArray(event?.system)) {
501
426
  event.system.push({ type: "text", text: startCtx })
502
- if (startCtx === ONBOARDING_WIZARD_PROMPT) {
503
- sessionStartContextCache.set(sessionID, "")
427
+ if (startCtx === ONBOARDING_WIZARD_PROMPT || startCtx.includes("[memoreal-setup-wizard]")) {
428
+ sessionStartContextCache.set(cacheKey, "")
504
429
  }
505
430
  }
506
-
507
- if (resolveCloudConfig().apiKey) {
431
+ if (!isSecondaryHookSilenced()) {
508
432
  const stopKey = `${sessionID}:stop`
509
433
  const stopCtx = sessionStartContextCache.get(stopKey)
510
434
  if (stopCtx && Array.isArray(event?.system)) {
511
435
  event.system.push({ type: "text", text: stopCtx })
512
436
  sessionStartContextCache.delete(stopKey)
513
437
  }
514
-
515
438
  if (pendingCorrectionBySession.get(sessionID) && Array.isArray(event?.system)) {
516
- event.system.push({
517
- type: "text",
518
- text: `[memoreal-correction] The user appears to be correcting your approach. After addressing the correction, encode the lesson into Memoreal (namespace: ${ns}, type: semantic, salience: 0.9) as a rule: what was wrong, what the correct approach is, and why. This ensures the mistake is never repeated in future sessions.`,
519
- })
439
+ event.system.push({ type: "text", text: CORRECTION_PROMPT(ns) })
520
440
  }
521
441
  }
522
442
  })
523
443
 
524
444
  await ctx.tool.hook("execute.after", async (event) => {
525
- if (event.status !== "completed" || !event.result) return
526
- if (await checkChild(event?.sessionID)) return
527
- if (!resolveCloudConfig().apiKey) return
528
- const tool = event.tool
529
- const args = event.input || {}
530
- const ns = deriveNamespace(directory)
531
-
532
- if (tool === "read") {
533
- const file = args.path || args.filePath || args.file_path || ""
534
- appendResultText(event.result, buildReadSuffix(file, ns))
535
- return
536
- }
537
-
538
- if (tool === "write") {
539
- const file = args.path || args.filePath || args.file_path || ""
540
- appendResultText(event.result, buildWriteSuffix(file, ns))
541
- return
542
- }
543
-
544
- if (tool === "edit" || tool === "patch") {
545
- const file = args.path || args.filePath || args.file_path || ""
546
- appendResultText(event.result, buildEditSuffix(file, ns))
547
- return
548
- }
549
-
550
- if (tool === "todowrite") {
551
- const sessionID = event?.sessionID || "default"
552
- appendResultText(event.result, buildTodoSuffix(sessionID, args.todos, previousTodosBySession, ns))
553
- }
445
+ if (event.status !== "completed" || !event.result || await checkChild(event?.sessionID) || isSecondaryHookSilenced()) return
446
+ appendResultText(event.result, handleToolSuffix(event.tool, event.input || {}, event?.sessionID || "default", previousTodosBySession, deriveNamespace(directory)))
554
447
  })
555
448
 
556
449
  await ctx.session.hook("compaction", async (event) => {
557
- if (await checkChild(event?.sessionID)) return
558
- if (!resolveCloudConfig().apiKey) return
559
- const ns = deriveNamespace(directory)
560
- if (Array.isArray(event?.system)) {
561
- event.system.push({
562
- type: "text",
563
- text: `[memoreal-pre-compact] Context is about to be compressed. Ensure the following are encoded into Memoreal (namespace: ${ns}) so nothing is lost:
564
- 1. (type: episodic) Current task state: what you were working on, what is done, what remains
565
- 2. (type: episodic) Key findings so far: bugs found, root causes identified, decisions made
566
- 3. (type: episodic) Open questions and blockers
567
- 4. (type: semantic) Any code patterns, architecture insights, or facts learned this session
568
- [memoreal-post-compact] After compression, call build_context with namespace "${ns}" and query "current task, recent progress, findings, decisions, open questions, what was I working on" and token_budget 2048 to restore critical context.`,
569
- })
570
- }
450
+ if (await checkChild(event?.sessionID) || isSecondaryHookSilenced()) return
451
+ if (Array.isArray(event?.system)) event.system.push({ type: "text", text: COMPACTION_PROMPT(deriveNamespace(directory)) })
571
452
  })
572
453
 
573
454
  const controller = new AbortController()
574
455
  void (async () => {
575
456
  try {
576
- for await (const event of ctx.event.subscribe({
577
- types: ["session.execution.succeeded"],
578
- signal: controller.signal,
579
- })) {
457
+ for await (const event of ctx.event.subscribe({ types: ["session.execution.succeeded"], signal: controller.signal })) {
580
458
  if (event?.type === "session.execution.succeeded") {
581
- const sessionID = event?.data?.sessionID || event?.sessionID || "default"
582
- if (await checkChild(event?.data?.sessionID || event?.sessionID)) continue
583
- if (!resolveCloudConfig().apiKey) continue
584
- const ns = deriveNamespace(directory)
585
- sessionStartContextCache.set(
586
- `${sessionID}:stop`,
587
- `[memoreal-session-end] Session is ending. Encode a session summary into Memoreal (namespace: ${ns}) with the following write gate — ONLY encode if the item would change future behavior, represents a commitment, or is a decision worth preserving. Skip transient details.
588
- 1. (type: episodic, salience: 0.7) Session summary: what was the goal, what was accomplished, what remains unfinished
589
- 2. (type: semantic, salience: 0.8) Key decisions made and their rationale — only decisions that affect future work
590
- 3. (type: semantic, salience: 0.8) Lessons learned: mistakes made, corrections received, patterns discovered
591
- 4. (type: semantic, salience: 0.6) Code patterns or architecture insights worth remembering
592
- 5. (type: episodic, salience: 0.5) Open questions and next steps for the next session
593
- Include [["source", "session-end"]] in context metadata for each. Then run consolidate on namespace "${ns}".`
594
- )
459
+ const rawSid = event?.data?.sessionID || event?.sessionID
460
+ if (await checkChild(rawSid) || isSecondaryHookSilenced()) continue
461
+ sessionStartContextCache.set(`${rawSid || "default"}:stop`, SESSION_END_PROMPT(deriveNamespace(directory)))
595
462
  }
596
463
  }
597
464
  } catch {}
@@ -604,6 +471,24 @@ export default {
604
471
  id: "memoreal-hooks",
605
472
  server: MemorealHooksPlugin,
606
473
  setup,
474
+ MEMOREAL_CLIENT_VERSION,
475
+ ONBOARDING_WIZARD_PROMPT,
476
+ PLACEHOLDER_KEY_REGEX,
477
+ isPlaceholderApiKey,
478
+ isUnregisteredApiKey,
479
+ isSecondaryHookSilenced,
480
+ buildSetupWizardPrompt,
607
481
  isChildSession,
608
482
  isChildSubagentSession,
609
- }
483
+ derivePathNamespace,
484
+ sanitizeLogicalNamespace,
485
+ resolveOpenCodeNamespaceInfo,
486
+ deriveNamespace,
487
+ resolveCloudConfig,
488
+ fetchSessionStartContext,
489
+ buildReadSuffix,
490
+ buildWriteSuffix,
491
+ buildEditSuffix,
492
+ MemorealHooksPlugin,
493
+ MemoriaHooksPlugin,
494
+ }