@lh8ppl/claude-memory-kit 0.2.2 → 0.2.4

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/src/doctor.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // `cmk doctor` — health checks HC-1..HC-9 (Task 37, T-031).
1
+ // `cmk doctor` — health checks HC-1..HC-7 (Task 37, T-031; memsearch HC-1/HC-7 removed in Task 120).
2
2
  //
3
3
  // Public boundary:
4
4
  // async runDoctor({projectRoot, userDir, now, promptUser?, ...overrides})
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // HCResult shape:
8
8
  // {
9
- // id: 'HC-1' | ... | 'HC-9',
9
+ // id: 'HC-1' | ... | 'HC-7',
10
10
  // name: string,
11
11
  // status: 'pass' | 'fail' | 'skip',
12
12
  // message: string,
@@ -15,10 +15,10 @@
15
15
  // }
16
16
  //
17
17
  // Per design §14. Composes on:
18
- // - cooldown.mjs (HC-3 distill freshness via cooldown marker mtime is
18
+ // - cooldown.mjs (HC-2 distill freshness via cooldown marker mtime is
19
19
  // NOT used — we read recent.md mtime directly, more accurate)
20
- // - lazy-compress.mjs::cronSentinelPath (HC-6 cron registration check)
21
- // - lock-discipline.mjs::detectStaleLocks (HC-9)
20
+ // - lazy-compress.mjs::cronSentinelPath (HC-5 cron registration check)
21
+ // - lock-discipline.mjs::detectStaleLocks (HC-7)
22
22
  // - platform-commands.mjs — cross-platform repair command emission
23
23
  //
24
24
  // Critical rule per design §14 + tasks.md 37.5: any repair requiring
@@ -38,7 +38,6 @@ import {
38
38
  statSync,
39
39
  writeFileSync,
40
40
  } from 'node:fs';
41
- import { spawnBinSync } from './spawn-bin.mjs';
42
41
  import { homedir } from 'node:os';
43
42
  import { basename, join } from 'node:path';
44
43
  import { nowIso } from './audit-log.mjs';
@@ -56,62 +55,15 @@ const MEMORY_DIR_REL = ['context', 'memory'];
56
55
  const LOCKS_REL = ['context', '.locks'];
57
56
  const NATIVE_MEMORY_LOG_REL = ['context', '.locks', 'native-memory-status.log'];
58
57
 
