claude-mem-lite 6.35.2 → 6.35.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.
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "claude-mem-lite",
12
- "version": "6.35.2",
12
+ "version": "6.35.4",
13
13
  "source": "./",
14
14
  "homepage": "https://github.com/sdsrss/claude-mem-lite",
15
15
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword 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)."
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "6.35.2",
3
+ "version": "6.35.4",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword 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
  "author": {
6
6
  "name": "sdsrss"
package/adopt-cli.mjs CHANGED
@@ -81,7 +81,7 @@ import {
81
81
  userInstructionFiles,
82
82
  steeringDetailDocPath,
83
83
  } from './lib/local-steering.mjs';
84
- import { pluginSettingsScopes } from './lib/plugin-key.mjs';
84
+ import { pluginSettingsScopes, readSettingsScope } from './lib/plugin-key.mjs';
85
85
  import { CLI_INVOKE } from './cli-path.mjs';
86
86
 
87
87
  /**
@@ -591,12 +591,9 @@ function worktreeMainCheckout(top) {
591
591
  function claudeMdExcludesSet(dirs) {
592
592
  const files = new Set(dirs.flatMap((d) => pluginSettingsScopes(claudeConfigDir(), d)));
593
593
  for (const f of files) {
594
- try {
595
- const v = JSON.parse(readFileSync(f, 'utf8'))?.claudeMdExcludes;
596
- if (Array.isArray(v) ? v.length > 0 : v !== undefined && v !== null) return true;
597
- } catch {
598
- /* absent or unparseable: sets nothing */
599
- }
594
+ // Absent, unparseable or not a regular file: sets nothing.
595
+ const v = readSettingsScope(f)?.claudeMdExcludes;
596
+ if (Array.isArray(v) ? v.length > 0 : v !== undefined && v !== null) return true;
600
597
  }
601
598
  return false;
602
599
  }
