toon-memory 4.3.0 → 4.3.2

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.
package/mcp/server.js CHANGED
@@ -22614,6 +22614,25 @@ function graphRecallDetailed(data, query, opts = {}) {
22614
22614
  }
22615
22615
  return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons };
22616
22616
  }
22617
+ function fetchEntriesByIds(data, tokens, opts = {}) {
22618
+ const byId = /* @__PURE__ */ new Map();
22619
+ const byKey = /* @__PURE__ */ new Map();
22620
+ const asOf = opts.asOf || "";
22621
+ for (const e of parseEntries(data)) {
22622
+ const visible = e.status === "active" || e.status === "resolved" || asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf;
22623
+ if (!visible) continue;
22624
+ if (asOf && e.date && e.date > asOf) continue;
22625
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue;
22626
+ if (!byId.has(e.id)) byId.set(e.id, e);
22627
+ if (!byKey.has(e.key)) byKey.set(e.key, e);
22628
+ }
22629
+ const out = [];
22630
+ for (const t of tokens) {
22631
+ const e = byKey.get(t) || byId.get(t);
22632
+ if (e && !out.includes(e)) out.push(e);
22633
+ }
22634
+ return out;
22635
+ }
22617
22636
  function globMatch(pattern, target) {
22618
22637
  if (!pattern) return true;
22619
22638
  if (pattern.startsWith("/")) pattern = pattern.slice(1);
@@ -22686,6 +22705,24 @@ function renderCompact(entries, opts = {}) {
22686
22705
  }
22687
22706
  return rendered.join("\n\n");
22688
22707
  }
22708
+ function renderIndex(entries, opts = {}) {
22709
+ let max = 0;
22710
+ if (opts.scores) {
22711
+ for (const v3 of opts.scores.values()) if (v3 > max) max = v3;
22712
+ }
22713
+ const lines = [];
22714
+ for (let i = 0; i < entries.length; i++) {
22715
+ const e = entries[i];
22716
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22717
+ let score = "";
22718
+ if (opts.scores && max > 0) {
22719
+ const s2 = opts.scores.get(e.key);
22720
+ if (s2 !== void 0) score = ` \xB7 ${Math.round(s2 / max * 100)}%`;
22721
+ }
22722
+ lines.push(`[${i + 1}] ${e.key} (${e.id})${pin} \xB7 ${e.category} \xB7 ${e.date}${score}`);
22723
+ }
22724
+ return lines.join("\n");
22725
+ }
22689
22726
  var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