59
- // --- HC-1: memsearch installed ----------------------------------------
60
- async function hc1Memsearch() {
61
- // Layer 5b (semantic search) is OPTIONAL per ADR-0008. Missing
62
- // memsearch → skip (not fail). The kit ships keyword-only as v0.1.0;
63
- // semantic requires a separate `pip install memsearch[onnx]`.
64
- // `requiresInstall: true` so the CLI prompts before auto-installing.
65
- try {
66
- // spawnBinSync resolves the Windows .cmd shim without `shell:true`+args
67
- // (no DEP0190; #4). memsearch's only arg is `--version` (no spaces), so
68
- // the quoting is a no-op here — the win is dropping the deprecated combo.
69
- const r = spawnBinSync('memsearch', ['--version'], {
70
- encoding: 'utf8',
71
- // M1 fix (skill-review 2026-05-28): 3.5s tolerates Windows
72
- // cold-Python startup (AV scan + .pyc generation on first hit
73
- // can push past 2s for a healthy install). HC-2..9 are file-
74
- // system ops that complete in ≪100ms total, so HC-1 + the rest
75
- // still fits comfortably inside the 5s NFR budget. Timeout →
76
- // 'skip' so cmk doctor completes regardless.
77
- timeout: 3_500,
78
- });
79
- if (r.status === 0) {
80
- return {
81
- id: 'HC-1',
82
- name: 'memsearch installed (semantic search backend)',
83
- status: 'pass',
84
- message: `memsearch ${(r.stdout || '').trim() || 'detected'}`,
85
- };
86
- }
87
- } catch {
88
- // fall through to skip
89
- }
90
- // Lior 2026-05-28: make the feature impact explicit so users
91
- // understand WHAT THEY LOSE by skipping the install, not just that
92
- // a check failed. Matches Lior's directive: "ask before we do
93
- // anything, explain if they dont install they dont get certain
94
- // features".
95
- return {
96
- id: 'HC-1',
97
- name: 'memsearch installed (semantic search backend)',
98
- status: 'skip',
99
- message:
100
- 'memsearch not on PATH — Layer 5b semantic backend disabled. Features unavailable: `cmk search --mode=semantic` (will error), `cmk search --mode=hybrid` (will error). Keyword search (`cmk search --mode=keyword`, default) still works fully.',
101
- recoveryCommand: 'python -m pip install "memsearch[onnx]"',
102
- requiresInstall: true,
103
- };
104
- }
105
-
106
- // --- HC-2: Stop + SessionStart hooks registered -----------------------
107
- function hc2Hooks({ projectRoot }) {
58
+ // --- HC-1: Stop + SessionStart hooks registered -----------------------
59
+ function hc1Hooks({ projectRoot }) {
108
60
  // Per design §5 — the kit's hooks live in .claude/settings.json
109
61
  // alongside its plugin manifest. Required for auto-extract +
110
62
  // session-end compression to fire.
111
63
  const settingsPath = join(projectRoot, '.claude', 'settings.json');
112
64
  if (!existsSync(settingsPath)) {
113
65
  return {
114
- id: 'HC-2',
66
+ id: 'HC-1',
115
67
  name: 'Stop + SessionStart hooks registered',
116
68
  status: 'fail',
117
69
  message: '.claude/settings.json missing — hooks not wired',
@@ -123,7 +75,7 @@ function hc2Hooks({ projectRoot }) {
123
75
  settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
124
76
  } catch (err) {
125
77
  return {
126
- id: 'HC-2',
78
+ id: 'HC-1',
127
79
  name: 'Stop + SessionStart hooks registered',
128
80
  status: 'fail',
129
81
  message: `.claude/settings.json parse error: ${err?.message ?? err}`,
@@ -170,7 +122,7 @@ function hc2Hooks({ projectRoot }) {
170
122
  }
171
123
  if (missing.length > 0) {
172
124
  return {
173
- id: 'HC-2',
125
+ id: 'HC-1',
174
126
  name: 'Stop + SessionStart hooks registered',
175
127
  status: 'fail',
176
128
  message: `missing hook references: ${missing.join(', ')}`,
@@ -178,15 +130,15 @@ function hc2Hooks({ projectRoot }) {
178
130
  };
179
131
  }
180
132
  return {
181
- id: 'HC-2',
133
+ id: 'HC-1',
182
134
  name: 'Stop + SessionStart hooks registered',
183
135
  status: 'pass',
184
136
  message: 'all kit hooks wired to their correct event arrays in .claude/settings.json',
185
137
  };
186
138
  }
187
139
 
188
- // --- HC-3: distill freshness (≤2 days) --------------------------------
189
- function hc3DistillFreshness({ projectRoot, now }) {
140
+ // --- HC-2: distill freshness (≤2 days) --------------------------------
141
+ function hc2DistillFreshness({ projectRoot, now }) {
190
142
  const recentPath = join(projectRoot, ...RECENT_MD_REL);
191
143
  if (!existsSync(recentPath)) {
192
144
  // Not a failure: on a fresh project there's nothing distilled yet, and
@@ -194,7 +146,7 @@ function hc3DistillFreshness({ projectRoot, now }) {
194
146
  // (or `cmk daily-distill`). "Stale recent.md" below IS a real fail; a
195
147
  // never-built one is just "not yet" — mirror HC-5's skip-on-fresh.
196
148
  return {
197
- id: 'HC-3',
149
+ id: 'HC-2',
198
150
  name: 'Daily distill is fresh (≤2 days)',
199
151
  status: 'skip',
200
152
  message: 'recent.md not built yet — nothing to distill. Runs automatically (lazy-on-read at SessionStart, or `cmk daily-distill`) once there is session content.',
@@ -205,7 +157,7 @@ function hc3DistillFreshness({ projectRoot, now }) {
205
157
  mtimeMs = statSync(recentPath).mtimeMs;
206
158
  } catch (err) {
207
159
  return {
208
- id: 'HC-3',
160
+ id: 'HC-2',
209
161
  name: 'Daily distill is fresh (≤2 days)',
210
162
  status: 'fail',
211
163
  message: `recent.md stat error: ${err?.message ?? err}`,
@@ -216,7 +168,7 @@ function hc3DistillFreshness({ projectRoot, now }) {
216
168
  const ageMs = nowMs - mtimeMs;
217
169
  if (ageMs > TWO_DAYS_MS) {
218
170
  return {
219
- id: 'HC-3',
171
+ id: 'HC-2',
220
172
  name: 'Daily distill is fresh (≤2 days)',
221
173
  status: 'fail',
222
174
  message: `recent.md ${Math.round(ageMs / (24 * 60 * 60 * 1000))}d old (cutoff: 2d)`,
@@ -224,21 +176,21 @@ function hc3DistillFreshness({ projectRoot, now }) {
224
176
  };
225
177
  }
226
178
  return {
227
- id: 'HC-3',
179
+ id: 'HC-2',
228
180
  name: 'Daily distill is fresh (≤2 days)',
229
181
  status: 'pass',
230
182
  message: `recent.md ${Math.round(ageMs / (60 * 60 * 1000))}h old`,
231
183
  };
232
184
  }
233
185
 
234
- // --- HC-4: transcripts firing (≤3 days) -------------------------------
235
- function hc4Transcripts({ projectRoot, now }) {
186
+ // --- HC-3: transcripts firing (≤3 days) -------------------------------
187
+ function hc3Transcripts({ projectRoot, now }) {
236
188
  const transcriptsDir = join(projectRoot, ...TRANSCRIPTS_REL);
237
189
  if (!existsSync(transcriptsDir)) {
238
190
  // Fresh project, never had a Claude Code session here → nothing to fire
239
191
  // yet. Skip, don't fail (the dir + first transcript appear on the first turn).
240
192
  return {
241
- id: 'HC-4',
193
+ id: 'HC-3',
242
194
  name: 'Transcripts firing (≤3 days)',
243
195
  status: 'skip',
244
196
  message: 'no transcripts yet — they appear after your first Claude Code turn in this project.',
@@ -262,7 +214,7 @@ function hc4Transcripts({ projectRoot, now }) {
262
214
  // Dir exists (scaffolded) but no transcripts captured yet → still "not
263
215
  // yet", not a failure.
264
216
  return {
265
- id: 'HC-4',
217
+ id: 'HC-3',
266
218
  name: 'Transcripts firing (≤3 days)',
267
219
  status: 'skip',
268
220
  message: 'no transcripts yet — they appear after your first Claude Code turn in this project.',
@@ -272,7 +224,7 @@ function hc4Transcripts({ projectRoot, now }) {
272
224
  // Transcripts EXIST but none recent → the kit was capturing and stopped.
273
225
  // That IS a real signal (the Stop hook may not be firing here).
274
226
  return {
275
- id: 'HC-4',
227
+ id: 'HC-3',
276
228
  name: 'Transcripts firing (≤3 days)',
277
229
  status: 'fail',
278
230
  message: 'transcripts exist but none within 3 days — the Stop hook may have stopped firing (is this project Claude Code\'s primary cwd?)',
@@ -280,20 +232,20 @@ function hc4Transcripts({ projectRoot, now }) {
280
232
  };
281
233
  }
282
234
  return {
283
- id: 'HC-4',
235
+ id: 'HC-3',
284
236
  name: 'Transcripts firing (≤3 days)',
285
237
  status: 'pass',
286
238
  message: `${recentCount} transcript(s) within 3 days`,
287
239
  };
288
240
  }
289
241
 
290
- // --- HC-5: INDEX.md matches context/memory/ ---------------------------
291
- function hc5IndexConsistency({ projectRoot }) {
242
+ // --- HC-4: INDEX.md matches context/memory/ ---------------------------
243
+ function hc4IndexConsistency({ projectRoot }) {
292
244
  const memoryDir = join(projectRoot, ...MEMORY_DIR_REL);
293
245
  const indexPath = join(projectRoot, ...MEMORY_INDEX_REL);
294
246
  if (!existsSync(memoryDir)) {
295
247
  return {
296
- id: 'HC-5',
248
+ id: 'HC-4',
297
249
  name: 'INDEX.md matches context/memory/ files',
298
250
  status: 'skip',
299
251
  message: 'context/memory/ missing — no granular facts to index yet',
@@ -301,7 +253,7 @@ function hc5IndexConsistency({ projectRoot }) {
301
253
  }
302
254
  if (!existsSync(indexPath)) {
303
255
  return {
304
- id: 'HC-5',
256
+ id: 'HC-4',
305
257
  name: 'INDEX.md matches context/memory/ files',
306
258
  status: 'fail',
307
259
  message: 'context/memory/INDEX.md missing',
@@ -316,7 +268,7 @@ function hc5IndexConsistency({ projectRoot }) {
316
268
  );
317
269
  } catch (err) {
318
270
  return {
319
- id: 'HC-5',
271
+ id: 'HC-4',
320
272
  name: 'INDEX.md matches context/memory/ files',
321
273
  status: 'fail',
322
274
  message: `readdir error: ${err?.message ?? err}`,
@@ -330,7 +282,7 @@ function hc5IndexConsistency({ projectRoot }) {
330
282
  indexText = readFileSync(indexPath, 'utf8');
331
283
  } catch (err) {
332
284
  return {
333
- id: 'HC-5',
285
+ id: 'HC-4',
334
286
  name: 'INDEX.md matches context/memory/ files',
335
287
  status: 'fail',
336
288
  message: `INDEX.md read error: ${err?.message ?? err}`,
@@ -345,7 +297,7 @@ function hc5IndexConsistency({ projectRoot }) {
345
297
  // Two false-positives this must avoid (both real):
346
298
  // 1. id-shaped names — the pre-Task-85 regex matched `[PUL]-XXXXXXXX.md`,
347
299
  // which the kit NEVER generates, so HC-5 false-FAILED "missing" on every
348
- // real fact the moment one existed (lior-test-7 2026-06-03).
300
+ // real fact the moment one existed (live-test-7 2026-06-03).
349
301
  // 2. non-fact links — a broad `](...md)` match also catches the scaffold's
350
302
  // own example `- [type] [Title](filename.md)` (inside an HTML comment) and
351
303
  // any prose link like `(design.md)`, which would false-FAIL "stale" on a
@@ -365,7 +317,7 @@ function hc5IndexConsistency({ projectRoot }) {
365
317
  const inIndexNotFacts = [...indexEntries].filter((f) => !factSet.has(f));
366
318
  if (inFactsNotIndex.length === 0 && inIndexNotFacts.length === 0) {
367
319
  return {
368
- id: 'HC-5',
320
+ id: 'HC-4',
369
321
  name: 'INDEX.md matches context/memory/ files',
370
322
  status: 'pass',
371
323
  message: `${factFiles.length} fact file(s); INDEX in sync`,
@@ -375,7 +327,7 @@ function hc5IndexConsistency({ projectRoot }) {
375
327
  if (inFactsNotIndex.length > 0) parts.push(`missing from INDEX: ${inFactsNotIndex.length}`);
376
328
  if (inIndexNotFacts.length > 0) parts.push(`stale in INDEX: ${inIndexNotFacts.length}`);
377
329
  return {
378
- id: 'HC-5',
330
+ id: 'HC-4',
379
331
  name: 'INDEX.md matches context/memory/ files',
380
332
  status: 'fail',
381
333
  message: parts.join('; '),
@@ -383,11 +335,11 @@ function hc5IndexConsistency({ projectRoot }) {
383
335
  };
384
336
  }
385
337
 
386
- // --- HC-6: Cron jobs registered with host scheduler -------------------
387
- function hc6CronRegistered({ projectRoot }) {
338
+ // --- HC-5: Cron jobs registered with host scheduler -------------------
339
+ function hc5CronRegistered({ projectRoot }) {
388
340
  if (existsSync(cronSentinelPath(projectRoot))) {
389
341
  return {
390
- id: 'HC-6',
342
+ id: 'HC-5',
391
343
  name: 'Cron jobs registered with host scheduler',
392
344
  status: 'pass',
393
345
  message: 'cron-registered sentinel present',
@@ -398,38 +350,15 @@ function hc6CronRegistered({ projectRoot }) {
398
350
  // SKIP, not a FAIL — flagging an optional, working-by-fallback feature as a
399
351
  // failure made a healthy fresh install read as broken.
400
352
  return {
401
- id: 'HC-6',
353
+ id: 'HC-5',
402
354
  name: 'Cron jobs registered with host scheduler',
403
355
  status: 'skip',
404
356
  message: 'cron not registered (optional) — using the lazy-on-read fallback (compresses at SessionStart). Run `cmk register-crons` for scheduled background compression.',
405
357
  };
406
358
  }
407
359
 
408
- // --- HC-7: memsearch backend reachable --------------------------------
409
- function hc7MemsearchReachable(hc1Result) {
410
- // Only relevant if HC-1 passed. Skip when memsearch isn't installed.
411
- if (hc1Result.status !== 'pass') {
412
- return {
413
- id: 'HC-7',
414
- name: 'memsearch backend reachable',
415
- status: 'skip',
416
- message: 'depends on HC-1 (memsearch installed) — skipped',
417
- };
418
- }
419
- // HC-1 already proves memsearch --version succeeds. For HC-7 the
420
- // additional check would be milvus reachability — out of scope for
421
- // v0.1.0's keyword-only ship (Layer 5b is v0.1.x). Treat HC-7 as
422
- // pass when HC-1 passes.
423
- return {
424
- id: 'HC-7',
425
- name: 'memsearch backend reachable',
426
- status: 'pass',
427
- message: 'memsearch responds to --version (milvus reachability is Layer 5b / v0.1.x)',
428
- };
429
- }
430
-
431
- // --- HC-8: Native Anthropic Auto Memory status -----------------------
432
- function hc8NativeAutoMemory({ projectRoot, now }) {
360
+ // --- HC-6: Native Anthropic Auto Memory status -----------------------
361
+ function hc6NativeAutoMemory({ projectRoot, now }) {
433
362
  // Per ADR-0011 — detect whether Anthropic's native Auto Memory is
434
363
  // also active for this project. Non-fatal; informational. Log the
435
364
  // result to context/.locks/native-memory-status.log so users can
@@ -507,19 +436,19 @@ function hc8NativeAutoMemory({ projectRoot, now }) {
507
436
  }
508
437
 
509
438
  return {
510
- id: 'HC-8',
439
+ id: 'HC-6',
511
440
  name: 'Native Anthropic Auto Memory status detected',
512
441
  status: 'pass',
513
442
  message,
514
443
  };
515
444
  }
516
445
 
517
- // --- HC-9: Stale lock files -------------------------------------------
518
- function hc9StaleLocks({ projectRoot, userDir }) {
446
+ // --- HC-7: Stale lock files -------------------------------------------
447
+ function hc7StaleLocks({ projectRoot, userDir }) {
519
448
  const stale = detectStaleLocks(projectRoot, { userDir }).filter((r) => r.stale);
520
449
  if (stale.length === 0) {
521
450
  return {
522
- id: 'HC-9',
451
+ id: 'HC-7',
523
452
  name: 'No stale lock files',
524
453
  status: 'pass',
525
454
  message: 'all locks healthy',
@@ -533,7 +462,7 @@ function hc9StaleLocks({ projectRoot, userDir }) {
533
462
  ? ` (+ ${stale.length - 1} more — re-run after cleaning to surface)`
534
463
  : '';
535
464
  return {
536
- id: 'HC-9',
465
+ id: 'HC-7',
537
466
  name: 'No stale lock files',
538
467
  status: 'fail',
539
468
  message: `${stale.length} stale lock(s); first: ${first.path} (${first.reason})${moreNote}`,
@@ -542,7 +471,7 @@ function hc9StaleLocks({ projectRoot, userDir }) {
542
471
  }
543
472
 
544
473
  /**
545
- * Run the full 9-check health audit.
474
+ * Run the full 7-check health audit.
546
475
  *
547
476
  * @param {object} opts
548
477
  * @param {string} opts.projectRoot
@@ -573,20 +502,18 @@ export async function runDoctor({
573
502
  const ts = now ?? nowIso();
574
503
  const resolvedUserDir = userDir ?? join(homedir(), '.claude-memory-kit');
575
504
 
576
- // Run in order. HC-7 depends on HC-1's verdict.
577
- const c1 = await hc1Memsearch();
578
- const c2 = hc2Hooks({ projectRoot });
579
- const c3 = hc3DistillFreshness({ projectRoot, now: ts });
580
- const c4 = hc4Transcripts({ projectRoot, now: ts });
581
- const c5 = hc5IndexConsistency({ projectRoot });
582
- const c6 = hc6CronRegistered({ projectRoot });
583
- const c7 = hc7MemsearchReachable(c1);
584
- const c8 = hc8NativeAutoMemory({ projectRoot, now: ts });
585
- const c9 = hc9StaleLocks({ projectRoot, userDir: resolvedUserDir });
505
+ // Run all checks in order.
506
+ const c1 = hc1Hooks({ projectRoot });
507
+ const c2 = hc2DistillFreshness({ projectRoot, now: ts });
508
+ const c3 = hc3Transcripts({ projectRoot, now: ts });
509
+ const c4 = hc4IndexConsistency({ projectRoot });
510
+ const c5 = hc5CronRegistered({ projectRoot });
511
+ const c6 = hc6NativeAutoMemory({ projectRoot, now: ts });
512
+ const c7 = hc7StaleLocks({ projectRoot, userDir: resolvedUserDir });
586
513
 
587
514
  return {
588
515
  action: 'completed',
589
- checks: [c1, c2, c3, c4, c5, c6, c7, c8, c9],
516
+ checks: [c1, c2, c3, c4, c5, c6, c7],
590
517
  duration_ms: Date.now() - t0,
591
518
  };
592
519
  }
package/src/forget.mjs CHANGED
@@ -27,6 +27,8 @@ import { parse, format } from './frontmatter.mjs';
27
27
  import { appendAuditEntry, nowIso, REASON_CODES } from './audit-log.mjs';
28
28
  import { ERROR_CATEGORIES, errorResult, notFoundResult } from './result-shapes.mjs';
29
29
  import { findBulletScratchpad } from './bullet-lookup.mjs';
30
+ import { openIndexDb } from './index-db.mjs';
31
+ import { reindexBoot } from './index-rebuild.mjs';
30
32
 
31
33
  // Layer-2 review: PR-1 rejected \n / \r / : in the `reason` field as a
32
34
  // minimum fix for the naive serializer (finding B2). PR-2's frontmatter.mjs
@@ -290,6 +292,32 @@ export function forget(opts = {}) {
290
292
  },
291
293
  });
292
294
 
295
+ // Task 110 (F-7 / D-84): reindex the project tier IN-BAND so the just-
296
+ // tombstoned fact stops surfacing in `cmk search` immediately — no manual
297
+ // `cmk reindex`, no forgotten fact resurfacing (D-85: the action completes
298
+ // automatically; the regular user runs no follow-up command). reindexBoot's
299
+ // orphan-prune drops the unlinked fact's index rows and re-reads the scrubbed
300
+ // scratchpads in one pass. Both `cmk forget` (CLI) and `mk_forget` (MCP) call
301
+ // this same forget(), so both surfaces get it. Best-effort: the fact is
302
+ // ALREADY tombstoned + scrubbed on disk, so an index error must not fail the
303
+ // forget — every index reader lazy-reindexes (also orphan-pruning) and self-
304
+ // heals on the next read. A pure user-tier forget (no projectRoot) has no
305
+ // project index to touch and skips this.
306
+ let reindexed = false;
307
+ if (projectRoot) {
308
+ try {
309
+ const db = openIndexDb({ projectRoot });
310
+ try {
311
+ reindexBoot({ projectRoot, userDir, db });
312
+ reindexed = true;
313
+ } finally {
314
+ db.close();
315
+ }
316
+ } catch {
317
+ // best-effort — the on-disk tombstone is authoritative; search self-heals.
318
+ }
319
+ }
320
+
293
321
  return {
294
322
  action: 'tombstoned',
295
323
  id: match.id,
@@ -297,6 +325,7 @@ export function forget(opts = {}) {
297
325
  originalPath: match.path,
298
326
  tombstonePath,
299
327
  scratchpadEdits,
328
+ reindexed,
300
329
  };
301
330
  }
302
331
 
@@ -403,10 +403,52 @@ export function reindexBoot({ projectRoot, userDir, db, now }) {
403
403
  observationsAffected += n;
404
404
  }
405
405
 
406
+ // Prune orphans (Task 110 / F-7). The walk above only ADDS/UPDATES files that
407
+ // still exist; a file removed since the last index (e.g. a fact `cmk forget`
408
+ // moved to archive/tombstones/, or a queue-discard) leaves its observation
409
+ // rows behind, so the forgotten fact keeps surfacing in `cmk search` until a
410
+ // manual `reindex --full`. Drop any `files` checkpoint whose source is no
411
+ // longer on disk, plus its observations (the FTS5 delete trigger fires per
412
+ // row). This makes boot a full sync (add/update/DELETE), so every index
413
+ // reader — all of which lazy-call reindexBoot first — self-heals after any
414
+ // removal with no manual command (the D-85 "everything automatic" contract).
415
+ //
416
+ // SAFETY (composition guard): the prune deletes any known row NOT in the
417
+ // current live-set, so it is only sound when the live-set is COMPLETE across
418
+ // every tier the index covers. The U tier is walked only when `userDir` is
419
+ // provided; without it, U sources are absent from `liveRelPaths` and a real
420
+ // U-tier row would be mis-pruned as an orphan. So we prune ONLY when userDir
421
+ // is present (P + L + U all walked). When it's absent we skip — the next
422
+ // reader that passes userDir (every `cmk search`/`get`/… does) self-heals.
423
+ // (projectRoot is always present here — it's required to open the db.)
424
+ let filesPruned = 0;
425
+ let observationsPruned = 0;
426
+ if (userDir) {
427
+ const liveRelPaths = new Set(
428
+ sources.map((s) => relativeSource(s.path, { projectRoot, userDir })),
429
+ );
430
+ const pruneTxn = db.transaction((relPath, obsCount) => {
431
+ db.prepare(DELETE_OBSERVATIONS_FOR_PATH_SQL).run(relPath);
432
+ db.prepare('DELETE FROM files WHERE path = ?').run(relPath);
433
+ filesPruned++;
434
+ observationsPruned += obsCount;
435
+ });
436
+ const knownPaths = db.prepare('SELECT path FROM files').all();
437
+ for (const { path: relPath } of knownPaths) {
438
+ if (liveRelPaths.has(relPath)) continue;
439
+ const obsCount = db
440
+ .prepare('SELECT COUNT(*) AS n FROM observations WHERE source_file = ?')
441
+ .get(relPath).n;
442
+ pruneTxn(relPath, obsCount);
443
+ }
444
+ }
445
+
406
446
  return {
407
447
  filesScanned,
408
448
  filesReindexed,
409
449
  observationsAffected,
450
+ filesPruned,
451
+ observationsPruned,
410
452
  durationMs: Date.now() - t0,
411
453
  skipped,
412
454
  };
package/src/install.mjs CHANGED
@@ -42,7 +42,7 @@ import { homedir } from 'node:os';
42
42
  import { basename, dirname, join, relative, resolve } from 'node:path';
43
43
  import { fileURLToPath } from 'node:url';
44
44
  import { injectClaudeMdBlock } from './claude-md.mjs';
45
- import { writeKitHooks } from './settings-hooks.mjs';
45
+ import { writeKitHooks, writeKitMcpServer } from './settings-hooks.mjs';
46
46
  import { appendAuditEntry, nowIso, REASON_CODES } from './audit-log.mjs';
47
47
 
48
48
  const __filename = fileURLToPath(import.meta.url);
@@ -360,6 +360,11 @@ export async function install(options = {}) {
360
360
  // hooks is a no-op. Opt out with {noHooks:true} (CLI: --no-hooks) for
361
361
  // scaffold-only installs.
362
362
  let hooks = { action: 'skipped', path: join(projectRoot, '.claude', 'settings.json') };
363
+ // Task 108b — register the kit's MCP server (.mcp.json) so the model can drive
364
+ // memory ops as allow-listed tools (the `mcp__cmk__*` rule writeKitHooks adds),
365
+ // not just `cmk` bash. Same {noHooks} opt-out as the hooks (it's Claude Code
366
+ // wiring). R2 / D-80 fix.
367
+ let mcpServer = { action: 'skipped', path: join(projectRoot, '.mcp.json') };
363
368
  if (!options.noHooks) {
364
369
  const settingsPath = join(projectRoot, '.claude', 'settings.json');
365
370
  const r = writeKitHooks(settingsPath);
@@ -396,7 +401,17 @@ export async function install(options = {}) {
396
401
  }
397
402
  }
398
403
 
399
- return { projectRoot, userTier, created, skipped, gitignore, claudeMd, hooks, errors };
404
+ if (!options.noHooks) {
405
+ const r = writeKitMcpServer(projectRoot);
406
+ if (r.error) {
407
+ errors.push({ path: r.path, error: r.error });
408
+ mcpServer = { action: 'error', path: r.path, error: r.error };
409
+ } else {
410
+ mcpServer = { action: r.changed ? 'registered' : 'unchanged', path: r.path };
411
+ }
412
+ }
413
+
414
+ return { projectRoot, userTier, created, skipped, gitignore, claudeMd, hooks, mcpServer, errors };
400
415
  }
401
416
 
402
417
  /**