claude-mem-lite 4.0.4 → 5.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.
Files changed (64) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +18 -72
  4. package/README.zh-CN.md +24 -74
  5. package/adopt-content.mjs +0 -1
  6. package/cli/common.mjs +0 -17
  7. package/cli.mjs +19 -3
  8. package/commands/mem.md +3 -3
  9. package/commands/update.md +5 -12
  10. package/format-utils.mjs +0 -21
  11. package/haiku-client.mjs +36 -5
  12. package/hash-utils.mjs +21 -0
  13. package/hook-episode.mjs +7 -1
  14. package/hook-optimize.mjs +103 -50
  15. package/hook-shared.mjs +8 -2
  16. package/hook-update.mjs +56 -14
  17. package/hook.mjs +21 -29
  18. package/hooks/hooks.json +0 -10
  19. package/install.mjs +100 -678
  20. package/lib/atomic-write.mjs +16 -0
  21. package/lib/deferred-work.mjs +7 -3
  22. package/lib/doctor-drift.mjs +0 -1
  23. package/lib/frontmatter.mjs +1 -2
  24. package/lib/get-core.mjs +27 -1
  25. package/lib/hook-prune.mjs +133 -0
  26. package/lib/hook-stdin.mjs +1 -1
  27. package/lib/hook-telemetry.mjs +1 -1
  28. package/lib/install-shape.mjs +45 -4
  29. package/lib/maintain-core.mjs +9 -0
  30. package/lib/metrics.mjs +2 -2
  31. package/lib/proc-lock.mjs +111 -13
  32. package/lib/proxy-fetch.mjs +26 -2
  33. package/lib/scrub-record.mjs +8 -0
  34. package/lib/shard-gc.mjs +11 -7
  35. package/lib/tmp-fixture-sweep.mjs +9 -0
  36. package/mem-cli.mjs +46 -434
  37. package/nlp.mjs +1 -1
  38. package/npm-shrinkwrap.json +6 -2
  39. package/package.json +9 -16
  40. package/project-utils.mjs +43 -15
  41. package/schema.mjs +112 -50
  42. package/scripts/hook-launcher.mjs +9 -3
  43. package/scripts/prompt-search-utils.mjs +0 -30
  44. package/scripts/setup.sh +5 -0
  45. package/scripts/user-prompt-search.js +3 -125
  46. package/secret-scrub.mjs +32 -3
  47. package/server.mjs +19 -451
  48. package/source-files.mjs +12 -29
  49. package/synonyms.mjs +2 -1
  50. package/tool-schemas.mjs +23 -91
  51. package/utils.mjs +5 -13
  52. package/commands/tools.md +0 -67
  53. package/install-metadata.mjs +0 -2193
  54. package/lib/registry-core.mjs +0 -264
  55. package/registry/preinstalled.json +0 -2419
  56. package/registry-enricher.mjs +0 -124
  57. package/registry-github.mjs +0 -86
  58. package/registry-importer.mjs +0 -569
  59. package/registry-recommend.mjs +0 -503
  60. package/registry-retriever.mjs +0 -611
  61. package/registry-scanner.mjs +0 -261
  62. package/registry.mjs +0 -665
  63. package/resource-discovery.mjs +0 -199
  64. package/scripts/pre-skill-bridge.js +0 -146
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "4.0.4",
3
+ "version": "5.1.0",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. Hybrid FTS5 + TF-IDF search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark).",
5
5
  "type": "module",
6
6
  "packageManager": "npm@10.9.2",
7
7
  "engines": {
8
8
  "node": ">=22"
9
9
  },
10
+ "os": [
11
+ "darwin",
12
+ "linux"
13
+ ],
10
14
  "bin": {
11
15
  "claude-mem-lite": "./cli.mjs"
12
16
  },
@@ -28,7 +32,8 @@
28
32
  "benchmark:gate": "node benchmark/ci-gate.mjs",
29
33
  "audit:inventory": "node scripts/audit-metrics.mjs --inventory",
30
34
  "audit:deps": "node scripts/audit-metrics.mjs --deps",
31
- "audit:selfcheck": "node scripts/audit-metrics.mjs --self-check"
35
+ "audit:selfcheck": "node scripts/audit-metrics.mjs --self-check",
36
+ "hooks:install": "git config core.hooksPath .githooks && echo \"core.hooksPath -> .githooks (scripts/pre-commit.sh now runs on every commit)\""
32
37
  },