@@ -1081,10 +1078,15 @@ function unadoptProject(dir, dryRun) {
1081
1078
  if (r.action === 'removed') {
1082
1079
  log(`[unadopt --all] ${dir} → removed`);
1083
1080
  n.blocks++;
1081
+ } else if (r.action === 'skipped-symlink') {
1082
+ log(`[unadopt --all] ${dir} → skipped-symlink`);
1083
+ n.failures++;
1084
1084
  } else {
1085
1085
  log(`[unadopt --all] ${dir} → cleaned partial residue (detail doc/state, no block)`);
1086
1086
  n.partial++;
1087
1087
  }
1088
+ for (const l of r.left ?? []) log(` ⚠ left ${l.link} alone: ${l.why}`);
1089
+ if (r.action === 'skipped-symlink') log(` ⚠ ${BLOCK_LEFT_NOTE}`);
1088
1090
  // OUTSIDE the branch, because residue is orthogonal to what happened to the block: a
1089
1091
  // project can have its block removed AND still carry an unpaired sentinel. An orphan is
1090
1092
  // the one kind of residue the sweep cannot finish — its block has no end marker, so its
@@ -1095,6 +1097,11 @@ function unadoptProject(dir, dryRun) {
1095
1097
  return n;
1096
1098
  }
1097
1099
 
1100
+ // unadopt's line when CLAUDE.md is a link it will not write through: the block, the detail doc and its
1101
+ // state file all stay, and only the user can take the block out (v6.35.4 pre-tag round 1, F5).
1102
+ const BLOCK_LEFT_NOTE =
1103
+ 'the block stays in the file CLAUDE.md links to, and the detail doc and its state file stay too: remove the block from that file by hand, then run unadopt again';
1104
+
1098
1105
  export function cmdUnadopt(args = []) {
1099
1106
  if (hasFlag(args, '--status')) return statusAll();
1100
1107
 
@@ -1129,6 +1136,11 @@ export function cmdUnadopt(args = []) {
1129
1136
  const mig = migrateLegacyMemoryDir(cwd, PLUGIN_SLUG, { force });
1130
1137
  const migNote = mig.action === 'removed' ? ' (+cleaned legacy memdir)' : '';
1131
1138
  log(`[unadopt] ${cwd} → ${r.action}${migNote}`);
1139
+ for (const l of r.left ?? []) log(` ⚠ left ${l.link} alone: ${l.why}`);
1140
+ if (r.action === 'skipped-symlink') {
1141
+ log(` ⚠ ${BLOCK_LEFT_NOTE}`);
1142
+ process.exitCode = 1;
1143
+ }
1132
1144
  const local = dropLocalSteering(cwd);
1133
1145
  if (local.action !== 'absent') log(`[unadopt] ${local.path} → ${local.action}`);
1134
1146
  if (local.residue) log(` ⚠ ${local.residue}`);
package/claudemd.mjs CHANGED
@@ -15,21 +15,10 @@
15
15
  //
16
16
  // See docs/CLAUDE-MD-STEERING-PLAN.md for rationale + migration.
17
17
 
18
- import {
19
- readFileSync,
20
- existsSync,
21
- unlinkSync,
22
- mkdirSync,
23
- rmdirSync,
24
- readdirSync,
25
- lstatSync,
26
- openSync,
27
- fstatSync,
28
- closeSync,
29
- readSync,
30
- constants as fsConstants,
31
- } from 'fs';
18
+ import { existsSync, unlinkSync, mkdirSync, rmdirSync, readdirSync, lstatSync, statSync } from 'fs';
32
19
  import { atomicWriteFileSync as atomicWrite } from './lib/atomic-write.mjs';
20
+ import { readRegularText, readRegularTextOrThrow } from './lib/regular-file.mjs';
21
+ import { linkRefusal, refusalText } from './lib/project-link.mjs';
33
22
  import { join, basename } from 'path';
34
23
  import { createHash } from 'crypto';
35
24
  import { memdirPath, removePluginSection, removePluginDoc, isAdopted as memdirIsAdopted } from './memdir.mjs';
@@ -46,11 +35,26 @@ export function claudeMdPath(cwd) {
46
35
  function dotClaudeDir(cwd) {
47
36
  return join(cwd, '.claude');
48
37
  }
38
+ const docRel = (slug) => `.claude/plugin_${slugSnake(slug)}.md`;
39
+ const stateRel = (slug) => `.claude/.plugin_${slugSnake(slug)}_state.json`;
49
40
  export function detailDocPath(cwd, slug) {
50
- return join(dotClaudeDir(cwd), `plugin_${slugSnake(slug)}.md`);
41
+ return join(cwd, docRel(slug));
51
42
  }
52
43
  function stateFilePath(cwd, slug) {
53
- return join(dotClaudeDir(cwd), `.plugin_${slugSnake(slug)}_state.json`);
44
+ return join(cwd, stateRel(slug));
45
+ }
46
+
47
+ // The three files adopt writes, each with whether the plugin writes it whole (lib/project-link.mjs).
48
+ const managedTargets = (slug) => [
49
+ ['CLAUDE.md', false],
50
+ [docRel(slug), true],
51
+ [stateRel(slug), true],
52
+ ];
53
+
54
+ // Throws the first refusal: a link on the way to `rel` that the plugin must not write through.
55
+ function assertWritable(cwd, rel, whole) {
56
+ const r = linkRefusal(cwd, rel, { whole });
57
+ if (r) throw new Error(refusalText(r));
54
58
  }
55
59
 
56
60
  // First line of the detail doc — an invisible (in rendered markdown) marker that
@@ -129,7 +133,8 @@ function orphanSentinelCount(raw, slug) {
129
133
  export function straySentinelLines(p, slug) {
130
134
  let raw;
131
135
  try {
132
- raw = readFileSync(p, 'utf8');
136
+ // Not a regular file, or over the limit: Claude Code does not load it, so nothing in it is.
137
+ raw = readRegularTextOrThrow(p);
133
138
  } catch {
134
139
  return [];
135
140
  }
@@ -230,8 +235,9 @@ export function holdsOnlyPluginLines(p, slug) {
230
235
  * @returns {'added'|'present'}
231
236
  */
232
237
  export function addAgentsImports(cwd, slug, imports) {
238
+ assertWritable(cwd, 'CLAUDE.md', false);
233
239
  const p = claudeMdPath(cwd);
234
- const raw = existsSync(p) ? readFileSync(p, 'utf8') : '';
240
+ const raw = existsSync(p) ? readRegularTextOrThrow(p) : '';
235
241
  const marker = agentsImportMarker(slug);
236
242
  if (raw.includes(marker)) return 'present';
237
243
  const lines = `${marker}\n${imports.map((i) => `@${i}`).join('\n')}\n`;
@@ -281,39 +287,11 @@ export function readBlock(cwd, slug) {
281
287
  return readBlockAt(claudeMdPath(cwd), slug);
282
288
  }
283
289
 
284
- // Claude Code 2.1.322 skips an instruction file that is "not a regular file or exceeds 4194304 byte
285
- // limit" (its own message).
286
- const INSTRUCTION_FILE_MAX_BYTES = 4194304;
287
-
288
- // A regular file's text, or null for one Claude Code would not load: a FIFO or a device, or over its
289
- // size limit. The session sync reads instruction files in every directory above the project
290
- // (D#509(4)), /tmp among them, where any local user can put a FIFO (a blocking read stalled
291
- // SessionStart, v6.32.0 pre-release defects review F1) or a huge file (read whole, it filled memory,
292
- // delta review R2-1). Opened non-blocking and checked on the descriptor, so a file swapped in after
293
- // the check is not the one read. The size fstat reports is no bound — a /proc file reports 0 and
294
- // never ends, and a file can grow — so at most one byte past the limit is read, as Claude Code's own
295
- // bounded read does (round-3 review F1). A directory still throws EISDIR, as a plain read did.
296
- function readRegularText(p) {
297
- const fd = openSync(p, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
298
- try {
299
- const st = fstatSync(fd);
300
- if (st.isDirectory()) throw Object.assign(new Error(`${p}: is a directory`), { code: 'EISDIR' });
301
- if (!st.isFile() || st.size > INSTRUCTION_FILE_MAX_BYTES) return null;
302
- const chunks = [];
303
- let total = 0;
304
- for (;;) {
305
- const chunk = Buffer.allocUnsafe(65536);
306
- const n = readSync(fd, chunk, 0, chunk.length, null);
307
- if (n === 0) break;
308
- total += n;
309
- if (total > INSTRUCTION_FILE_MAX_BYTES) return null;
310
- chunks.push(chunk.subarray(0, n));
311
- }
312
- return Buffer.concat(chunks, total).toString('utf8');
313
- } finally {
314
- closeSync(fd);
315
- }
316
- }
290
+ // Every read of an instruction file in this module goes through lib/regular-file.mjs: null (or a
291
+ // throw) for a FIFO, a device or a file over Claude Code's 4194304-byte limit. The session sync
292
+ // reads instruction files in every directory above the project (D#509(4)), /tmp among them, where
293
+ // any local user can put a FIFO (v6.32.0 pre-release defects review F1) or a huge file (delta
294
+ // review R2-1); inside the project a repository can commit a symlink to a device.
317
295
 
318
296
  /**
319
297
  * readBlock for any instructions file — CLAUDE.md, or the CLAUDE.local.md that auto-adopt
@@ -361,7 +339,7 @@ export function isOwnAdoptionArtifact(cwd, relPath, slug) {
361
339
  const ownFile = (name) =>
362
340
  name === stateName ||
363
341
  (name === docName &&
364
- readFileSync(join(dotClaudeDir(cwd), name), 'utf8').startsWith(managedByMarker(slug)));
342
+ readRegularTextOrThrow(join(dotClaudeDir(cwd), name)).startsWith(managedByMarker(slug)));
365
343
  if (rel === '.claude') {
366
344
  const names = readdirSync(dotClaudeDir(cwd));
367
345
  return names.length > 0 && names.every(ownFile);
@@ -446,6 +424,11 @@ export function needsRefresh(cwd, { slug, version, block, doc }) {
446
424
  * (block disposition, and the detail doc's)
447
425
  */
448
426
  export function writeManaged(cwd, { slug, version, block, doc }) {
427
+ // The shared writer writes THROUGH a link (for a dotfiles-managed CLAUDE.md), and a cloned
428
+ // repository can commit links: one as the doc or the state, as `.claude`, or as CLAUDE.md had this
429
+ // write outside the project (D#880). All three are checked before anything is written, so a
430
+ // refusal leaves CLAUDE.md as it was too.
431
+ for (const [rel, whole] of managedTargets(slug)) assertWritable(cwd, rel, whole);
449
432
  const { action } = writeBlockAt(claudeMdPath(cwd), { slug, version, block });
450
433
 
451
434
  // Detail doc (marker on first line so unadopt/refresh can tell it apart from a
@@ -454,7 +437,7 @@ export function writeManaged(cwd, { slug, version, block, doc }) {
454
437
  const dp = detailDocPath(cwd, slug);
455
438
  const dir = dotClaudeDir(cwd);
456
439
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
457
- const existingDoc = existsSync(dp) ? readFileSync(dp, 'utf8') : null;
440
+ const existingDoc = existsSync(dp) ? readRegularTextOrThrow(dp) : null;
458
441
  if (existingDoc !== docContent) atomicWrite(dp, docContent);
459
442
  const docAction = existingDoc === null ? 'created' : existingDoc === docContent ? 'unchanged' : 'updated';
460
443
 
@@ -465,7 +448,7 @@ export function writeManaged(cwd, { slug, version, block, doc }) {
465
448
  const docHash = sha256(doc);
466
449
  let prev = null;
467
450
  try {
468
- prev = JSON.parse(readFileSync(stateFilePath(cwd, slug), 'utf8'));
451
+ prev = JSON.parse(readRegularTextOrThrow(stateFilePath(cwd, slug)));
469
452
  } catch {
470
453
  /* absent or unreadable: write it */
471
454
  }
@@ -483,7 +466,8 @@ export function writeManaged(cwd, { slug, version, block, doc }) {
483
466
  * @returns {{action: 'created'|'updated'|'unchanged'}}
484
467
  */
485
468
  export function writeBlockAt(p, { slug, version, block }) {
486
- const raw = existsSync(p) ? readFileSync(p, 'utf8') : '';
469
+ // Throws for a FIFO, a device or an over-limit file: nothing is written over it.
470
+ const raw = existsSync(p) ? readRegularTextOrThrow(p) : '';
487
471
  const section = renderBlock(slug, version, block);
488
472
  const m = raw.match(blockRegex(slug));
489
473
 
@@ -531,10 +515,32 @@ export function writeBlockAt(p, { slug, version, block }) {
531
515
  * (that is the defect, not a detail), and guessing a span in a file we do not own is how the
532
516
  * adopt side came to delete a user's runbook. Report, do not repair.
533
517
  *
534
- * @returns {{action: 'removed'|'partial'|'absent', residue?: string}}
518
+ * A file reached through a link the plugin must not write through (lib/project-link.mjs) is left as
519
+ * it is, and named in `left`: a cloned repository's committed `.claude` link had unadopt delete two
520
+ * files in the directory it picked (D#880). `skipped-symlink` = CLAUDE.md was such a file; the doc
521
+ * and the state then stay too.
522
+ *
523
+ * @returns {{action: 'removed'|'partial'|'absent'|'skipped-symlink', residue?: string,
524
+ * left?: {link: string, why: string}[]}}
535
525
  */
536
526
  export function removeManaged(cwd, slug) {
537
- const { action, orphans } = removeBlockAt(claudeMdPath(cwd), slug);
527
+ const left = [];
528
+ // A CLAUDE.md the plugin will not write through is left alone only while the block is in it (read
529
+ // with a bound, never written): once the user has taken the block out by hand, the rest goes.
530
+ const mdRefusal = linkRefusal(cwd, 'CLAUDE.md');
531
+ const mdLeft = mdRefusal !== null && readBlockAt(claudeMdPath(cwd), slug).body !== null;
532
+ if (mdLeft) left.push(mdRefusal);
533
+ const { action, orphans } = mdLeft
534
+ ? { action: 'skipped-symlink', orphans: 0 }
535
+ : mdRefusal
536
+ ? { action: 'absent', orphans: 0 }
537
+ : removeBlockAt(claudeMdPath(cwd), slug);
538
+ // The doc and the state go only with the block: a block left behind a link still points at the
539
+ // doc (v6.35.4 pre-tag round 1, F5). Deleting either one is unlinkSync, which removes a link
540
+ // itself, not what it names; what can lead it out of the project is a `.claude` link.
541
+ const dirRefusal = linkRefusal(cwd, '.claude');
542
+ if (dirRefusal) left.push(dirRefusal);
543
+ const keep = dirRefusal !== null || mdLeft;
538
544
  // Captured BEFORE the deletions below, because they are what it asks about: is there any
539
545
  // evidence the plugin ever wrote in this project? An unpaired sentinel is NOT such
540
546
  // evidence — it is text, and a project that merely documents the marker in prose has one
@@ -542,13 +548,13 @@ export function removeManaged(cwd, slug) {
542
548
  // own paragraph, on a project this tool has never touched.
543
549
  const dp = detailDocPath(cwd, slug);
544
550
  const wasOurs = action === 'removed' || existsSync(dp) || existsSync(stateFilePath(cwd, slug));
545
- if (existsSync(dp))
551
+ if (!keep && existsSync(dp))
546
552
  try {
547
553
  unlinkSync(dp);
548
554
  } catch {
549
555
  /* best-effort */
550
556
  }
551
- clearState(cwd, slug);
557
+ if (!keep) clearState(cwd, slug);
552
558
  // Drop an emptied .claude/ so unadopt leaves no trace (skips if it holds
553
559
  // anything else — e.g. settings.local.json).
554
560
  try {
@@ -564,9 +570,10 @@ export function removeManaged(cwd, slug) {
564
570
  // `partial++`, so a sweep that DID remove a block reported "no block" and tallied zero
565
571
  // removals. Two facts, two fields.
566
572
  const residue = orphans > 0 && wasOurs ? orphanResidueNote(orphans, slug, claudeMdPath(cwd)) : null;
567
- if (action === 'removed') return residue ? { action, residue } : { action };
568
- if (residue) return { action: 'partial', residue };
569
- return { action };
573
+ const leftField = left.length > 0 ? { left } : {};
574
+ if (action === 'removed') return residue ? { action, residue, ...leftField } : { action, ...leftField };
575
+ if (residue) return { action: 'partial', residue, ...leftField };
576
+ return { action, ...leftField };
570
577
  }
571
578
 
572
579
  /**
@@ -577,6 +584,18 @@ export function orphanResidueNote(orphans, slug, p) {
577
584
  return `${orphans} unpaired \`${slug}\` sentinel line(s) remain in ${p} — the block they opened has no matching end marker, so its extent cannot be determined safely. Remove those lines and the text they wrap by hand.`;
578
585
  }
579
586
 
587
+ // readRegularText's limit for removing our block: its default (Claude Code's 4194304-byte limit)
588
+ // unless `p` reports a larger size, then that size. A device, a FIFO and /proc/self/pagemap
589
+ // report 0 and keep the default (readRegularText reads neither of the first two).
590
+ function regularFileLimit(p) {
591
+ try {
592
+ const st = statSync(p);
593
+ return st.size > 4194304 ? st.size : undefined;
594
+ } catch {
595
+ return undefined;
596
+ }
597
+ }
598
+
580
599
  /**
581
600
  * Remove every well-formed block of `slug` from one instructions file, keeping all other
582
601
  * text; a file left holding only whitespace is deleted (a symlink is emptied through the
@@ -588,8 +607,12 @@ export function orphanResidueNote(orphans, slug, p) {
588
607
  export function removeBlockAt(p, slug) {
589
608
  let action = 'absent';
590
609
  let orphans = 0;
591
- if (existsSync(p)) {
592
- let raw = readFileSync(p, 'utf8');
610
+ // A FIFO or a device is not read and holds no block: a repository can commit
611
+ // `CLAUDE.md -> /dev/zero`. A regular file is read whatever its size, as before: Claude Code
612
+ // does not load one over 4 MiB, but the block the user asked to remove still comes out.
613
+ const found = existsSync(p) ? readRegularText(p, regularFileLimit(p)) : null;
614
+ if (found !== null) {
615
+ let raw = found;
593
616
  // H2: loop so ALL same-slug blocks are removed, not just the first (a
594
617
  // duplicate/CRLF-orphaned copy must not survive unadopt).
595
618
  let m;
package/hook-context.mjs CHANGED
@@ -6,8 +6,10 @@
6
6
  // Handles adaptive time windows, token-budgeted selection, and legacy CLAUDE.md cleanup.
7
7
 
8
8
  import { basename, join } from 'path';
9
- import { existsSync, readFileSync, writeFileSync } from 'fs';
9
+ import { existsSync, writeFileSync } from 'fs';
10
10
  import { atomicWriteFileSync } from './lib/atomic-write.mjs';
11
+ import { linkRefusal, refusalText } from './lib/project-link.mjs';
12
+ import { readRegularTextOrThrow } from './lib/regular-file.mjs';
11
13
  import {
12
14
  estimateTokens,
13
15
  truncate,
@@ -422,7 +424,8 @@ export function cleanupClaudeMdLegacyBlock() {
422
424
  const claudeMdPath = join(inferProjectDir(), 'CLAUDE.md');
423
425
  let content;
424
426
  try {
425
- content = readFileSync(claudeMdPath, 'utf8');
427
+ // Bounded: a repository can commit `CLAUDE.md -> /dev/zero`; such a file is treated as missing.
428
+ content = readRegularTextOrThrow(claudeMdPath);
426
429
  } catch {
427
430
  // CLAUDE.md missing — still drop the marker so we don't re-stat every session
428
431
  try {
@@ -479,8 +482,11 @@ export function cleanupClaudeMdLegacyBlock() {
479
482
  }
480
483
  }
481
484
 
482
- // Swallow a single preceding newline to avoid leaving a blank-line gap behind.
483
- if (removeStart > 0 && content[removeStart - 1] === '\n') removeStart -= 1;
485
+ // A span at the end of the file has no newline after it: take the one before it instead. Never
486
+ // both — that joined the lines around the span (`keep this` + `trailing` → `keep thistrailing`,
487
+ // v6.35.3 pre-tag round 2, O1).
488
+ if (removeEnd === endIdx + endTag.length && removeStart > 0 && content[removeStart - 1] === '\n')
489
+ removeStart -= 1;
484
490
 
485
491
  const cleaned = content.slice(0, removeStart) + content.slice(removeEnd);
486
492
  // Collapse any ≥3 consecutive newlines to two, then ensure exactly one trailing newline.
@@ -491,6 +497,15 @@ export function cleanupClaudeMdLegacyBlock() {
491
497
  return;
492
498
  }
493
499
 
500
+ // Not through a CLAUDE.md link the repository may have committed: it rewrote the outside file
501
+ // it names, with auto-adopt off too (D#880). Marked done, as a file without a block is.
502
+ const refusal = linkRefusal(inferProjectDir(), 'CLAUDE.md');
503
+ if (refusal) {
504
+ debugLog('WARN', 'cleanupClaudeMdLegacyBlock', refusalText(refusal));
505
+ dropMarker();
506
+ return;
507
+ }
508
+
494
509
  // atomicWriteFileSync keeps the per-pid temp (two concurrent first-run SessionStarts in
495
510
  // one project must not rename each other's half-written temp onto the user's tracked
496
511
  // CLAUDE.md) AND adds the lstat the local twin lacked: renaming onto a symlink NAME
package/hook.mjs CHANGED
@@ -53,7 +53,7 @@ import {
53
53
  // their canonical module.
54
54
  import { inferProjectDir } from './project-utils.mjs';
55
55
  import { extractFileTargets } from './bash-utils.mjs';
56
- import { isPluginDisabledInScopes, pluginSettingsScopes } from './lib/plugin-key.mjs';
56
+ import { isPluginDisabledInScopes, pluginSettingsScopes, readSettingsScope } from './lib/plugin-key.mjs';
57
57
  import { readHookStdin, salvageTruncatedHookEvent, TOOL_INPUT_FILE_MAX_BYTES } from './lib/hook-stdin.mjs';
58
58
  // Aliased: `acquireLock` from hook-episode.mjs below is the episode buffer's own
59
59
  // (argument-less) lock — a different mutex with a different staleness policy.
@@ -306,21 +306,13 @@ else if (event === 'session-start') setHookDbDeadline(performance.timeOrigin + S
306
306
  // in Claude UI does not automatically remove them. Exit early to make disable actually work.
307
307
  // The KEY and the predicate live in lib/plugin-key.mjs (P2-7) — install.mjs branches on the
308
308
  // same decision, and a key that drifts on one side leaves the user with a plugin they
309
- // switched off and a settings.json hook set that never noticed. Reading the file stays here:
310
- // install.mjs already holds a parsed settings object when it asks, this process does not.
309
+ // switched off and a settings.json hook set that never noticed.
311
310
  // The user, project and local scopes are merged as the host merges them (lib/plugin-key.mjs).
311
+ // A missing, unparseable or non-regular scope sets nothing. Fail OPEN: a corrupt file must not
312
+ // switch the plugin off for a user who never asked for that.
312
313
  function pluginDisabledHere() {
313
- const read = (path) => {
314
- try {
315
- return JSON.parse(readFileSync(path, 'utf8'));
316
- } catch {
317
- // Missing or unparseable → sets nothing. Fail OPEN: a corrupt file must not switch the
318
- // plugin off for a user who never asked for that.
319
- return null;
320
- }
321
- };
322
314
  const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
323
- return isPluginDisabledInScopes(pluginSettingsScopes(claudeConfigDir(), projectDir).map(read));
315
+ return isPluginDisabledInScopes(pluginSettingsScopes(claudeConfigDir(), projectDir).map(readSettingsScope));
324
316
  }
325
317
 
326
318
  if (event && pluginDisabledHere()) process.exit(0);
package/install.mjs CHANGED
@@ -77,6 +77,18 @@ import {
77
77
  isPluginExplicitlyDisabled,
78
78
  pluginSettingsScopes,
79
79
  } from './lib/plugin-key.mjs';
80
+ // A namespace, as for lib/proc-lock.mjs below: readSettingsScope is newer than v6.35.2 and this file
81
+ // is the repair path. Without it, the plain read that release used.
82
+ import * as pluginKeyModule from './lib/plugin-key.mjs';
83
+ const readSettingsScope =
84
+ pluginKeyModule.readSettingsScope ??
85
+ ((p) => {
86
+ try {
87
+ return JSON.parse(readFileSync(p, 'utf8'));
88
+ } catch {
89
+ return null;
90
+ }
91
+ });
80
92
  import { isNpxRun } from './lib/npx-run.mjs';
81
93
  import { doctorDbModeHint } from './lib/doctor-modes.mjs';
82
94
  // Static, matching doctor-modes above. Safe here where it would not be for a heavier
@@ -896,7 +908,8 @@ function noteForeignMem(foreignMem) {
896
908
  export function projectScopedMemRegistrations(cwd) {
897
909
  const file = join(cwd, '.mcp.json');
898
910
  try {
899
- const servers = JSON.parse(readFileSync(file, 'utf8'))?.mcpServers;
911
+ // Bounded like a settings scope: a repository can commit `.mcp.json -> /dev/zero`.
912
+ const servers = readSettingsScope(file)?.mcpServers;
900
913
  // Array.isArray is load-bearing: `typeof [] === 'object'`, so without it an array
901
914
  // falls through to the membership filter and the guard cannot fire on its own
902
915
  // named input — which is how the test case for it was passing.
@@ -1745,12 +1758,9 @@ function projectPluginOverride(userSettings) {
1745
1758
  const userValue = userSettings?.enabledPlugins?.[PLUGIN_KEY];
1746
1759
  let found = null;
1747
1760
  for (const file of pluginSettingsScopes(claudeConfigDir(), projectDir).slice(1)) {
1748
- try {
1749
- const v = JSON.parse(readFileSync(file, 'utf8'))?.enabledPlugins?.[PLUGIN_KEY];
1750
- if (typeof v === 'boolean') found = { enabled: v, file };
1751
- } catch {
1752
- /* missing or unparseable: sets nothing */
1753
- }
1761
+ // Missing, unparseable or not a regular file: sets nothing.
1762
+ const v = readSettingsScope(file)?.enabledPlugins?.[PLUGIN_KEY];
1763
+ if (typeof v === 'boolean') found = { enabled: v, file };
1754
1764
  }
1755
1765
  if (!found) return null;
1756
1766
  // The user scope's effective reading: an absent key is enabled unless set false.
@@ -4899,8 +4909,17 @@ async function rebuildBinding() {
4899
4909
  if (failed > 0) {
4900
4910
  process.exitCode = 1;
4901
4911
  } else {
4902
- // Every tree is loadable → drop the marker so session-start stops retrying.
4912
+ // Every tree is loadable → drop the marker so session-start stops retrying, and the CLI's
4913
+ // cooldown (D#311) so a later, unrelated break heals on the next command. The name is
4914
+ // binding-probe's CLI_HEAL_MARKER written out, not imported: 6.35.2's lib lacks that export,
4915
+ // and a named import of it would stop this recovery path loading over a half-swapped tree.
4916
+ // tests/native-binding-selfheal.test.mjs runs rebuild-binding against the constant.
4903
4917
  clearNativeBindingBreakage(MEM_RUNTIME_DIR);
4918
+ try {
4919
+ unlinkSync(join(MEM_RUNTIME_DIR, 'native-binding-cli-lastheal'));
4920
+ } catch {
4921
+ /* none armed */
4922
+ }
4904
4923
  }
4905
4924
  } finally {
4906
4925
  release();
@@ -7,10 +7,11 @@
7
7
  // sufficient — the binding can be present-but-stale after a Node upgrade.
8
8
 
9
9
  import { execSync, spawnSync } from 'node:child_process';
10
- import { existsSync, renameSync } from 'node:fs';
10
+ import { existsSync, readFileSync, renameSync, unlinkSync } from 'node:fs';
11
11
  import { createRequire } from 'node:module';
12
12
  import { join } from 'node:path';
13
13
  import { shellWord } from '../cli-path.mjs';
14
+ import { atomicWriteFileSync } from './atomic-write.mjs';
14
15
 
15
16
  // npm >= 12 blocks lifecycle scripts by default, so a plain `npm rebuild` exits 0
16
17
  // WITHOUT compiling — see the rebuild() comment below. Step 1 of the heal chain, and
@@ -33,6 +34,9 @@ export const NATIVE_BINDING_REBUILD_CMD = 'npm rebuild better-sqlite3 --dangerou
33
34
  // nothing → this command produces build/Release/better_sqlite3.node and the DB opens.
34
35
  export const NATIVE_BINDING_SOURCE_BUILD_CMD = 'npm run --prefix node_modules/better-sqlite3 build-release';
35
36
 
37
+ /** Cap on each npm step of the default rebuild; the source build has none (D#859). */
38
+ const NPM_STEP_TIMEOUT_MS = 240_000;
39
+
36
40
  /**
37
41
  * The one-liner a HUMAN should be given to repair the binding under `root`.
38
42
  *
@@ -285,11 +289,14 @@ export async function ensureBetterSqlite3Working(installDir, deps = {}) {
285
289
  // existing semantics.
286
290
  const probe = deps.probe || (() => probeBindingInFreshProcess(installDir));
287
291
  const verify = deps.verify || deps.probe || (() => probeBindingInFreshProcess(installDir));
288
- // Bounded by default: a node-gyp fallback that stalls (no compiler, a hung
289
- // registry fetch) must not hang the caller forever — the CLI blocks a user at
290
- // the terminal, and scripts/setup.sh passes an even tighter 20s cap because it
291
- // runs under a hook timeout. Callers needing a different budget inject `exec`.
292
- const exec = deps.exec || ((cmd, opts) => execSync(cmd, { timeout: 240_000, ...opts }));
292
+ // The npm steps are bounded: one that stalls (a hung registry fetch) must not hang
293
+ // the caller forever — the CLI blocks a user at the terminal, and
294
+ // scripts/binding-probe-cli.mjs injects an even tighter 20s cap because it runs under
295
+ // a hook timeout. The source build below is NOT bounded (D#859): execSync's timeout
296
+ // signals only its direct child, the shell it starts, so a cap left npm and node-gyp
297
+ // compiling after this function had reported failure, put the shadowing prebuild back and
298
+ // returned to a caller that then released install.lock.
299
+ const exec = deps.exec || ((cmd, opts) => execSync(cmd, opts));
293
300
  const rebuild =
294
301
  deps.rebuild ||
295
302
  (async () => {
@@ -305,9 +312,9 @@ export async function ensureBetterSqlite3Working(installDir, deps = {}) {
305
312
  // npm has no such gate and treats the unknown flag as an ignored config; if
306
313
  // it instead errors on the flag, fall back to the plain rebuild.
307
314
  try {
308
- exec(NATIVE_BINDING_REBUILD_CMD, { cwd: installDir, stdio: 'pipe' });
315
+ exec(NATIVE_BINDING_REBUILD_CMD, { cwd: installDir, stdio: 'pipe', timeout: NPM_STEP_TIMEOUT_MS });
309
316
  } catch {
310
- exec('npm rebuild better-sqlite3', { cwd: installDir, stdio: 'pipe' });
317
+ exec('npm rebuild better-sqlite3', { cwd: installDir, stdio: 'pipe', timeout: NPM_STEP_TIMEOUT_MS });
311
318
  }
312
319
  });
313
320
 
@@ -414,11 +421,26 @@ export async function ensureBetterSqlite3Working(installDir, deps = {}) {
414
421
  * Refuses to act when the guard env is already set, so a heal that does not
415
422
  * actually fix the binding cannot spawn an unbounded chain of children.
416
423
  *
417
- * @param {{installDir?: string, argv?: string[], env?: Record<string,string|undefined>, ensure?: () => Promise<{ok: boolean, action?: string, error?: string}>, reexec?: (argv: string[], env: Record<string,string|undefined>) => number, log?: (msg: string) => void}} opts
418
- * @returns {Promise<{healed: true, exitCode: number} | {healed: false, reason: string, error?: string}>}
424
+ * With `cooldownPath`, at most one automatic rebuild per CLI_HEAL_COOLDOWN_MS (D#311). The
425
+ * marker is armed before the rebuild starts and kept when it fails. A rebuild that works removes
426
+ * it, as rebuild-binding does whenever every code home loads, so a later, unrelated break heals at
427
+ * once. A re-exec'd child that still cannot load the binding arms it: the rebuild reported
428
+ * success without fixing the tree this CLI runs from, and running it again would not either. A
429
+ * marker dated after `now` (the clock moved back) counts as absent. Every marker read or write is
430
+ * best-effort — one that cannot be written costs the cooldown, never the heal.
431
+ *
432
+ * @param {{installDir?: string, argv?: string[], env?: Record<string,string|undefined>, ensure?: () => Promise<{ok: boolean, action?: string, error?: string}>, reexec?: (argv: string[], env: Record<string,string|undefined>) => number, log?: (msg: string) => void, cooldownPath?: string, now?: number}} opts
433
+ * @returns {Promise<{healed: true, exitCode: number} | {healed: false, reason: string, error?: string, since?: number}>}
419
434
  */
420
435
  export async function healAndReexec(opts) {
421
- const { installDir, argv = process.argv, env = process.env, log = () => {} } = opts;
436
+ const {
437
+ installDir,
438
+ argv = process.argv,
439
+ env = process.env,
440
+ log = () => {},
441
+ cooldownPath,
442
+ now = Date.now(),
443
+ } = opts;
422
444
  const ensure = opts.ensure || (() => ensureBetterSqlite3Working(installDir));
423
445
  const reexec =
424
446
  opts.reexec ||
@@ -427,7 +449,17 @@ export async function healAndReexec(opts) {
427
449
  return typeof r.status === 'number' ? r.status : 1;
428
450
  });
429
451
 
430
- if (env[BINDING_HEAL_GUARD_ENV]) return { healed: false, reason: 'already-attempted' };
452
+ if (env[BINDING_HEAL_GUARD_ENV]) {
453
+ if (cooldownPath) writeHealMarker(cooldownPath, now);
454
+ return { healed: false, reason: 'already-attempted' };
455
+ }
456
+
457
+ if (cooldownPath) {
458
+ const since = readHealMarker(cooldownPath);
459
+ const age = now - since;
460
+ if (age >= 0 && age < CLI_HEAL_COOLDOWN_MS) return { healed: false, reason: 'cooldown', since };
461
+ writeHealMarker(cooldownPath, now);
462
+ }
431
463
 
432
464
  log(`native DB binding unusable — rebuilding for this Node (${process.version})…`);
433
465
  let verify;
@@ -438,7 +470,87 @@ export async function healAndReexec(opts) {
438
470
  }
439
471
  if (!verify.ok) return { healed: false, reason: 'rebuild-failed', error: verify.error };
440
472
 
473
+ if (cooldownPath) {
474
+ try {
475
+ unlinkSync(cooldownPath);
476
+ } catch {
477
+ /* not there, or not ours to remove — the heal itself worked */
478
+ }
479
+ }
441
480
  log('binding rebuilt — retrying');
442
481
  const exitCode = reexec(argv, { ...env, [BINDING_HEAL_GUARD_ENV]: '1' });
443
482
  return { healed: true, exitCode };
444
483
  }
484
+
485
+ /**
486
+ * The CLI's `ensure` for healAndReexec: run `cli.mjs rebuild-binding` in a child, so there is
487
+ * ONE healer — it takes install.lock, repairs every code home on this machine, and clears the
488
+ * hooks' breakage marker.
489
+ *
490
+ * Child stdout is DISCARDED, not inherited: install.mjs logs progress to stdout, and the CLI's
491
+ * stdout is a data channel (`search --json` is piped into jq). Progress still reaches the user
492
+ * via stderr.
493
+ *
494
+ * No time cap on the child (D#311). This is the foreground path the source-build comment in
495
+ * ensureBetterSqlite3Working leaves the compile to. The 300 s cap this had was sized for one 240 s npm step in one code home; rebuild-binding now
496
+ * covers every code home with a source build after the npm step, and a kill mid-compile leaves
497
+ * build/ deleted, the quarantined prebuild moved aside and install.lock held by a dead pid.
498
+ *
499
+ * @param {string} cliPath Absolute path to cli.mjs
500
+ * @param {typeof spawnSync} [spawn]
501
+ * @returns {{ok: true, action: 'rebuilt'} | {ok: false, error: string}}
502
+ */
503
+ export function rebuildBindingViaCli(cliPath, spawn = spawnSync) {
504
+ const r = spawn(process.execPath, [cliPath, 'rebuild-binding'], {
505
+ stdio: ['ignore', 'ignore', 'inherit'],
506
+ });
507
+ return r.status === 0
508
+ ? { ok: true, action: 'rebuilt' }
509
+ : { ok: false, error: `rebuild-binding exited ${r.status ?? 'on signal'}` };
510
+ }
511
+
512
+ export const CLI_HEAL_MARKER = 'native-binding-cli-lastheal';
513
+ export const CLI_HEAL_COOLDOWN_MS = 6 * 60 * 60 * 1000;
514
+
515
+ /**
516
+ * The CLI's heal: healAndReexec with rebuildBindingViaCli as its rebuild and a cooldown marker
517
+ * in `runtimeDir`.
518
+ *
519
+ * @param {{cliPath: string, runtimeDir: string, spawn?: typeof spawnSync, now?: number, argv?: string[], env?: Record<string,string|undefined>, reexec?: (argv: string[], env: Record<string,string|undefined>) => number, log?: (msg: string) => void}} opts
520
+ */
521
+ export function healCliBinding({ cliPath, runtimeDir, spawn, ...opts }) {
522
+ return healAndReexec({
523
+ ...opts,
524
+ ensure: async () => rebuildBindingViaCli(cliPath, spawn),
525
+ cooldownPath: join(runtimeDir, CLI_HEAL_MARKER),
526
+ });
527
+ }
528
+
529
+ /** Epoch ms of the last armed heal; NaN with no readable marker, which no window contains. */
530
+ function readHealMarker(path) {
531
+ try {
532
+ return Number(readFileSync(path, 'utf8'));
533
+ } catch {
534
+ return NaN;
535
+ }
536
+ }
537
+
538
+ /**
539
+ * Through the shared writer, whose rename needs only the directory: a stale marker this user can
540
+ * read but not write (left by a sudo run) is still replaced, where a plain write would fail and
541
+ * switch the cooldown off for good.
542
+ */
543
+ function writeHealMarker(path, at) {
544
+ try {
545
+ atomicWriteFileSync(path, String(at));
546
+ } catch {
547
+ /* no marker, no cooldown — the heal still runs */
548
+ }
549
+ }
550
+
551
+ /** The reason line the CLI prints when the cooldown skipped its rebuild. */
552
+ export function cliHealSkipNote(since, now = Date.now()) {
553
+ const min = Math.floor((now - since) / 60_000);
554
+ const ago = min < 1 ? 'under a minute' : min < 120 ? `${min} min` : `${Math.floor(min / 60)} h`;
555
+ return `automatic rebuild skipped: last attempted ${ago} ago (one per 6 h)`;
556
+ }
@@ -42,6 +42,7 @@ import {
42
42
  writeFileSync,
43
43
  } from 'fs';
44
44
  import { homedir } from 'os';
45
+ import { readRegularTextOrThrow } from './regular-file.mjs';
45
46
  import { dirname, isAbsolute, join, parse, resolve, sep } from 'path';
46
47
  import {
47
48
  readBlockAt,
@@ -188,14 +189,14 @@ function npmPublishable(root) {
188
189
  if (!existsSync(pj)) return false;
189
190
  let pkg;
190
191
  try {
191
- pkg = JSON.parse(readFileSync(pj, 'utf8'));
192
+ pkg = JSON.parse(readRegularTextOrThrow(pj));
192
193
  } catch {
193
194
  return true;
194
195
  }
195
196
  if (pkg && pkg.private === true) return false;
196
197
  if (Array.isArray(pkg?.files)) return pkg.files.some(filesEntryCouldShipRootFile);
197
198
  try {
198
- const ignore = readFileSync(join(root, '.npmignore'), 'utf8');
199
+ const ignore = readRegularTextOrThrow(join(root, '.npmignore'));
199
200
  if (/^\s*\/?CLAUDE\.local\.md\s*$/m.test(ignore)) return false;
200
201
  } catch {
201
202
  /* no .npmignore */
@@ -234,7 +235,7 @@ function npmShipsRules(root) {
234
235
  if (!existsSync(pj)) return false;
235
236
  let pkg;
236
237
  try {
237
- pkg = JSON.parse(readFileSync(pj, 'utf8'));
238
+ pkg = JSON.parse(readRegularTextOrThrow(pj));
238
239
  } catch {
239
240
  return true;
240
241
  }
@@ -252,7 +253,7 @@ function npmShipsRules(root) {
252
253
  const ignoreFile = existsSync(join(root, '.npmignore')) ? '.npmignore' : '.gitignore';
253
254
  let lines;
254
255
  try {
255
- lines = readFileSync(join(root, ignoreFile), 'utf8')
256
+ lines = readRegularTextOrThrow(join(root, ignoreFile))
256
257
  .split(/\r?\n/)
257
258
  .map((l) => l.trim());
258
259
  } catch {
@@ -102,7 +102,9 @@ export function readPausedNote({
102
102
  if (!name.endsWith('-paused.md')) continue;
103
103
  try {
104
104
  const st = statSync(join(tasksDir, name));
105
- if (st.size > MAX_NOTE_BYTES) continue;
105
+ // A FIFO or a device (a repository can commit a link to one) is no note, and must not
106
+ // shadow an older regular one.
107
+ if (!st.isFile() || st.size > MAX_NOTE_BYTES) continue;
106
108
  if (!newest || st.mtimeMs > newest.mtime) newest = { name, mtime: st.mtimeMs };
107
109
  } catch {
108
110
  /* vanished between readdir and stat — skip it */
@@ -21,7 +21,7 @@
21
21
  // `tests/post-tool-use-disabled.test.mjs` pins it. Two homes with a tested bridge is a
22
22
  // different thing from two homes and a comment.
23
23
 
24
- import { readFileSync } from 'node:fs';
24
+ import { readRegularTextOrThrow } from './regular-file.mjs';
25
25
 
26
26
  /** Marketplace this plugin is published under. */
27
27
  export const MARKETPLACE_KEY = 'sdsrss';
@@ -92,12 +92,21 @@ export function isPluginDisabledInScopes(settingsList) {
92
92
  * @param {string} projectDir CLAUDE_PROJECT_DIR, else the caller's cwd
93
93
  */
94
94
  export function isPluginDisabledForProject(configHome, projectDir) {
95
- const read = (path) => {
96
- try {
97
- return JSON.parse(readFileSync(path, 'utf8'));
98
- } catch {
99
- return null;
100
- }
101
- };
102
- return isPluginDisabledInScopes(pluginSettingsScopes(configHome, projectDir).map(read));
95
+ return isPluginDisabledInScopes(pluginSettingsScopes(configHome, projectDir).map(readSettingsScope));
96
+ }
97
+
98
+ /**
99
+ * One settings file parsed, or null when it is missing, unparseable, or not a regular file (a FIFO,
100
+ * a device) or over 4 MiB, which sets nothing (fail open). Two of the scopes live in the project,
101
+ * where a repository can commit `.claude/settings.json -> /dev/zero`: a plain read of that ran
102
+ * without end on every hook event.
103
+ * @param {string} path
104
+ * @returns {object|null}
105
+ */
106
+ export function readSettingsScope(path) {
107
+ try {
108
+ return JSON.parse(readRegularTextOrThrow(path));
109
+ } catch {
110
+ return null;
111
+ }
103
112
  }
@@ -0,0 +1,147 @@
1
+ // Leaf (node: imports only): whether the plugin may write a project file reached through a link.
2
+ //
3
+ // A cloned repository can commit links, and the plugin writes into the project it is opened in:
4
+ // with `.claude -> ../../somewhere` committed, adopt and the SessionStart sync wrote their two files
5
+ // into a directory the repository picked, unadopt deleted them there, and a CLAUDE.md committed as a
6
+ // link had its outside target rewritten (D#880; v6.35.3 pre-tag round 2, F1). A link the user made
7
+ // at `.claude` or CLAUDE.md — a dotfiles-managed one, a worktree sharing the main checkout's — is
8
+ // theirs to point anywhere, and git lists it as untracked where it lists a committed one as a staged
9
+ // symlink. git cannot tell the user's from one an unpacked archive left in a work tree (untracked
10
+ // too): a link at either file the plugin rewrites whole is never written through, as before
11
+ // (v6.35.4 pre-tag round 1, F1).
12
+ import { lstatSync, realpathSync } from 'node:fs';
13
+ import { execFileSync } from 'node:child_process';
14
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
15
+
16
+ /**
17
+ * Why the plugin must not write `rel` under `root` through the links on its way, or null when it
18
+ * may. Each link on the path, nearest the project first:
19
+ * - the file itself, when `whole` is set (the plugin replaces or deletes that file whole): refused,
20
+ * whoever made it;
21
+ * - git lists it as untracked: written through;
22
+ * - otherwise it must resolve inside the project (the git top-level, else `root`) and not into a
23
+ * `.git` directory, in any letter case.
24
+ * No link on the path costs one lstat per component and no git.
25
+ * `kind`: 'whole', 'committed' (git lists the path as tracked: a committed link, or a committed file
26
+ * the link replaced) or 'unknown' (git does not list it: no work tree, git missing or refusing, a path
27
+ * git tracks only under another letter case).
28
+ * @param {string} root the project directory
29
+ * @param {string} rel '/'-separated path below it
30
+ * @param {{whole?: boolean}} [opts]
31
+ * @returns {{link: string, why: string, kind: 'whole'|'committed'|'unknown'}|null}
32
+ */
33
+ export function linkRefusal(root, rel, { whole = false } = {}) {
34
+ const parts = rel.split('/');
35
+ let top;
36
+ for (let i = 0; i < parts.length; i++) {
37
+ const lex = join(root, ...parts.slice(0, i + 1));
38
+ let st;
39
+ try {
40
+ st = lstatSync(lex);
41
+ } catch {
42
+ return null; // absent: nothing below it exists to write through
43
+ }
44
+ if (!st.isSymbolicLink()) continue;
45
+ if (whole && i === parts.length - 1)
46
+ return {
47
+ link: lex,
48
+ kind: 'whole',
49
+ why: 'a link, and the plugin rewrites this file whole: git cannot tell a link you made here from one a repository or an unpacked archive put there',
50
+ };
51
+ const made = userMade(root, lex);
52
+ if (made) continue;
53
+ let target = null;
54
+ try {
55
+ target = realpathSync(lex);
56
+ } catch {
57
+ /* dangling: where a write would land is unknown */
58
+ }
59
+ let where = target === null ? 'out' : place(root, target);
60
+ if (where === 'out' && target !== null) {
61
+ if (top === undefined) top = gitTop(root);
62
+ if (top) where = place(top, target);
63
+ }
64
+ if (where === 'in') continue;
65
+ const who =
66
+ made === false
67
+ ? 'a link this repository commits'
68
+ : 'a link git does not list as one you made (outside a git work tree, or git did not answer)';
69
+ const to =
70
+ target === null
71
+ ? 'to a path that does not resolve'
72
+ : `to ${target}, ${where === 'git' ? 'inside a .git directory' : 'outside this project'}`;
73
+ return { link: lex, kind: made === false ? 'committed' : 'unknown', why: `${who}, ${to}` };
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /** The refusal as adopt reports it: what the link is, then what to do. */
79
+ export function refusalText(r) {
80
+ const next =
81
+ r.kind === 'unknown'
82
+ ? 'if you made the link, adopt in a git work tree, where git lists it as untracked; otherwise delete it, then run adopt again'
83
+ : 'delete the link, then run adopt again';
84
+ return `${r.link}: ${r.why}. Not written through; ${next}.`;
85
+ }
86
+
87
+ // 'in': inside `dir` by real path; 'git': inside a `.git` directory below it (a link into one
88
+ // reaches git's own config and hooks; any letter case, for case-insensitive file systems); 'out'.
89
+ function place(dir, target) {
90
+ let base;
91
+ try {
92
+ base = realpathSync(dir);
93
+ } catch {
94
+ return 'out';
95
+ }
96
+ const r = relative(base, target);
97
+ if (r === '') return 'in';
98
+ if (isAbsolute(r)) return 'out';
99
+ const segs = r.split(sep);
100
+ if (segs[0] === '..') return 'out';
101
+ return segs.some((s) => s.toLowerCase() === '.git') ? 'git' : 'in';
102
+ }
103
+
104
+ function git(cwd, args) {
105
+ return execFileSync('git', args, {
106
+ cwd,
107
+ encoding: 'utf8',
108
+ stdio: ['ignore', 'pipe', 'ignore'],
109
+ timeout: 5000,
110
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_LITERAL_PATHSPECS: '1' },
111
+ });
112
+ }
113
+
114
+ function gitTop(root) {
115
+ try {
116
+ return git(root, ['rev-parse', '--show-toplevel']).trim() || null;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ // true: git lists the link as untracked; false: as a tracked path (a committed link, or a committed
123
+ // file the link replaced, which is also what a case-insensitive checkout of `CLAUDE.md` beside a
124
+ // committed `claude.md` link leaves — v6.35.4 pre-tag round 1, F3); null: git does not list it (not a
125
+ // work tree, no git or git refusing, a path git tracks only under another letter case).
126
+ // Asked by its real directory, so a path below a link inside the project is still one git knows.
127
+ function userMade(root, lex) {
128
+ let here;
129
+ try {
130
+ here = join(realpathSync(dirname(lex)), basename(lex));
131
+ } catch {
132
+ return null;
133
+ }
134
+ let out;
135
+ try {
136
+ out = git(root, ['ls-files', '-z', '-s', '-o', '--', here]);
137
+ } catch {
138
+ return null;
139
+ }
140
+ let made = null;
141
+ for (const entry of out.split('\0')) {
142
+ if (entry === '') continue;
143
+ if (!/^\d{6} [0-9a-f]+ \d\t/.test(entry)) return true;
144
+ made = false;
145
+ }
146
+ return made;
147
+ }
@@ -0,0 +1,58 @@
1
+ // lib/regular-file.mjs — read a file only when it is a regular file, and only up to a byte limit.
2
+ //
3
+ // For paths someone else can occupy: the instruction files above a project (/tmp is writable by
4
+ // every local user), and the files inside a project, where a repository can commit a symlink to a
5
+ // device (`CLAUDE.md -> /dev/zero`) and a local process can leave a FIFO. A plain readFileSync
6
+ // reads a device without end and blocks on a FIFO with no writer; Claude Code itself skips an
7
+ // instruction file that is "not a regular file or exceeds 4194304 byte limit" (2.1.322's message).
8
+ // A leaf (node:fs only), so a hook or the settings check can take it without a load graph.
9
+
10
+ import { closeSync, constants as fsConstants, fstatSync, openSync, readSync } from 'node:fs';
11
+
12
+ /** Claude Code's limit for an instruction file, and the default limit here. */
13
+ const INSTRUCTION_FILE_MAX_BYTES = 4194304;
14
+
15
+ /**
16
+ * A regular file's text, or null for a FIFO, a device or a file over `maxBytes`. Opened
17
+ * non-blocking and checked on the descriptor, so a file swapped in after the check is not the one
18
+ * read. The size fstat reports is no bound — /proc/self/pagemap reports 0 whatever it holds, and a
19
+ * file can grow — so the read stops at the first 64 KiB chunk that takes the total past the limit. A
20
+ * missing path throws ENOENT and a directory EISDIR, as a plain read did.
21
+ * @param {string} p
22
+ * @param {number} [maxBytes]
23
+ * @returns {string|null}
24
+ */
25
+ export function readRegularText(p, maxBytes = INSTRUCTION_FILE_MAX_BYTES) {
26
+ const fd = openSync(p, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
27
+ try {
28
+ const st = fstatSync(fd);
29
+ if (st.isDirectory()) throw Object.assign(new Error(`${p}: is a directory`), { code: 'EISDIR' });
30
+ if (!st.isFile() || st.size > maxBytes) return null;
31
+ const chunks = [];
32
+ let total = 0;
33
+ for (;;) {
34
+ const chunk = Buffer.allocUnsafe(65536);
35
+ const n = readSync(fd, chunk, 0, chunk.length, null);
36
+ if (n === 0) break;
37
+ total += n;
38
+ if (total > maxBytes) return null;
39
+ chunks.push(chunk.subarray(0, n));
40
+ }
41
+ return Buffer.concat(chunks, total).toString('utf8');
42
+ } finally {
43
+ closeSync(fd);
44
+ }
45
+ }
46
+
47
+ /**
48
+ * readRegularText for a caller that already handles a file it cannot read: throws where that
49
+ * returns null, so the caller's existing handling of an unreadable file applies.
50
+ * @param {string} p
51
+ * @param {number} [maxBytes]
52
+ * @returns {string}
53
+ */
54
+ export function readRegularTextOrThrow(p, maxBytes = INSTRUCTION_FILE_MAX_BYTES) {
55
+ const text = readRegularText(p, maxBytes);
56
+ if (text === null) throw new Error(`${p}: not a regular file, or over ${maxBytes} bytes`);
57
+ return text;
58
+ }
package/mem-cli.mjs CHANGED
@@ -89,13 +89,12 @@ import {
89
89
  splitDeferredTokens,
90
90
  } from './lib/id-routing.mjs';
91
91
  import { join, dirname } from 'path';
92
- import { spawnSync } from 'child_process';
93
92
  import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
94
93
 
95
94
  // v2.41: shared CLI helpers extracted to cli/common.mjs. Keep this file as the
96
95
  // router + remaining-command bodies during the incremental split. Future work:
97
96
  // move each cmdXxx into its own cli/<cmd>.mjs; mem-cli.mjs becomes pure dispatch.
98
- import { isNativeBindingError, healAndReexec } from './lib/binding-probe.mjs';
97
+ import { isNativeBindingError, healCliBinding, cliHealSkipNote } from './lib/binding-probe.mjs';
99
98
  import {
100
99
  isSchemaSkewError,
101
100
  schemaSkewFromError,
@@ -4236,32 +4235,19 @@ async function runDispatch(argv) {
4236
4235
  // healer was an MCP server start the user might never perform — the shape of
4237
4236
  // the 4-day outage on 2026-08-13. Heal in place, then RE-EXEC: this process
4238
4237
  // has already dlopen'd the stale binary, so it cannot use the new one.
4238
+ // One automatic try per 6 h (D#311); `rebuild-binding` itself is never gated.
4239
4239
  if (isNativeBindingError(e)) {
4240
- const healed = await healAndReexec({
4241
- // Delegate the actual rebuild to `cli.mjs rebuild-binding` so there is
4242
- // ONE healer: it takes install.lock, resolves which node_modules tree
4243
- // the running code uses, and clears the hooks' breakage marker.
4244
- ensure: async () => {
4245
- // Child stdout is DISCARDED, not inherited: install.mjs logs progress
4246
- // to stdout, and this CLI's stdout is a data channel (`search --json`
4247
- // is piped into jq). Progress still reaches the user via stderr.
4248
- const r = spawnSync(process.execPath, [CLI_PATH, 'rebuild-binding'], {
4249
- stdio: ['ignore', 'ignore', 'inherit'],
4250
- timeout: 300_000,
4251
- });
4252
- return r.status === 0
4253
- ? { ok: true, action: 'rebuilt' }
4254
- : { ok: false, error: `rebuild-binding exited ${r.status ?? 'on signal'}` };
4255
- },
4240
+ const healed = await healCliBinding({
4241
+ cliPath: CLI_PATH,
4242
+ runtimeDir: resolveRuntimeDir(DB_DIR),
4256
4243
  log: (m) => process.stderr.write(`[mem] ${m}\n`),
4257
4244
  });
4258
4245
  if (healed.healed) {
4259
4246
  process.exitCode = healed.exitCode;
4260
4247
  return;
4261
4248
  }
4262
- out(
4263
- `[mem] Error: native DB binding unusable on Node ${process.version}${healed.error ? ` — ${healed.error}` : ''}`,
4264
- );
4249
+ const why = healed.reason === 'cooldown' ? cliHealSkipNote(healed.since) : healed.error;
4250
+ out(`[mem] Error: native DB binding unusable on Node ${process.version}${why ? ` — ${why}` : ''}`);
4265
4251
  out(`[mem] Fix: ${CLI_INVOKE} rebuild-binding`);
4266
4252
  process.exitCode = 1;
4267
4253
  return;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "6.35.2",
3
+ "version": "6.35.4",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "claude-mem-lite",
9
- "version": "6.35.2",
9
+ "version": "6.35.4",
10
10
  "os": [
11
11
  "darwin",
12
12
  "linux",
@@ -24,11 +24,11 @@
24
24
  "@eslint/js": "^10.0.1",
25
25
  "@vitest/coverage-v8": "^5.1.0",
26
26
  "acorn": "8.19.0",
27
- "eslint": "^10.14.0",
27
+ "eslint": "^10.15.0",
28
28
  "fast-check": "^4.10.2",
29
- "knip": "^6.44.1",
29
+ "knip": "^6.45.1",
30
30
  "picomatch": "^4.0.4",
31
- "prettier": "3.9.10",
31
+ "prettier": "3.10.1",
32
32
  "vitest": "^5.0.3"
33
33
  },
34
34
  "engines": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "6.35.2",
3
+ "version": "6.35.4",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword 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",
@@ -133,6 +133,8 @@
133
133
  "lib/recent-table.mjs",
134
134
  "lib/proc-lock.mjs",
135
135
  "lib/atomic-write.mjs",
136
+ "lib/regular-file.mjs",
137
+ "lib/project-link.mjs",
136
138
  "lib/platform-gate.mjs",
137
139
  "lib/hook-prune.mjs",
138
140
  "lib/proxy-fetch.mjs",
@@ -254,11 +256,11 @@
254
256
  "@eslint/js": "^10.0.1",
255
257
  "@vitest/coverage-v8": "^5.1.0",
256
258
  "acorn": "8.19.0",
257
- "eslint": "^10.14.0",
259
+ "eslint": "^10.15.0",
258
260
  "fast-check": "^4.10.2",
259
- "knip": "^6.44.1",
261
+ "knip": "^6.45.1",
260
262
  "picomatch": "^4.0.4",
261
- "prettier": "3.9.10",
263
+ "prettier": "3.10.1",
262
264
  "vitest": "^5.0.3"
263
265
  }
264
266
  }
@@ -26,7 +26,19 @@
26
26
  // would defeat the entire purpose — the launcher must survive a broken
27
27
  // install.
28
28
 
29
- import { existsSync, mkdirSync, writeFileSync, statSync, unlinkSync, readFileSync } from 'node:fs';
29
+ import {
30
+ closeSync,
31
+ constants as fsConstants,
32
+ existsSync,
33
+ fstatSync,
34
+ mkdirSync,
35
+ openSync,
36
+ readFileSync,
37
+ readSync,
38
+ statSync,
39
+ unlinkSync,
40
+ writeFileSync,
41
+ } from 'node:fs';
30
42
  import { spawn, spawnSync } from 'node:child_process';
31
43
  import { dirname, join, isAbsolute } from 'node:path';
32
44
  import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -196,6 +208,33 @@ if (swapInProgress()) process.exit(0);
196
208
  // and local scopes are merged as the host merges them, highest last (lib/plugin-key.mjs
197
209
  // pluginSettingsScopes / isPluginDisabledInScopes): reading the user scope alone killed a
198
210
  // plugin a project enabled (E2E 2026-10-16 round 2).
211
+ //
212
+ // Each scope is read only when it is a regular file of at most 4 MiB: a cloned repository can
213
+ // commit `.claude/settings.json -> /dev/zero`, which a plain read followed without end on every
214
+ // hook event, and a FIFO there blocked the open. lib/regular-file.mjs readRegularText, inline per
215
+ // the charter; null for anything else, which sets nothing (fail open).
216
+ const SETTINGS_MAX_BYTES = 4194304;
217
+ function readSettingsText(path) {
218
+ const fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
219
+ try {
220
+ const st = fstatSync(fd);
221
+ if (!st.isFile() || st.size > SETTINGS_MAX_BYTES) return null;
222
+ const chunks = [];
223
+ let total = 0;
224
+ for (;;) {
225
+ const chunk = Buffer.allocUnsafe(65536);
226
+ const n = readSync(fd, chunk, 0, chunk.length, null);
227
+ if (n === 0) break;
228
+ total += n;
229
+ if (total > SETTINGS_MAX_BYTES) return null;
230
+ chunks.push(chunk.subarray(0, n));
231
+ }
232
+ return Buffer.concat(chunks, total).toString('utf8');
233
+ } finally {
234
+ closeSync(fd);
235
+ }
236
+ }
237
+
199
238
  function pluginDisabled() {
200
239
  const d = process.env.CLAUDE_CONFIG_DIR;
201
240
  const configHome = d && isAbsolute(d) ? d : join(homedir(), '.claude');
@@ -207,7 +246,9 @@ function pluginDisabled() {
207
246
  join(projectDir, '.claude', 'settings.local.json'),
208
247
  ]) {
209
248
  try {
210
- const v = JSON.parse(readFileSync(path, 'utf8'))?.enabledPlugins?.['claude-mem-lite@sdsrss'];
249
+ const text = readSettingsText(path);
250
+ if (text === null) continue;
251
+ const v = JSON.parse(text)?.enabledPlugins?.['claude-mem-lite@sdsrss'];
211
252
  if (typeof v === 'boolean') value = v;
212
253
  } catch {
213
254
  /* missing or unparseable: sets nothing (fail open) */
@@ -21,9 +21,9 @@
21
21
  # tests/post-tool-use-disabled.test.mjs.
22
22
  # Cheap by construction: no `node`, no external command on this ~5ms per-tool-call path — except
23
23
  # when the regex says disabled, which node then confirms (see _mem_plugin_disabled).
24
- # `-r` covers missing/unreadable in one builtin test, and `$(<file)` slurps the whole file
25
- # for ONE regex — measured +0.4ms/call vs +4.0ms for a `while read` loop over the same
26
- # 239-line settings.json (bash pays a syscall + a regex per line there).
24
+ # Each file is read once for ONE regex (see _mem_plugin_disabled), not line by line: a
25
+ # `while read` loop over a 239-line settings.json measured +4.0ms/call (bash pays a syscall +
26
+ # a regex per line there).
27
27
  # The ERE (not a `==` glob) is what keeps a MINIFIED single-line settings.json from
28
28
  # matching `"<key>": true, … "other": false` as a false positive: the pattern is anchored
29
29
  # to the key, so only that key's own value can satisfy it.
@@ -48,10 +48,20 @@ _mem_settings_file="$_mem_config_home/settings.json"
48
48
  _mem_project_dir="${CLAUDE_PROJECT_DIR:-$PWD}"
49
49
  _mem_plugin_disabled() {
50
50
  local _f _settings _value=""
51
+ # Bytes, for -n and ${#} below. Function-local: restored on return.
52
+ local LC_ALL=C
51
53
  for _f in "$_mem_settings_file" "$_mem_project_dir/.claude/settings.json" \
52
54
  "$_mem_project_dir/.claude/settings.local.json"; do
53
- [[ -r "$_f" ]] || continue
54
- _settings=$(<"$_f")
55
+ # At most 4 MiB of a regular file (lib/regular-file.mjs bounds node's reads of the same
56
+ # files): a cloned repository can commit `.claude/settings.json -> /dev/zero`, which
57
+ # `$(<file)` read without end, and a FIFO there blocked the open. -f follows a link and is
58
+ # false for a device or a FIFO. The read stops at 4 MiB or at the first NUL byte; a file
59
+ # still longer than 4 MiB reads as unreadable. Builtins only: on bash 5.3, ~50 µs over
60
+ # `$(<file)` on a 7 KB file.
61
+ [[ -f "$_f" && -r "$_f" ]] || continue
62
+ _settings=
63
+ IFS= read -r -d '' -n 4194305 _settings <"$_f"
64
+ ((${#_settings} <= 4194304)) || continue
55
65
  [[ "$_settings" =~ \"claude-mem-lite@sdsrss\"[[:space:]]*:[[:space:]]*(true|false) ]] &&
56
66
  _value="${BASH_REMATCH[1]}"
57
67
  done
package/source-files.mjs CHANGED
@@ -78,6 +78,14 @@ export const SOURCE_FILES = [
78
78
  // are present in the pre-edit file (component 2). Imported ONLY by
79
79
  // scripts/pre-tool-recall.js; kept here for the same reason as file-intel.mjs.
80
80
  'lib/lesson-idents.mjs',
81
+ // Leaf (node: imports only). Ahead of binding-probe, which writes the CLI heal marker through it.
82
+ 'lib/atomic-write.mjs',
83
+ // Leaf (node: imports only): bounded reads of files someone else can occupy. Ahead of plugin-key,
84
+ // claudemd, local-steering and hook-context, which import it.
85
+ 'lib/regular-file.mjs',
86
+ // Leaf (node: imports only): whether a project file reached through a link may be written. Ahead
87
+ // of claudemd and hook-context, which import it.
88
+ 'lib/project-link.mjs',
81
89
  // v2.71.x: better-sqlite3 ABI probe + auto-rebuild. Shared by install.mjs
82
90
  // (post-`npm install` verify) and scripts/launch.mjs (pre-server-launch
83
91
  // self-heal after Node ABI changes). Missing from manifest → auto-update
@@ -98,7 +106,6 @@ export const SOURCE_FILES = [
98
106
  'lib/hook-text-cap.mjs',
99
107
  'lib/hook-stdout.mjs',
100
108
  'lib/recall-framing.mjs',
101
- 'lib/atomic-write.mjs',
102
109
  'lib/recall-shown.mjs',
103
110
  // A closed WAL store in an unwritable data dir: one classification for doctor, status and
104
111
  // mem-cli's DB open (D#296), so the CLI does not load install.mjs to word one error.