22690
22727
  var init_graph = __esm({
22691
22728
  "src/lib/graph.ts"() {
@@ -33181,10 +33218,16 @@ function readObservations() {
33181
33218
  // src/mcp/archive.ts
33182
33219
  import { readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
33183
33220
  init_utils();
33221
+ function findHeaderIdx(lines) {
33222
+ return lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
33223
+ }
33224
+ function bumpHeaderCount(line, count) {
33225
+ return line.replace(/^([a-z]+)?\[(\d+)\|/, (_m2, pre) => `${pre || ""}[${count}|`);
33226
+ }
33184
33227
  function archiveOldEntries(opts = {}) {
33185
33228
  const data = readMemory();
33186
33229
  const lines = data.split("\n");
33187
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
33230
+ const headerIdx = findHeaderIdx(lines);
33188
33231
  if (headerIdx === -1) return { archived: 0, kept: 0 };
33189
33232
  const today = /* @__PURE__ */ new Date();
33190
33233
  const cutoff = new Date(today);
@@ -33225,14 +33268,14 @@ archived:
33225
33268
  archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:`);
33226
33269
  archiveHeaderIdx = archiveLines.length - 1;
33227
33270
  }
33228
- const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/);
33271
+ const archiveMatch = archiveLines[archiveHeaderIdx].match(/\[(\d+)\|/);
33229
33272
  const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0;
33230
33273
  for (const entry of toArchiveLines) {
33231
33274
  archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`);
33232
33275
  }
33233
- archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`);
33276
+ archiveLines[archiveHeaderIdx] = bumpHeaderCount(archiveLines[archiveHeaderIdx], archiveCount + toArchiveLines.length);
33234
33277
  safeWrite(ARCHIVE_FILE, archiveLines.join("\n"));
33235
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`);
33278
+ lines[headerIdx] = bumpHeaderCount(lines[headerIdx], toKeepLines.length);
33236
33279
  const keepSet = new Set(toKeepLines);
33237
33280
  const allEntryLines = lines.slice(headerIdx + 1);
33238
33281
  const newEntryLines = allEntryLines.filter((l) => {
@@ -33250,7 +33293,7 @@ function pruneExpiredEntries() {
33250
33293
  withLockSync(MEMORY_FILE, () => {
33251
33294
  const data = readMemory();
33252
33295
  const lines = data.split("\n");
33253
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
33296
+ const headerIdx = findHeaderIdx(lines);
33254
33297
  if (headerIdx === -1) return;
33255
33298
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
33256
33299
  const kept = entryLines2.filter((l) => {
@@ -33264,7 +33307,7 @@ function pruneExpiredEntries() {
33264
33307
  return true;
33265
33308
  });
33266
33309
  if (pruned === 0) return;
33267
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`);
33310
+ lines[headerIdx] = bumpHeaderCount(lines[headerIdx], kept.length);
33268
33311
  const keepSet = new Set(kept.map((l) => l.trim()));
33269
33312
  const allEntryLines = lines.slice(headerIdx + 1);
33270
33313
  const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()));
@@ -34866,12 +34909,14 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34866
34909
  title: "Search Memory",
34867
34910
  description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files. Pattern: recall \u2192 context_diff for recent changes \u2192 capture to save observations.",
34868
34911
  inputSchema: {
34869
- query: external_exports.string().describe("Text to search for"),
34912
+ query: external_exports.string().optional().default("").describe("Text to search for (optional when mode:'index' or ids is given)"),
34870
34913
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
34871
34914
  from_date: external_exports.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
34872
34915
  to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
34873
- mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
34916
+ mode: external_exports.enum(["flat", "graph", "index"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens). 'index' = one line per entry (key, id, category, date, relevance %) with no content \u2014 browse then fetch full entries with `ids`."),
34917
+ ids: external_exports.string().optional().default("").describe("Batch fetch: comma/space/;-separated entry ids or keys, rendered in the given order (unknown entries skipped). Complements mode:'index' \u2014 layer 2 of progressive disclosure. Overrides mode."),
34874
34918
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
34919
+ limit: external_exports.number().optional().describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
34875
34920
  compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
34876
34921
  budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
34877
34922
  budget_tokens: external_exports.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
@@ -34883,11 +34928,62 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34883
34928
  },
34884
34929
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34885
34930
  },
34886
- async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
34931
+ async ({ query, category, from_date, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
34887
34932
  const data = readMemory();
34888
- const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34889
34933
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
34890
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: as_of || void 0 });
34934
+ const resolvedAsOf = as_of || void 0;
34935
+ if (ids && ids.trim()) {
34936
+ const tokens = ids.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean);
34937
+ const entries = fetchEntriesByIds(data, tokens, { asOf: resolvedAsOf });
34938
+ if (entries.length === 0) {
34939
+ return { content: [{ type: "text", text: `No entries found for ids: ${ids}` }] };
34940
+ }
34941
+ bumpAccessed(entries.map((e) => e.id));
34942
+ const label = entries.length === 1 ? "entry" : "entries";
34943
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
34944
+ const formatted3 = renderCompact(entries, {
34945
+ budget: resolvedBudget,
34946
+ budgetTokens: budget_tokens || void 0
34947
+ });
34948
+ return { content: [{ type: "text", text: `Fetched ${entries.length} ${label}:
34949
+
34950
+ ${formatted3}` }] };
34951
+ }
34952
+ const formatted2 = entries.map((r2) => {
34953
+ const links = r2.links.length ? `
34954
+ links: ${r2.links.join(", ")}` : "";
34955
+ const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
34956
+ const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
34957
+ const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
34958
+ const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
34959
+ const supersededInfo = r2.supersededOn ? ` | superseded: ${r2.supersededOn}` : "";
34960
+ return `[${r2.category}] ${r2.key}${pin} (${r2.id})
34961
+ ${r2.content}
34962
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`;
34963
+ }).join("\n\n");
34964
+ return { content: [{ type: "text", text: `Fetched ${entries.length} ${label}:
34965
+
34966
+ ${formatted2}` }] };
34967
+ }
34968
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34969
+ const limit = limitParam ?? (mode === "index" ? 15 : 6);
34970
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, limit, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: resolvedAsOf });
34971
+ if (mode === "index") {
34972
+ if (detail.entries.length === 0) {
34973
+ return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34974
+ }
34975
+ const formatted2 = renderIndex(detail.entries, { scores: detail.scores });
34976
+ return {
34977
+ content: [{
34978
+ type: "text",
34979
+ text: `\u{1F4C7} Memory index (${detail.entries.length} entries):
34980
+
34981
+ ${formatted2}
34982
+
34983
+ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"flat".`
34984
+ }]
34985
+ };
34986
+ }
34891
34987
  if (detail.entries.length === 0) {
34892
34988
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34893
34989
  }
@@ -48210,7 +48306,7 @@ function registerResources(server2) {
48210
48306
 
48211
48307
  // src/mcp/server.ts
48212
48308
  var server = new McpServer(
48213
- { name: "toon-memory", version: "4.3.0" },
48309
+ { name: "toon-memory", version: "4.3.2" },
48214
48310
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
48215
48311
  );
48216
48312
  var s = server.server;
@@ -48222,7 +48318,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
48222
48318
  return {
48223
48319
  protocolVersion,
48224
48320
  capabilities: s.getCapabilities(),
48225
- serverInfo: { name: "toon-memory", version: "4.3.0" },
48321
+ serverInfo: { name: "toon-memory", version: "4.3.2" },
48226
48322
  ...s._instructions && { instructions: s._instructions }
48227
48323
  };
48228
48324
  });
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "toon-memory",
3
3
  "mcpName": "io.github.LuiggiVal08/toon-memory",
4
- "version": "4.3.0",
5
- "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 35 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
4
+ "version": "4.3.2",
5
+ "description": "The Continuity Layer for AI Agents — an MCP memory server that preserves project knowledge, decisions, and conventions across sessions so every session starts where the last one ended. Offline, token-efficient, no LLM, no server; works with 15+ agents.",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "toon-memory": "./bin/toon-memory.js"
@@ -19,7 +19,7 @@
19
19
  ],
20
20
  "scripts": {
21
21
  "build": "npm run build:bin && npm run build:mcp && npm run build:cli",
22
- "build:bin": "esbuild src/bin/toon-memory.ts --platform=node --format=esm --outfile=bin/toon-memory.js",
22
+ "build:bin": "esbuild src/bin/toon-memory.ts --bundle --platform=node --format=esm --outfile=bin/toon-memory.js",
23
23
  "build:mcp": "node -e \"const{version}=require('./package.json');const esbuild=require('esbuild');esbuild.build({entryPoints:['src/mcp/server.ts'],bundle:true,platform:'node',format:'esm',outfile:'mcp/server.js',define:{TOON_VERSION:JSON.stringify(version)}})\"",
24
24
  "build:cli": "esbuild src/cli/setup.ts --bundle --platform=node --format=esm --packages=external --outfile=dist/cli/setup.js && esbuild src/cli/toon-memory.ts --bundle --platform=node --format=esm --outfile=dist/cli/toon-memory.js && esbuild src/cli/capture.ts --bundle --platform=node --format=esm --outfile=dist/cli/capture.js && esbuild src/cli/session-start.ts --bundle --platform=node --format=esm --outfile=dist/cli/session-start.js",
25
25
  "test": "vitest run",
@@ -2,6 +2,7 @@
2
2
  import { dirname, join } from "path"
3
3
  import { readFileSync } from "fs"
4
4
  import { fileURLToPath } from "url"
5
+ import { fileImportURL } from "../cli/entry"
5
6
 
6
7
  const __dirname = dirname(fileURLToPath(import.meta.url))
7
8
  const args = process.argv.slice(2)
@@ -55,8 +56,8 @@ if (args[0] === "-h" || args[0] === "--help") {
55
56
  }
56
57
 
57
58
  if (args[0] === "mcp") {
58
- await import(join(__dirname, "..", "mcp", "server.js"))
59
+ await import(fileImportURL(__dirname, "..", "mcp", "server.js"))
59
60
  } else {
60
61
  process.argv = ["node", "toon-memory", ...args]
61
- await import(join(__dirname, "..", "dist", "cli", "setup.js"))
62
+ await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"))
62
63
  }
@@ -469,13 +469,15 @@ export function importMemory(): void {
469
469
  const existing = readFileSync(memoryFile, "utf-8")
470
470
  const existingCount = existing.split("\n")
471
471
  .filter((l: string) => l.startsWith(" ") && l.includes("|")).length
472
+ const newCount = existingCount + newEntries.length
473
+ // Match either `entries[N|]` (MCP writers) or `[N|]` (CLI init) and keep the prefix.
472
474
  const updated = existing.replace(
473
- /entries\[\d+\|]/,
474
- `entries[${existingCount + newEntries.length}|]`
475
+ /^(version: 1\n)?(entries)?\[(\d+)\|/,
476
+ (m, _v: string, prefix: string) => `${m.startsWith("version: 1\n") ? "version: 1\n" : ""}${prefix || ""}[${newCount}|`
475
477
  ) + "\n" + newLines
476
478
  writeFileSync(memoryFile, updated)
477
479
  } else {
478
- writeFileSync(memoryFile, `version: 1\nentries[${newEntries.length}|]{id|category|key|content|file|tags|date}:\n${newLines}\n`)
480
+ writeFileSync(memoryFile, `version: 1\n[${newEntries.length}|]{id|category|key|content|file|tags|date}:\n${newLines}\n`)
479
481
  }
480
482
 
481
483
  console.log(`Imported ${newEntries.length} new entries`)
@@ -3,6 +3,21 @@ import { dirname } from "path"
3
3
  import type { Agent } from "./types"
4
4
  import { MEMORY_DIR, CAPTURE_CONFIG } from "./constants"
5
5
 
6
+ /**
7
+ * Read an existing JSON config file.
8
+ * Returns {} when the file is missing, or null when it exists but cannot be
9
+ * parsed — callers MUST skip (never overwrite) on null to avoid wiping the
10
+ * user's other settings.
11
+ */
12
+ function loadJSON(file: string): Record<string, any> | null {
13
+ if (!existsSync(file)) return {}
14
+ try {
15
+ return JSON.parse(readFileSync(file, "utf-8"))
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+
6
21
  /**
7
22
  * Install MCP server configuration for a JSON-format agent.
8
23
  */
@@ -17,13 +32,10 @@ export function installJSONConfig(agent: Agent, scope: string): void {
17
32
  const configDir = dirname(configPath)
18
33
  if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
19
34
 
20
- let config: Record<string, any> = {}
21
- if (existsSync(configPath)) {
22
- try {
23
- config = JSON.parse(readFileSync(configPath, "utf-8"))
24
- } catch {
25
- config = {}
26
- }
35
+ const config = loadJSON(configPath)
36
+ if (config === null) {
37
+ console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
38
+ return
27
39
  }
28
40
 
29
41
  const mcpKey = agent.mcpKey || "mcpServers"
@@ -80,17 +92,22 @@ export function installZedConfig(agent: Agent): void {
80
92
  const configDir = dirname(configPath)
81
93
  if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
82
94
 
83
- let config: Record<string, any> = {}
95
+ let config: Record<string, any> | null = {}
84
96
  if (existsSync(configPath)) {
85
97
  try {
86
98
  const raw = readFileSync(configPath, "utf-8")
87
99
  const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
88
100
  config = JSON.parse(stripped)
89
101
  } catch {
90
- config = {}
102
+ config = null
91
103
  }
92
104
  }
93
105
 
106
+ if (config === null) {
107
+ console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
108
+ return
109
+ }
110
+
94
111
  if (!config.context_servers) config.context_servers = {}
95
112
 
96
113
  config.context_servers["toon-memory"] = {
@@ -114,13 +131,10 @@ export function installContinueConfig(agent: Agent): void {
114
131
  const configDir = dirname(configPath)
115
132
  if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
116
133
 
117
- let config: Record<string, any> = {}
118
- if (existsSync(configPath)) {
119
- try {
120
- config = JSON.parse(readFileSync(configPath, "utf-8"))
121
- } catch {
122
- config = {}
123
- }
134
+ const config = loadJSON(configPath)
135
+ if (config === null) {
136
+ console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
137
+ return
124
138
  }
125
139
 
126
140
  if (!config.experimental) config.experimental = {}
@@ -158,13 +172,10 @@ export function installOpenClawConfig(agent: Agent): void {
158
172
  const configDir = dirname(configPath)
159
173
  if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
160
174
 
161
- let config: Record<string, any> = {}
162
- if (existsSync(configPath)) {
163
- try {
164
- config = JSON.parse(readFileSync(configPath, "utf-8"))
165
- } catch {
166
- config = {}
167
- }
175
+ const config = loadJSON(configPath)
176
+ if (config === null) {
177
+ console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
178
+ return
168
179
  }
169
180
 
170
181
  if (!config.mcp) config.mcp = {}
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
2
2
  import { dirname, join } from "path"
3
+ import { fileURLToPath } from "url"
3
4
 
4
5
  export const projectRoot = process.cwd()
5
6
  export const HOME = process.env.HOME || process.env.USERPROFILE || "~"
@@ -8,11 +9,13 @@ export const HOME = process.env.HOME || process.env.USERPROFILE || "~"
8
9
  export const MEMORY_DIR = join(projectRoot, ".toon-memory", "memory")
9
10
 
10
11
  /**
11
- * Directory containing the running CLI script.
12
- * Derived from process.argv[1] — avoids __dirname / import.meta.url issues
13
- * in ESM bundles with top-level await.
12
+ * Directory containing the running CLI bundle.
13
+ * Derived from import.meta.url (NOT process.argv[1], which the entry points
14
+ * overwrite with "toon-memory" — that made the paths resolve relative to the
15
+ * hook's CWD). Every CLI bundle lives in dist/cli/, so this resolves to an
16
+ * absolute path in the installed package.
14
17
  */
15
- const scriptDir = dirname(process.argv[1] || process.cwd())
18
+ const scriptDir = dirname(fileURLToPath(import.meta.url))
16
19
 
17
20
  /** Path to the compiled capture script (dist/cli/capture.js) */
18
21
  export const CAPTURE_JS = join(scriptDir, "capture.js")
@@ -0,0 +1,11 @@
1
+ import { join } from "path"
2
+ import { pathToFileURL } from "url"
3
+
4
+ /**
5
+ * Build a file:// URL for a dynamic import relative to the running module.
6
+ * pathToFileURL is required on Windows: `import("C:\\...")` is parsed as a
7
+ * URL with scheme "c:" and throws ERR_UNSUPPORTED_ESM_URL_SCHEME.
8
+ */
9
+ export function fileImportURL(dirname: string, ...parts: string[]): string {
10
+ return pathToFileURL(join(dirname, ...parts)).href
11
+ }
package/src/cli/hooks.ts CHANGED
@@ -3,6 +3,21 @@ import { dirname, join } from "path"
3
3
  import type { Agent } from "./types"
4
4
  import { projectRoot, CAPTURE_JS, SESSION_START_JS, CAPTURE_CONFIG, ANTIGRAVITY_HOOK_NAME } from "./constants"
5
5
 
6
+ /**
7
+ * Read an existing JSON config file.
8
+ * Returns {} when the file is missing, or null when it exists but cannot be
9
+ * parsed — callers MUST skip (never overwrite) on null to avoid wiping the
10
+ * user's other settings.
11
+ */
12
+ function readJSON(file: string): Record<string, any> | null {
13
+ if (!existsSync(file)) return {}
14
+ try {
15
+ return JSON.parse(readFileSync(file, "utf-8"))
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+
6
21
  /** Hook script content for SessionStart reminder */
7
22
  export function sessionStartHookContent(agentName: string): string {
8
23
  return `#!/bin/bash
@@ -76,13 +91,10 @@ export function registerCaptureHookJSON(agent: Agent, scriptPath: string): void
76
91
  const configDir = dirname(configPath)
77
92
  if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
78
93
 
79
- let config: Record<string, any> = {}
80
- if (existsSync(configPath)) {
81
- try {
82
- config = JSON.parse(readFileSync(configPath, "utf-8"))
83
- } catch {
84
- config = {}
85
- }
94
+ const config = readJSON(configPath)
95
+ if (config === null) {
96
+ console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
97
+ return
86
98
  }
87
99
 
88
100
  if (!config.hooks) config.hooks = {}
@@ -136,7 +148,7 @@ export function registerHookJSON(agent: Agent, hookPath: string): void {
136
148
  const configDir = dirname(configPath)
137
149
  if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
138
150
 
139
- let config: Record<string, any> = {}
151
+ let config: Record<string, any> | null = {}
140
152
  if (existsSync(configPath)) {
141
153
  try {
142
154
  if (agent.format === "jsonc") {
@@ -147,10 +159,15 @@ export function registerHookJSON(agent: Agent, hookPath: string): void {
147
159
  config = JSON.parse(readFileSync(configPath, "utf-8"))
148
160
  }
149
161
  } catch {
150
- config = {}
162
+ config = null
151
163
  }
152
164
  }
153
165
 
166
+ if (config === null) {
167
+ console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
168
+ return
169
+ }
170
+
154
171
  if (agent.name === "claude" || agent.name === "gemini") {
155
172
  if (!config.hooks) config.hooks = {}
156
173
  if (!config.hooks.SessionStart) config.hooks.SessionStart = []
@@ -186,15 +203,20 @@ export function registerAntigravityHooks(agent: Agent): void {
186
203
  const hooksFile = join(base, "hooks.json")
187
204
  mkdirSync(base, { recursive: true })
188
205
 
189
- let cfg: Record<string, any> = {}
206
+ let cfg: Record<string, any> | null = {}
190
207
  if (existsSync(hooksFile)) {
191
208
  try {
192
209
  cfg = JSON.parse(readFileSync(hooksFile, "utf-8"))
193
210
  } catch {
194
- cfg = {}
211
+ cfg = null
195
212
  }
196
213
  }
197
214
 
215
+ if (cfg === null) {
216
+ console.log(` ⚠️ Skipping ${hooksFile}: existing file is not valid JSON — fix it manually, then re-run.`)
217
+ return
218
+ }
219
+
198
220
  cfg[ANTIGRAVITY_HOOK_NAME] = {
199
221
  PreInvocation: [{ type: "command", command: sessionPath }],
200
222
  PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: capPath }] }],
@@ -29,6 +29,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
29
29
  const recall = async (query, opts = {}) => {
30
30
  try {
31
31
  const args = { query, mode: "flat", budget: opts.budget || "tiny", path_scope: opts.path_scope || "" }
32
+ if (opts.category) args.category = opts.category
32
33
  const result = await $\`npx -y toon-memory mcp\`.cwd(root)
33
34
  .stdin(JSON.stringify({
34
35
  jsonrpc: "2.0",
@@ -42,11 +43,44 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
42
43
  } catch { return "" }
43
44
  }
44
45
 
46
+ // Pre-edit risk surfacing: warning-category entries scoped to a file path.
47
+ // Injected as a distinct block so the agent sees known risks before it edits.
48
+ const risks = async (filePath) => {
49
+ return await recall(filePath, { budget: "tiny", path_scope: filePath, category: "warning" })
50
+ }
51
+
45
52
  const write = (text) => {
46
53
  fs.mkdirSync(INS, { recursive: true })
47
54
  fs.writeFileSync(OUT, text)
48
55
  }
49
56
 
57
+ const pickPath = (args) => {
58
+ if (!args) return ""
59
+ if (args.file) return args.file
60
+ if (args.path) return args.path
61
+ if (args.filePath) return args.filePath
62
+ if (args.target) return args.target
63
+ return ""
64
+ }
65
+
66
+ const buildQuery = (filePath) => {
67
+ const basename = path.basename(filePath, path.extname(filePath))
68
+ const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
69
+ return [basename, ...dirParts.slice(-2)].join(" ")
70
+ }
71
+
72
+ const inject = (ctx, key, text) => {
73
+ if (!text || text.includes("(empty)") || text.includes("No results")) return
74
+ if (typeof ctx?.setContext === "function") ctx.setContext(key, text)
75
+ }
76
+
77
+ // Edit/write-ish tools are where known risks matter most.
78
+ const isEditTool = (name) => {
79
+ if (!name) return false
80
+ return name === "edit" || name === "write" || name === "apply-patch" ||
81
+ name.includes("edit") || name.includes("write") || name.includes("patch")
82
+ }
83
+
50
84
  return {
51
85
  "session.created": async () => {
52
86
  try {
@@ -60,6 +94,19 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
60
94
  if (Array.isArray(output?.context)) output.context.push(out)
61
95
  } catch {}
62
96
  },
97
+ "tool.execute.before": async (input, output) => {
98
+ // Pre-edit risk surfacing: for edit/write tools, surface known
99
+ // warning entries for the target file BEFORE the tool runs.
100
+ try {
101
+ const toolName = input?.tool || ""
102
+ if (!isEditTool(toolName)) return
103
+ const args = output?.args || input?.args || {}
104
+ const filePath = pickPath(args)
105
+ if (!filePath) return
106
+ const text = await risks(filePath)
107
+ inject(input, "toon-memory:risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + text)
108
+ } catch {}
109
+ },
63
110
  "tool.execute.after": async (input) => {
64
111
  // Intelligent auto-loading: extract file path from tool result,
65
112
  // recall only memory relevant to that file, inject as context.
@@ -69,11 +116,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
69
116
  const args = input?.args || {}
70
117
 
71
118
  // Extract file path from tool arguments or output
72
- let filePath = ""
73
- if (args.file) filePath = args.file
74
- else if (args.path) filePath = args.path
75
- else if (args.filePath) filePath = args.filePath
76
- else if (args.target) filePath = args.target
119
+ let filePath = pickPath(args)
77
120
 
78
121
  // Also try to extract from tool output text
79
122
  if (!filePath && input?.output) {
@@ -84,15 +127,15 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
84
127
 
85
128
  if (filePath) {
86
129
  // Build recall query from file path components
87
- const basename = path.basename(filePath, path.extname(filePath))
88
- const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
89
- const query = [basename, ...dirParts.slice(-2)].join(" ")
90
-
130
+ const query = buildQuery(filePath)
91
131
  const text = await recall(query, { budget: "tiny", path_scope: filePath })
92
- if (text && !text.includes("(empty)") && !text.includes("No results")) {
93
- if (typeof input?.setContext === "function") {
94
- input.setContext("toon-memory:" + filePath, text)
95
- }
132
+ inject(input, "toon-memory:" + filePath, text)
133
+
134
+ // Pre-edit risk block for edit/write tools (same key as the before
135
+ // hook — setContext overwrites, so no duplication when both fire).
136
+ if (isEditTool(toolName)) {
137
+ const riskText = await risks(filePath)
138
+ inject(input, "toon-memory:risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + riskText)
96
139
  }
97
140
  }
98
141
 
@@ -110,11 +153,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
110
153
 
111
154
  if (toolKeywords.length > 3) {
112
155
  const text = await recall(toolKeywords, { budget: "tiny" })
113
- if (text && !text.includes("(empty)") && !text.includes("No results")) {
114
- if (typeof input?.setContext === "function") {
115
- input.setContext("toon-memory:" + toolName, text)
116
- }
117
- }
156
+ inject(input, "toon-memory:" + toolName, text)
118
157
  }
119
158
  }
120
159
  } catch {}
@@ -1,12 +1,13 @@
1
- import { dirname, join } from "path"
1
+ import { dirname } from "path"
2
2
  import { fileURLToPath } from "url"
3
+ import { fileImportURL } from "./entry"
3
4
 
4
5
  const __dirname = dirname(fileURLToPath(import.meta.url))
5
6
  const args = process.argv.slice(2)
6
7
 
7
8
  if (args[0] === "mcp") {
8
- await import(join(__dirname, "..", "mcp", "server.js"))
9
+ await import(fileImportURL(__dirname, "..", "mcp", "server.js"))
9
10
  } else {
10
11
  process.argv = ["node", "toon-memory", ...args]
11
- await import(join(__dirname, "..", "dist", "cli", "setup.js"))
12
+ await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"))
12
13
  }