33
38
  "files": [
34
39
  "cli.mjs",
@@ -99,6 +104,7 @@
99
104
  "lib/hook-stdout.mjs",
100
105
  "lib/proc-lock.mjs",
101
106
  "lib/atomic-write.mjs",
107
+ "lib/hook-prune.mjs",
102
108
  "lib/proxy-fetch.mjs",
103
109
  "lib/llm-provider-probe.mjs",
104
110
  "lib/release-digest.mjs",
@@ -116,7 +122,6 @@
116
122
  "lib/save-observation.mjs",
117
123
  "lib/observation-write.mjs",
118
124
  "lib/recall-core.mjs",
119
- "lib/registry-core.mjs",
120
125
  "lib/timeline-core.mjs",
121
126
  "lib/search-core.mjs",
122
127
  "lib/recent-core.mjs",
@@ -146,18 +151,9 @@
146
151
  "cli/doctor.mjs",
147
152
  "cli/activity.mjs",
148
153
  "server/fts-check.mjs",
149
- "registry.mjs",
150
- "registry-retriever.mjs",
151
- "registry-recommend.mjs",
152
- "registry-scanner.mjs",
153
- "registry-github.mjs",
154
- "registry-importer.mjs",
155
- "registry-enricher.mjs",
156
- "resource-discovery.mjs",
157
154
  "source-files.mjs",
158
155
  "npm-shrinkwrap.json",
159
156
  "install.mjs",
160
- "install-metadata.mjs",
161
157
  "skip-tools.mjs",
162
158
  "tool-schemas.mjs",
163
159
  "utils.mjs",
@@ -177,7 +173,6 @@
177
173
  "commands/mem.md",
178
174
  "commands/memory.md",
179
175
  "commands/update.md",
180
- "commands/tools.md",
181
176
  "commands/adopt.md",
182
177
  "commands/unadopt.md",
183
178
  "commands/lesson.md",
@@ -190,7 +185,6 @@
190
185
  "scripts/user-prompt-search.js",
191
186
  "scripts/pre-tool-recall.js",
192
187
  "scripts/post-tool-recall.js",
193
- "scripts/pre-skill-bridge.js",
194
188
  "scripts/pre-agent-inject.sh",
195
189
  "scripts/pre-agent-inject.js",
196
190
  "scripts/prompt-search-utils.mjs",
@@ -199,8 +193,7 @@
199
193
  ".mcp.json",
200
194
  ".claude-plugin/plugin.json",
201
195
  ".claude-plugin/marketplace.json",
202
- "README.md",
203
- "registry/preinstalled.json"
196
+ "README.md"
204
197
  ],
