claude-mem-lite 6.35.2 → 6.35.3

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.3",
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.3",
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
  }
package/claudemd.mjs CHANGED
@@ -15,21 +15,9 @@
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';
33
21
  import { join, basename } from 'path';
34
22
  import { createHash } from 'crypto';
35
23
  import { memdirPath, removePluginSection, removePluginDoc, isAdopted as memdirIsAdopted } from './memdir.mjs';
@@ -129,7 +117,8 @@ function orphanSentinelCount(raw, slug) {
129
117
  export function straySentinelLines(p, slug) {
130
118
  let raw;
131
119
  try {
132
- raw = readFileSync(p, 'utf8');
120
+ // Not a regular file, or over the limit: Claude Code does not load it, so nothing in it is.
121
+ raw = readRegularTextOrThrow(p);
133
122
  } catch {
134
123
  return [];
135
124
  }
@@ -231,7 +220,7 @@ export function holdsOnlyPluginLines(p, slug) {
231
220
  */
232
221
  export function addAgentsImports(cwd, slug, imports) {
233
222
  const p = claudeMdPath(cwd);
234
- const raw = existsSync(p) ? readFileSync(p, 'utf8') : '';
223
+ const raw = existsSync(p) ? readRegularTextOrThrow(p) : '';
235
224
  const marker = agentsImportMarker(slug);
236
225
  if (raw.includes(marker)) return 'present';
237
226
  const lines = `${marker}\n${imports.map((i) => `@${i}`).join('\n')}\n`;
@@ -281,39 +270,11 @@ export function readBlock(cwd, slug) {
281
270
  return readBlockAt(claudeMdPath(cwd), slug);
282
271
  }
283
272
 
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
- }
273
+ // Every read of an instruction file in this module goes through lib/regular-file.mjs: null (or a
274
+ // throw) for a FIFO, a device or a file over Claude Code's 4194304-byte limit. The session sync
275
+ // reads instruction files in every directory above the project (D#509(4)), /tmp among them, where
276
+ // any local user can put a FIFO (v6.32.0 pre-release defects review F1) or a huge file (delta
277
+ // review R2-1); inside the project a repository can commit a symlink to a device.
317
278
 
318
279
  /**
319
280
  * readBlock for any instructions file — CLAUDE.md, or the CLAUDE.local.md that auto-adopt
@@ -361,7 +322,7 @@ export function isOwnAdoptionArtifact(cwd, relPath, slug) {
361
322
  const ownFile = (name) =>
362
323
  name === stateName ||
363
324
  (name === docName &&
364
- readFileSync(join(dotClaudeDir(cwd), name), 'utf8').startsWith(managedByMarker(slug)));
325
+ readRegularTextOrThrow(join(dotClaudeDir(cwd), name)).startsWith(managedByMarker(slug)));
365
326
  if (rel === '.claude') {
366
327
  const names = readdirSync(dotClaudeDir(cwd));
367
328
  return names.length > 0 && names.every(ownFile);
@@ -446,6 +407,19 @@ export function needsRefresh(cwd, { slug, version, block, doc }) {
446
407
  * (block disposition, and the detail doc's)
447
408
  */
448
409
  export function writeManaged(cwd, { slug, version, block, doc }) {
410
+ // The detail doc and the state sidecar are this plugin's own files, and the shared writer writes
411
+ // THROUGH a link (for a dotfiles-managed CLAUDE.md): a cloned repository that committed either as
412
+ // a link out of the project had SessionStart overwrite the file it names. Refused before
413
+ // anything is written.
414
+ for (const p of [detailDocPath(cwd, slug), stateFilePath(cwd, slug)]) {
415
+ let link = false;
416
+ try {
417
+ link = lstatSync(p).isSymbolicLink();
418
+ } catch {
419
+ /* absent */
420
+ }
421
+ if (link) throw new Error(`${p}: a symbolic link; not written through`);
422
+ }
449
423
  const { action } = writeBlockAt(claudeMdPath(cwd), { slug, version, block });
450
424
 
451
425
  // Detail doc (marker on first line so unadopt/refresh can tell it apart from a
@@ -454,7 +428,7 @@ export function writeManaged(cwd, { slug, version, block, doc }) {
454
428
  const dp = detailDocPath(cwd, slug);
455
429
  const dir = dotClaudeDir(cwd);
456
430
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
457
- const existingDoc = existsSync(dp) ? readFileSync(dp, 'utf8') : null;
431
+ const existingDoc = existsSync(dp) ? readRegularTextOrThrow(dp) : null;
458
432
  if (existingDoc !== docContent) atomicWrite(dp, docContent);
459
433
  const docAction = existingDoc === null ? 'created' : existingDoc === docContent ? 'unchanged' : 'updated';
460
434
 
@@ -465,7 +439,7 @@ export function writeManaged(cwd, { slug, version, block, doc }) {
465
439
  const docHash = sha256(doc);
466
440
  let prev = null;
467
441
  try {
468
- prev = JSON.parse(readFileSync(stateFilePath(cwd, slug), 'utf8'));
442
+ prev = JSON.parse(readRegularTextOrThrow(stateFilePath(cwd, slug)));
469
443
  } catch {
470
444
  /* absent or unreadable: write it */
471
445
  }
@@ -483,7 +457,8 @@ export function writeManaged(cwd, { slug, version, block, doc }) {
483
457
  * @returns {{action: 'created'|'updated'|'unchanged'}}
484
458
  */
485
459
  export function writeBlockAt(p, { slug, version, block }) {
486
- const raw = existsSync(p) ? readFileSync(p, 'utf8') : '';
460
+ // Throws for a FIFO, a device or an over-limit file: nothing is written over it.
461
+ const raw = existsSync(p) ? readRegularTextOrThrow(p) : '';
487
462
  const section = renderBlock(slug, version, block);
488
463
  const m = raw.match(blockRegex(slug));
489
464
 
@@ -577,6 +552,18 @@ export function orphanResidueNote(orphans, slug, p) {
577
552
  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
553
  }
579
554
 
555
+ // readRegularText's limit for removing our block: its default (Claude Code's 4194304-byte limit)
556
+ // unless `p` reports a larger size, then that size. A device, a FIFO and /proc/self/pagemap
557
+ // report 0 and keep the default (readRegularText reads neither of the first two).
558
+ function regularFileLimit(p) {
559
+ try {
560
+ const st = statSync(p);
561
+ return st.size > 4194304 ? st.size : undefined;
562
+ } catch {
563
+ return undefined;
564
+ }
565
+ }
566
+
580
567
  /**
581
568
  * Remove every well-formed block of `slug` from one instructions file, keeping all other
582
569
  * text; a file left holding only whitespace is deleted (a symlink is emptied through the
@@ -588,8 +575,12 @@ export function orphanResidueNote(orphans, slug, p) {
588
575
  export function removeBlockAt(p, slug) {
589
576
  let action = 'absent';
590
577
  let orphans = 0;
591
- if (existsSync(p)) {
592
- let raw = readFileSync(p, 'utf8');
578
+ // A FIFO or a device is not read and holds no block: a repository can commit
579
+ // `CLAUDE.md -> /dev/zero`. A regular file is read whatever its size, as before: Claude Code
580
+ // does not load one over 4 MiB, but the block the user asked to remove still comes out.
581
+ const found = existsSync(p) ? readRegularText(p, regularFileLimit(p)) : null;
582
+ if (found !== null) {
583
+ let raw = found;
593
584
  // H2: loop so ALL same-slug blocks are removed, not just the first (a
594
585
  // duplicate/CRLF-orphaned copy must not survive unadopt).
595
586
  let m;
package/hook-context.mjs CHANGED
@@ -6,8 +6,9 @@
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 { readRegularTextOrThrow } from './lib/regular-file.mjs';
11
12
  import {
12
13
  estimateTokens,
13
14
  truncate,
@@ -422,7 +423,8 @@ export function cleanupClaudeMdLegacyBlock() {
422
423
  const claudeMdPath = join(inferProjectDir(), 'CLAUDE.md');
423
424
  let content;
424
425
  try {
425
- content = readFileSync(claudeMdPath, 'utf8');
426
+ // Bounded: a repository can commit `CLAUDE.md -> /dev/zero`; such a file is treated as missing.
427
+ content = readRegularTextOrThrow(claudeMdPath);
426
428
  } catch {
427
429
  // CLAUDE.md missing — still drop the marker so we don't re-stat every session
428
430
  try {
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,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.3",
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.3",
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.3",
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,7 @@
133
133
  "lib/recent-table.mjs",
134
134
  "lib/proc-lock.mjs",
135
135
  "lib/atomic-write.mjs",
136
+ "lib/regular-file.mjs",
136
137
  "lib/platform-gate.mjs",
137
138
  "lib/hook-prune.mjs",
138
139
  "lib/proxy-fetch.mjs",
@@ -254,11 +255,11 @@
254
255
  "@eslint/js": "^10.0.1",
255
256
  "@vitest/coverage-v8": "^5.1.0",
256
257
  "acorn": "8.19.0",
257
- "eslint": "^10.14.0",
258
+ "eslint": "^10.15.0",
258
259
  "fast-check": "^4.10.2",
259
- "knip": "^6.44.1",
260
+ "knip": "^6.45.1",
260
261
  "picomatch": "^4.0.4",
261
- "prettier": "3.9.10",
262
+ "prettier": "3.10.1",
262
263
  "vitest": "^5.0.3"
263
264
  }
264
265
  }
@@ -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,11 @@ 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',
81
86
  // v2.71.x: better-sqlite3 ABI probe + auto-rebuild. Shared by install.mjs
82
87
  // (post-`npm install` verify) and scripts/launch.mjs (pre-server-launch
83
88
  // self-heal after Node ABI changes). Missing from manifest → auto-update
@@ -98,7 +103,6 @@ export const SOURCE_FILES = [
98
103
  'lib/hook-text-cap.mjs',
99
104
  'lib/hook-stdout.mjs',
100
105
  'lib/recall-framing.mjs',
101
- 'lib/atomic-write.mjs',
102
106
  'lib/recall-shown.mjs',
103
107
  // A closed WAL store in an unwritable data dir: one classification for doctor, status and
104
108
  // mem-cli's DB open (D#296), so the CLI does not load install.mjs to word one error.