205
198
  "dependencies": {
206
199
  "@modelcontextprotocol/sdk": "^1.30.0",
package/project-utils.mjs CHANGED
@@ -72,14 +72,31 @@ export function projectNameFromDir(p) {
72
72
  return raw.replace(/[^a-zA-Z0-9_.-]/g, '-').slice(0, 100);
73
73
  }
74
74
 
75
+ /** Escape LIKE metacharacters so a caller-supplied name is matched literally.
76
+ * R10 P2-3: unescaped, `--project '%'` matched every project and ORDER BY COUNT(*)
77
+ * returned the biggest one; `_` matched any single character the same way. */
78
+ function likeLiteral(s) {
79
+ return s.replace(/[\\%_]/g, '\\$&');
80
+ }
81
+
75
82
  /**
76
83
  * Resolve short project name to canonical "parent--base" form.
77
84
  * Uses DB suffix match with in-process cache.
85
+ *
86
+ * R10 P2-3 — `mode` is not cosmetic. The fuzzy steps 2 and 3 below are a deliberate READ
87
+ * convenience: a wrong guess costs one query, and the user sees an empty result and tries
88
+ * again. On a WRITE they cost the row's identity — `mem_save project:"api"` landed in
89
+ * `mono--api-gateway`, and the caller's own next project-scoped read of "api" does not
90
+ * find it. Write callers pass mode:'write' and get exact matching only: an already
91
+ * canonical name, the exact `%--name` suffix completion users depend on (`mem` ->
92
+ * `projects--mem`), an exactly existing bare name, or the caller's own string back.
93
+ *
78
94
  * @param {import('better-sqlite3').Database} db Database instance
79
95
  * @param {string|null|undefined} name Project name to resolve
96
+ * @param {{mode?: 'read'|'write'}} [opts]
80
97
  * @returns {string|null|undefined} Canonical project name
81
98
  */
82
- export function resolveProject(db, name) {
99
+ export function resolveProject(db, name, { mode = 'read' } = {}) {
83
100
  if (!name) return name;
84
101
  // Defense-in-depth: a bare `--project` CLI flag parses to boolean `true` (and a
85
102
  // malformed MCP/hook caller could pass any non-string). `true.includes('--')` below
@@ -87,10 +104,13 @@ export function resolveProject(db, name) {
87
104
  // Treat any non-string as "no project filter" (null) — the degradation every caller
88
105
  // already handles for an absent --project — instead of crashing at the root helper.
89
106
  if (typeof name !== 'string') return null;
90
- if (_cache.has(name)) return _cache.get(name);
107
+ // Key on the MODE too: the same name legitimately resolves to two different answers,
108
+ // and a name-only cache hands whichever call ran first to the other one.
109
+ const ck = `${mode}:${name}`;
110
+ if (_cache.has(ck)) return _cache.get(ck);
91
111
  // Already a canonical name (contains "--")? Use as-is.
92
112
  if (name.includes('--')) {
93
- _cache.set(name, name);
113
+ _cache.set(ck, name);
94
114
  return name;
95
115
  }
96
116
 
@@ -99,11 +119,11 @@ export function resolveProject(db, name) {
99
119
  // 1) Exact suffix match: "mem" → "projects--mem"
100
120
  const suffixed = db
101
121
  .prepare(
102
- 'SELECT project FROM observations WHERE project LIKE ? GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1',
122
+ "SELECT project FROM observations WHERE project LIKE ? ESCAPE '\\' GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1",
103
123
  )
104
- .get(`%--${name}`);
124
+ .get(`%--${likeLiteral(name)}`);
105
125
  if (suffixed) {
106
- _cache.set(name, suffixed.project);
126
+ _cache.set(ck, suffixed.project);
107
127
  return suffixed.project;
108
128
  }
109
129
 
@@ -115,18 +135,26 @@ export function resolveProject(db, name) {
115
135
  // the documented "prefer canonical parent--name over a stray short name" intent.
116
136
  const exact = db.prepare('SELECT project FROM observations WHERE project = ? LIMIT 1').get(name);
117
137
  if (exact) {
118
- _cache.set(name, exact.project);
138
+ _cache.set(ck, exact.project);
119
139
  return exact.project;
120
140
  }
121
141
 
142
+ // R10 P2-3: a write stops here. Steps 2 and 3 below guess; step 4 synthesizes from the
143
+ // process cwd, which for a write is worse still — an MCP call naming a project the
144
+ // caller is not sitting in would land in the caller's own directory's project.
145
+ if (mode === 'write') {
146
+ _cache.set(ck, name);
147
+ return name;
148
+ }
149
+
122
150
  // 2) Prefix-in-suffix match: "code-graph" → "projects--code-graph-mcp"
123
151
  const prefixed = db
124
152
  .prepare(
125
- 'SELECT project FROM observations WHERE project LIKE ? GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1',
153
+ "SELECT project FROM observations WHERE project LIKE ? ESCAPE '\\' GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1",
126
154
  )
127
- .get(`%--${name}%`);
155
+ .get(`%--${likeLiteral(name)}%`);
128
156
  if (prefixed) {
129
- _cache.set(name, prefixed.project);
157
+ _cache.set(ck, prefixed.project);
130
158
  return prefixed.project;
131
159
  }
132
160
 
@@ -140,23 +168,23 @@ export function resolveProject(db, name) {
140
168
  const token = db
141
169
  .prepare(
142
170
  `SELECT project FROM observations
143
- WHERE (project LIKE '%-' || ? || '-%' OR project LIKE '%-' || ?)
171
+ WHERE (project LIKE '%-' || ? || '-%' ESCAPE '\\' OR project LIKE '%-' || ? ESCAPE '\\')
144
172
  GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1`,
145
173
  )
146
- .get(name, name);
174
+ .get(likeLiteral(name), likeLiteral(name));
147
175
  if (token) {
148
- _cache.set(name, token.project);
176
+ _cache.set(ck, token.project);
149
177
  return token.project;
150
178
  }
151
179
 
152
180
  // 4) Fallback: synthesize canonical form from current directory
153
181
  const inferred = inferProject();
154
182
  if (inferred.endsWith(`--${name}`)) {
155
- _cache.set(name, inferred);
183
+ _cache.set(ck, inferred);
156
184
  return inferred;
157
185
  }
158
186
 
159
- _cache.set(name, name);
187
+ _cache.set(ck, name);
160
188
  return name;
161
189
  }
162
190
 
package/schema.mjs CHANGED
@@ -13,7 +13,6 @@ import { resolveDataDir } from './lib/resolve-data-dir.mjs';
13
13
  // CLAUDE_MEM_DIR so users can relocate state to a larger/faster volume.
14
14
  export const DB_DIR = resolveDataDir(process.env.CLAUDE_MEM_DIR);
15
15
  export const DB_PATH = join(DB_DIR, 'claude-mem-lite.db');
16
- export const REGISTRY_DB_PATH = join(DB_DIR, 'resource-registry.db');
17
16
  // CODE / install location — server.mjs, hook.mjs, cli.mjs, package.json live
18
17
  // here. ALWAYS homedir-rooted: Claude Code's settings.json + MCP registration
19
18
  // bake ABSOLUTE paths to server.mjs/hooks, so the code must NOT follow the
@@ -1062,8 +1061,8 @@ const DEFERRED_CLEANUPS = [
1062
1061
  },
1063
1062
  {
1064
1063
  // Project-name normalization: migrate short names ("mem") to canonical
1065
- // ("projects--mem"). Exact suffix match first, then distinctive-token
1066
- // substring. Idempotent: only acts on remaining short-name records.
1064
+ // ("projects--mem") by EXACT canonical-suffix match. Idempotent: only acts on
1065
+ // remaining short-name records.
1067
1066
  name: 'normalize-project-names',
1068
1067
  run: (db) => {
1069
1068
  const shortProjects = db
@@ -1078,52 +1077,66 @@ const DEFERRED_CLEANUPS = [
1078
1077
  )
1079
1078
  .all();
1080
1079
  if (shortProjects.length === 0) return;
1081
- const normalize = db.transaction(() => {
1082
- for (const { project: shortName } of shortProjects) {
1083
- let canonical = db
1084
- .prepare(
1085
- `SELECT project FROM observations WHERE project LIKE ? GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1`,
1086
- )
1087
- .get(`%--${shortName}`);
1088
- if (!canonical) {
1089
- const tokens = shortName.split(/[-_.]/).filter((t) => t.length >= 5);
1090
- for (const token of tokens) {
1091
- canonical = db
1092
- .prepare(
1093
- `SELECT project FROM observations WHERE project LIKE ? AND project LIKE '%--_%'
1094
- GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1`,
1095
- )
1096
- .get(`%${token}%`);
1097
- if (canonical) break;
1098
- }
1099
- }
1100
- if (canonical) {
1101
- // Rename the short project to canonical on EVERY project-scoped table.
1102
- // Originally only the first three were rewritten, so a short-named
1103
- // project's deferred TODOs (deferred_work), activity (events), citation
1104
- // history (citation_log + v45 citation_surface_log), and /clear-/exit
1105
- // handoffs (session_handoffs) were stranded on the old name — invisible to
1106
- // every project-scoped query after normalization. All eight carry a
1107
- // `project` column (verified).
1108
- for (const table of [
1109
- 'observations',
1110
- 'sdk_sessions',
1111
- 'session_summaries',
1112
- 'session_handoffs',
1113
- 'citation_log',
1114
- 'citation_surface_log',
1115
- 'events',
1116
- 'deferred_work',
1117
- ]) {
1118
- db.prepare(`UPDATE ${table} SET project = ? WHERE project = ?`).run(
1119
- canonical.project,
1120
- shortName,
1121
- );
1122
- }
1123
- }
1080
+ // R10 P1-3: ONE transaction per short name, not one for the whole scan. Three of the
1081
+ // eight tables below have a PRIMARY KEY containing `project`, so a single collision
1082
+ // used to roll back every OTHER project's rename too, leave the sentinel unwritten,
1083
+ // and replay the whole SELECT DISTINCT + N updates on every subsequent DB open —
1084
+ // i.e. on every hook event, forever, never converging.
1085
+ const renameOne = db.transaction((shortName, canonicalName) => {
1086
+ // Rename the short project to canonical on EVERY project-scoped table.
1087
+ // Originally only the first three were rewritten, so a short-named
1088
+ // project's deferred TODOs (deferred_work), activity (events), citation
1089
+ // history (citation_log + v45 citation_surface_log), and /clear-/exit
1090
+ // handoffs (session_handoffs) were stranded on the old name — invisible to
1091
+ // every project-scoped query after normalization. All eight carry a
1092
+ // `project` column (verified).
1093
+ for (const table of [
1094
+ 'observations',
1095
+ 'sdk_sessions',
1096
+ 'session_summaries',
1097
+ 'session_handoffs',
1098
+ 'citation_log',
1099
+ 'citation_surface_log',
1100
+ 'events',
1101
+ 'deferred_work',
1102
+ ]) {
1103
+ // R10 P1-3: OR IGNORE. session_handoffs (project,type,session_id),
1104
+ // citation_log (project,memory_session_id) and citation_surface_log
1105
+ // (project,session_id,surface) collide whenever the SAME session was recorded
1106
+ // under both names — which is exactly what an in-session plugin upgrade
1107
+ // produces. Skipping the colliding row keeps the canonical one, which is the
1108
+ // newer and more complete of the two; the alternative was a permanent stall.
1109
+ db.prepare(`UPDATE OR IGNORE ${table} SET project = ? WHERE project = ?`).run(
1110
+ canonicalName,
1111
+ shortName,
1112
+ );
1124
1113
  }
1125
1114
  });
1126
- normalize();
1115
+ for (const { project: shortName } of shortProjects) {
1116
+ // R10 P1-2: EXACT canonical-suffix match only. There used to be a fallback that
1117
+ // took any >=5-char token of the short name and substring-matched it against every
1118
+ // canonical project — so `workspace`, the ordinary name for a devcontainer whose
1119
+ // cwd is the filesystem root `/workspace`, was absorbed into an unrelated
1120
+ // `workspaces--repo` across all eight tables. project-utils.mjs:109-120 already
1121
+ // treats a root-directory short name as legitimate; this cleanup did not, there is
1122
+ // no snapshot on this path, and the sentinel means it never runs again. A legacy
1123
+ // name that only a token match could resolve is still readable — resolveProject
1124
+ // step 3 does that substring match at READ time, where a wrong guess costs a query
1125
+ // rather than the row's identity.
1126
+ const canonical = db
1127
+ .prepare(
1128
+ `SELECT project FROM observations WHERE project LIKE ? GROUP BY project ORDER BY COUNT(*) DESC LIMIT 1`,
1129
+ )
1130
+ .get(`%--${shortName}`);
1131
+ if (canonical) {
1132
+ try {
1133
+ renameOne(shortName, canonical.project);
1134
+ } catch (e) {
1135
+ // One project's failure must not abandon the others, nor the sentinel.
1136
+ debugCatch(e, 'normalize-project-names');
1137
+ }
1138
+ }
1139
+ }
1127
1140
  },
1128
1141
  },
1129
1142
  ];
@@ -1228,9 +1241,25 @@ export function ensureDb() {
1228
1241
  * uncheckpointed transactions — silent data loss.
1229
1242
  */
1230
1243
  export function isDbCorruptionError(err) {
1231
- return /SQLITE_CORRUPT|SQLITE_NOTADB|malformed|not a database|disk image/i.test(
1232
- `${err?.code || ''} ${err?.message || ''}`,
1233
- );
1244
+ // R10 P3-9: SQLITE_CORRUPT_VTAB is EXCLUDED. It means a damaged FTS5 index over an
1245
+ // otherwise healthy file, and both halves of the WAL remedy are wrong for it — deleting
1246
+ // the WAL discards committed-but-uncheckpointed transactions (the reason this predicate
1247
+ // exists at all, per the docblock above), and it cannot repair an index that lives in the
1248
+ // main database file. isFtsCorruptionError below routes it to rebuildFTS instead.
1249
+ const text = `${err?.code || ''} ${err?.message || ''}`;
1250
+ if (isFtsCorruptionError(err)) return false;
1251
+ return /SQLITE_CORRUPT|SQLITE_NOTADB|malformed|not a database|disk image/i.test(text);
1252
+ }
1253
+
1254
+ /**
1255
+ * Whether an error is a damaged FTS5 INDEX rather than a damaged database file. SQLite
1256
+ * reports these as SQLITE_CORRUPT_VTAB, whose message text is the same
1257
+ * "database disk image is malformed" the file-level faults use — so the code is the only
1258
+ * thing that separates them, and matching on message alone is what conflated them.
1259
+ * The remedy is rebuildFTS, which the FTS content lets us do losslessly.
1260
+ */
1261
+ export function isFtsCorruptionError(err) {
1262
+ return /SQLITE_CORRUPT_VTAB/i.test(`${err?.code || ''}`);
1234
1263
  }
1235
1264
 
1236
1265
  /**
@@ -1250,6 +1279,39 @@ export function ensureDbWithWalRecovery({ warn, info } = {}) {
1250
1279
  try {
1251
1280
  return ensureDb();
1252
1281
  } catch (firstErr) {
1282
+ // R10 P3-9: FTS index damage first, because its remedy is both correct and lossless
1283
+ // while the WAL remedy below is neither. Open a raw handle (ensureDb just failed, so
1284
+ // its schema pass cannot be trusted to get far enough), rebuild every FTS table from
1285
+ // its content table, then retry the real opener.
1286
+ if (isFtsCorruptionError(firstErr)) {
1287
+ warn?.(`FTS index corruption detected, rebuilding indexes: ${firstErr.message}`);
1288
+ let raw = null;
1289
+ try {
1290
+ raw = new Database(DB_PATH);
1291
+ const { errors } = rebuildFTS(raw);
1292
+ if (errors.length) warn?.(`FTS rebuild reported: ${errors.join('; ')}`);
1293
+ } catch (rebuildErr) {
1294
+ warn?.(`FTS rebuild failed: ${rebuildErr.message}`);
1295
+ } finally {
1296
+ try {
1297
+ raw?.close();
1298
+ } catch {
1299
+ /* best-effort */
1300
+ }
1301
+ }
1302
+ try {
1303
+ const db = ensureDb();
1304
+ info?.('DB recovered after FTS rebuild');
1305
+ return db;
1306
+ } catch (retryErr) {
1307
+ try {
1308
+ retryErr.ftsRebuildAttempted = true;
1309
+ } catch {
1310
+ /* frozen error — fine */
1311
+ }
1312
+ throw retryErr;
1313
+ }
1314
+ }
1253
1315
  if (!isDbCorruptionError(firstErr)) throw firstErr;
1254
1316
  warn?.(`DB corruption detected, attempting WAL recovery: ${firstErr.message}`);
1255
1317
  try {
@@ -54,7 +54,7 @@ const DATA_DIR = MEM_DIR && isAbsolute(MEM_DIR) ? MEM_DIR : join(homedir(), '.cl
54
54
  // declared exception in the tree: the launcher runs BEFORE the native binding is known to
55
55
  // work, so it imports only `node:` builtins on purpose — even a leaf lib module is a
56
56
  // resolution it declines to make on the path whose job is surviving a broken install. The
57
- // standalone hook scripts it mirrors (pre-tool-recall / pre-skill-bridge) honour the same
57
+ // standalone hook scripts it mirrors (pre-tool-recall / post-tool-recall) honour the same
58
58
  // variable and write 78 of every 79 of these markers, so reading a different dir would mean
59
59
  // never healing. `resolveRuntimeDir` is the canonical rule (audit 2026-09-02 P1-14) and this
60
60
  // is NOT identical to it: the resolver additionally makes a RELATIVE override absolute
@@ -331,7 +331,13 @@ async function attemptHeal(reason) {
331
331
  return false;
332
332
  }
333
333
  const result = spawnSync(process.execPath, [installer, 'repair'], {
334
- stdio: 'inherit',
334
+ // R10 P2-15: NOT 'inherit'. The installer prints progress on stdout, and this process's
335
+ // stdout is the hook channel — the host parses it as one JSON envelope. With 'inherit',
336
+ // `✓ repair: copied 3 files…` was prepended to `{"suppressOutput":true,…}`, the whole
337
+ // stream stopped being JSON, and it went down the plainText path with suppressOutput
338
+ // silently inoperative. The installer's own diagnostics belong on stderr, which the host
339
+ // shows to the user anyway; index 0 is ignored because repair reads no stdin.
340
+ stdio: ['ignore', 2, 2],
335
341
  timeout: 300000,
336
342
  });
337
343
  return result.status === 0;
@@ -342,7 +348,7 @@ async function attemptHeal(reason) {
342
348
  //
343
349
  // Since the heal moved off the hot path, a hot-path fire that hits a missing module records
344
350
  // the breakage and defers. But this launcher fronts several entries — hook.mjs plus
345
- // pre-tool-recall.js, pre-skill-bridge.js, post-tool-recall.js, user-prompt-search.js — and
351
+ // pre-tool-recall.js, post-tool-recall.js, user-prompt-search.js — and
346
352
  // the missing module may sit on one of THEIR import chains and not on hook.mjs's. Then
347
353
  // session-start's own entry imports cleanly, the catch below never fires, and before this
348
354
  // function existed the clean fire simply cleared the marker: nothing ever repaired it. (That
@@ -244,36 +244,6 @@ export function shouldSkipByDedup(newIds, injectedFile, sessionId) {
244
244
  }
245
245
  }
246
246
 
247
- // ─── Registry Skill Name Matching ───────────────────────────────────────────
248
-
249
- /**
250
- * Check if prompt text contains a known managed skill name.
251
- * Returns the matched name or null.
252
- * @param {string} text - user prompt
253
- * @param {Set<string>} skillNames - set of known managed skill names (lowercase)
254
- * @returns {string|null}
255
- */
256
- export function matchRegistrySkillName(text, skillNames) {
257
- if (!text || skillNames.size === 0) return null;
258
- const lower = text.toLowerCase();
259
-
260
- // Sort names longest-first to match "code-review-expert" before "code-review"
261
- const sorted = [...skillNames].sort((a, b) => b.length - a.length);
262
-
263
- for (const name of sorted) {
264
- const idx = lower.indexOf(name);
265
- if (idx === -1) continue;
266
-
267
- // Check word boundaries: char before and after must be non-alphanumeric (or start/end)
268
- const before = idx === 0 ? ' ' : lower[idx - 1];
269
- const after = idx + name.length >= lower.length ? ' ' : lower[idx + name.length];
270
- if (/[a-z0-9]/.test(before) || /[a-z0-9]/.test(after)) continue;
271
-
272
- return name;
273
- }
274
- return null;
275
- }
276
-
277
247
  // ─── File Path Detection ─────────────────────────────────────────────────────
278
248
 
279
249
  /** Detect file paths in text — excludes URLs and pure version numbers */
package/scripts/setup.sh CHANGED
@@ -259,6 +259,11 @@ if [[ -n "${CLAUDE_PLUGIN_ROOT:-}" ]]; then
259
259
  # cache) it falls outside the newest 3 — so this loop deleted the tree every hook
260
260
  # and the MCP server import from, mid-session. -ef compares device+inode, so it is
261
261
  # not fooled by a trailing slash, a `..` segment or a symlinked cache dir.
262
+ # R10 P2-9 checked this and it needs no change: the whole step is gated on
263
+ # CLAUDE_PLUGIN_ROOT being set (see the `if` above), so unlike prunePluginCache()
264
+ # — which also runs from a terminal, where Claude Code does not set it — this
265
+ # comparison is never made against an empty value. Do not "align" it by dropping
266
+ # that outer gate.
262
267
  # hook-update.mjs prunePluginCache() carries the same guard; the two prune the same
263
268
  # directory and must agree.
264
269
  if [[ "$CACHE_DIR/$ver" -ef "$CLAUDE_PLUGIN_ROOT" ]]; then
@@ -3,7 +3,7 @@
3
3
  // Runs as UserPromptSubmit hook — injects relevant memories before Claude sees the prompt
4
4
  // Lightweight: only imports schema.mjs and utils.mjs, no MCP SDK
5
5
 
6
- import { ensureDb, DB_DIR, REGISTRY_DB_PATH } from '../schema.mjs';
6
+ import { ensureDb, DB_DIR } from '../schema.mjs';
7
7
  import {
8
8
  relaxFtsQueryToOr,
9
9
  truncate,
@@ -22,10 +22,9 @@ import { fileMatchClause, fileMatchParams, basenameAnySep } from '../lib/file-ed
22
22
  import { cjkPrecisionOk } from '../nlp.mjs';
23
23
  import { upsFtsQuery } from '../lib/ups-query.mjs';
24
24
  import { corpusFloorScale } from '../lib/relevance-floor.mjs';
25
- import { writeFileSync, readFileSync, existsSync, renameSync } from 'fs';
26
- import { join, sep } from 'path';
25
+ import { readFileSync } from 'fs';
26
+ import { join } from 'path';
27
27
  import { pathToFileURL } from 'url';
28
- import Database from 'better-sqlite3';
29
28
  import {
30
29
  shouldSkip,
31
30
  computeEffectiveLen,
@@ -35,12 +34,10 @@ import {
35
34
  extractErrorSignature,
36
35
  extractDeferredRefs,
37
36
  DEDUP_STALE_MS,
38
- matchRegistrySkillName,
39
37
  detectMemOverride,
40
38
  } from './prompt-search-utils.mjs';
41
39
  import { injectedIdsFileName, mergeInjectedMarker } from '../lib/injected-ids.mjs';
42
40
  import { getDeferredByIds } from '../lib/deferred-work.mjs';
43
- import { recommendSkill } from '../registry-recommend.mjs';
44
41
  import { recordHookError } from '../lib/hook-telemetry.mjs';
45
42
 
46
43
  import { DAY_MS } from '../lib/time-constants.mjs';
@@ -649,73 +646,6 @@ function formatPromptResults(rows) {
649
646
  return lines.join('\n');
650
647
  }
651
648
 
652
- // ─── Registry Skill Pointer (T4 v2.31) ─────────────────────────────────────
653
- // Formerly "auto-load": we used to read the full SKILL.md body (up to 16KB)
654
- // and inject it into stdout on keyword match. Now we only emit a short
655
- // pointer line so Claude can decide to invoke via SkillTool. The cooldown
656
- // and match mechanics below are unchanged.
657
-
658
- const SKILL_COOLDOWN_FILE = join(RUNTIME_DIR, `.skill-cooldown-${inferProject()}`);
659
- const SKILL_COOLDOWN_MS = 300_000; // 5 minutes
660
-
661
- function loadManagedSkillNames() {
662
- if (!existsSync(REGISTRY_DB_PATH)) return new Set();
663
- try {
664
- const rdb = new Database(REGISTRY_DB_PATH, { readonly: true });
665
- rdb.pragma('busy_timeout = 500');
666
- try {
667
- // D#29: derive the managed marker from the env-aware data dir, not a hardcoded
668
- // homedir literal — under CLAUDE_MEM_DIR relocation the stored local_path lives at
669
- // DB_DIR/managed, so the old literal matched nothing and dropped every managed skill
670
- // from injection. Coarse LIKE prefilter; resource names are re-validated downstream.
671
- // D#29: derive the managed marker from the env-aware data dir, not a hardcoded
672
- // homedir literal — under CLAUDE_MEM_DIR relocation the stored local_path lives at
673
- // DB_DIR/managed, so the old literal matched nothing and dropped every managed skill
674
- // from injection. Coarse LIKE prefilter; resource names are re-validated downstream.
675
- const rows = rdb
676
- .prepare(
677
- `
678
- SELECT name FROM resources
679
- WHERE status = 'active' AND local_path LIKE ?
680
- `,
681
- )
682
- .all(`%${join(DB_DIR, 'managed') + sep}%`);
683
- return new Set(rows.map((r) => r.name.toLowerCase()));
684
- } finally {
685
- rdb.close();
686
- }
687
- } catch {
688
- return new Set();
689
- }
690
- }
691
-
692
- function getSkillCooldown() {
693
- try {
694
- const raw = readFileSync(SKILL_COOLDOWN_FILE, 'utf8');
695
- const data = JSON.parse(raw);
696
- const now = Date.now();
697
- const cleaned = {};
698
- for (const [k, v] of Object.entries(data)) {
699
- if (now - v < SKILL_COOLDOWN_MS) cleaned[k] = v;
700
- }
701
- return cleaned;
702
- } catch {
703
- return {};
704
- }
705
- }
706
-
707
- function setSkillCooldown(name) {
708
- try {
709
- const data = getSkillCooldown();
710
- data[name] = Date.now();
711
- const tmp = SKILL_COOLDOWN_FILE + `.tmp-${process.pid}`;
712
- writeFileSync(tmp, JSON.stringify(data));
713
- renameSync(tmp, SKILL_COOLDOWN_FILE);
714
- } catch {
715
- /* silent */
716
- }
717
- }
718
-
719
649
  // ─── Main ───────────────────────────────────────────────────────────────────
720
650
 
721
651
  async function main() {
@@ -1091,58 +1021,6 @@ async function main() {
1091
1021
  } catch {}
1092
1022
  }
1093
1023
  }
1094
-
1095
- // ─── L1: Registry skill pointer (T4 v2.31) ──────────────────────────
1096
- // Previously this block injected the full skill body (up to 16KB) on
1097
- // keyword match, silently inflating every matched prompt. We now emit a
1098
- // single pointer line so Claude can decide to invoke via SkillTool on
1099
- // demand — the cooldown and match preconditions stay identical.
1100
- try {
1101
- const skillNames = loadManagedSkillNames();
1102
- const matched = matchRegistrySkillName(promptText, skillNames);
1103
- if (matched) {
1104
- const cooldown = getSkillCooldown();
1105
- if (!cooldown[matched]) {
1106
- // Registry skill names come from third-party repos (tools/adopt import) — an
1107
- // untrusted boundary like every other DB-derived string on this surface.
1108
- const safeName = neutralizeContextDelimiters(matched);
1109
- process.stdout.write(
1110
- `\n[mem] Skill "${safeName}" may apply — invoke via SkillTool or run: claude-mem-lite registry show ${safeName}\n`,
1111
- );
1112
- setSkillCooldown(matched);
1113
- }
1114
- }
1115
- } catch {
1116
- /* silent — never block on registry failure */
1117
- }
1118
-
1119
- // ─── L2: Intent-based skill recommendation (shadow-first, v3.12) ─────
1120
- // Distinct from L1 (explicit-name pointer): fires on intent even when the
1121
- // user did not name a skill. Phase 1 = shadow only (logs, never emits).
1122
- // Reuses a readonly registry DB; cooldown/shadow writes go to the FS.
1123
- try {
1124
- if (existsSync(REGISTRY_DB_PATH)) {
1125
- // #8259: explicit-signal presence is the decisive lever for UPS injection
1126
- // quality (UPS cite-recall was 25.8% until gated on it). Logged in shadow so
1127
- // Phase 2 can decide whether live injection gates on it. Shadow measures broadly.
1128
- const hasSignal = !!(
1129
- extractErrorSignature(promptText) ||
1130
- extractFiles(promptText).length > 0 ||
1131
- detectIntent(promptText)
1132
- );
1133
- const rdb = new Database(REGISTRY_DB_PATH, { readonly: true });
1134
- rdb.pragma('busy_timeout = 500');
1135
- // CC session_id (hook stdin) is the cross-hook pairing key: PostToolUse adoptions
1136
- // in this same session join back to this reco for matched precision (B1).
1137
- try {
1138
- recommendSkill(rdb, promptText, inferProject(), { hasSignal, sessionId: hookData.session_id });
1139
- } finally {
1140
- rdb.close();
1141
- }
1142
- }
1143
- } catch {
1144
- /* silent — never block on recommendation failure */
1145
- }
1146
1024
  } catch (e) {
1147
1025
  // Hooks must never break Claude Code — swallow, but RECORD: this catch wraps
1148
1026
  // every FTS query on the surface, so a schema/FTS drift here would zero out