linksee-memory 0.16.1 → 0.17.1

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.
@@ -1,19 +1,91 @@
1
1
  import Database from 'better-sqlite3';
2
2
  import { readFileSync } from 'node:fs';
3
- import { mkdirSync, renameSync, existsSync } from 'node:fs';
3
+ import { mkdirSync, renameSync, existsSync, statSync, unlinkSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { homedir } from 'node:os';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { normalizeEntityName } from '../lib/normalize.js';
8
+ import { isNativeLoadError } from '../lib/native-hint.js';
8
9
  const DEFAULT_DB_DIR = process.env.LINKSEE_MEMORY_DIR ?? join(homedir(), '.linksee-memory');
9
10
  const DB_PATH = join(DEFAULT_DB_DIR, 'memory.db');
10
11
  export function getDbPath() {
11
12
  return DB_PATH;
12
13
  }
14
+ /**
15
+ * Decide, WITHOUT a writable connection, whether this file may be opened for writing at all.
16
+ * (0.17.1, Codex re-review of #15.) A writable connection that is the last one to close
17
+ * checkpoints a leftover WAL into memory.db and deletes it, and rolls back a hot journal — both
18
+ * are writes to a file we are about to refuse. So the schema is read through a read-only
19
+ * connection first (SQLITE_OPEN_READONLY: no checkpoint, no rollback, memory.db and -wal untouched).
20
+ * • schema 1–5 → LegacySchemaError
21
+ * • a hot rollback journal → HotJournalError (it cannot be read without rolling back)
22
+ * • not a DB → return; the normal open's corruption path moves it aside
23
+ * • native addon failed → rethrown as is
24
+ * • anything else (busy, locked, unreadable) → PrecheckError: could not check, so no writing
25
+ * When the file is refused, the -wal/-shm that the read-only open itself created are removed
26
+ * again, so the folder is left as it was.
27
+ */
28
+ function precheckBeforeWrite(path) {
29
+ if (!existsSync(path))
30
+ return; // new DB: nothing to protect, create it
31
+ const had = { wal: existsSync(path + '-wal'), shm: existsSync(path + '-shm') };
32
+ // Remove only what the read-only open itself added: a -wal that was absent and is still empty,
33
+ // and a -shm that was absent (e.g. a leftover -wal with no -shm — the reader builds one).
34
+ // Known limit (0.17.2): if another process opens the file in the same instant, the -shm deleted
35
+ // here may already be in use by it. The tests check a single process only, not concurrency.
36
+ const tidy = () => {
37
+ try {
38
+ if (!had.wal && existsSync(path + '-wal') && statSync(path + '-wal').size === 0)
39
+ unlinkSync(path + '-wal');
40
+ if (!had.shm && existsSync(path + '-shm'))
41
+ unlinkSync(path + '-shm');
42
+ }
43
+ catch { /* leave them; memory.db itself is untouched either way */ }
44
+ };
45
+ let v = 0;
46
+ try {
47
+ const ro = new Database(path, { readonly: true, fileMustExist: true });
48
+ try {
49
+ v = readSchemaVersion(ro);
50
+ }
51
+ finally {
52
+ ro.close();
53
+ }
54
+ }
55
+ catch (e) {
56
+ const code = e?.code ?? '';
57
+ const msg = e?.message ?? String(e);
58
+ // The file vanished between the check and the open: a new DB, as above.
59
+ if (!existsSync(path) && (code === 'SQLITE_CANTOPEN' || code === 'ENOENT' || /unable to open|does not exist/i.test(msg)))
60
+ return;
61
+ // The native addon itself failed: let it surface as such (the hooks turn it into one line).
62
+ if (isNativeLoadError(e))
63
+ throw e;
64
+ // Not a database at all: the normal open's corruption path moves it aside (nothing lost).
65
+ if (code === 'SQLITE_NOTADB' || code === 'SQLITE_CORRUPT' || /not a database|malformed|disk image/i.test(msg))
66
+ return;
67
+ tidy();
68
+ if (code === 'SQLITE_READONLY_ROLLBACK')
69
+ throw new HotJournalError(path);
70
+ // Anything else (SQLITE_BUSY, locked, permission, I/O): we could not check it, so we do not
71
+ // write to it either — fail closed (0.17.1, Codex third review of #15).
72
+ throw new PrecheckError(path, code || msg.split('\n')[0]);
73
+ }
74
+ if (v > 0 && v < MIN_SUPPORTED_SCHEMA) {
75
+ tidy();
76
+ throw new LegacySchemaError(v, path);
77
+ }
78
+ }
13
79
  function openAt(path) {
80
+ precheckBeforeWrite(path);
14
81
  const db = new Database(path);
15
82
  try {
16
- db.pragma('journal_mode = WAL'); // first real read of the file header — throws if it isn't a DB
83
+ // Second line (the read-only precheck is the real gate): refuse before the journal-mode pragma.
84
+ // This is also the first real read of the file — it throws if the file isn't a DB.
85
+ const v = readSchemaVersion(db);
86
+ if (v > 0 && v < MIN_SUPPORTED_SCHEMA)
87
+ throw new LegacySchemaError(v, path);
88
+ db.pragma('journal_mode = WAL');
17
89
  db.pragma('foreign_keys = ON');
18
90
  return db;
19
91
  }
@@ -54,18 +126,82 @@ export function openDb() {
54
126
  throw err; // not a corruption we recognize — surface it
55
127
  }
56
128
  }
129
+ /** Oldest schema this version migrates in place. Older files are refused before any write. */
130
+ export const MIN_SUPPORTED_SCHEMA = 6;
131
+ /** Base class: openDb() refused this file without writing to it. The message says what to do. */
132
+ export class DbRefusedError extends Error {
133
+ }
134
+ /**
135
+ * Thrown for a schema older than MIN_SUPPORTED_SCHEMA (a DB last opened by a 2026-05-or-earlier
136
+ * version). Raised by openDb() from a read-only connection, before any writable connection exists,
137
+ * and again by runMigrations() as a second line.
138
+ *
139
+ * No old version is recommended as a stepping stone: 0.8.0–0.17.0 stop on `no such table:
140
+ * drift_anchors` after partly altering the file, and 0.7.2 has no subcommands — `npx
141
+ * linksee-memory@0.7.2 <anything>` starts its MCP server, whose start-up consolidate can delete
142
+ * original rows (Codex review of PR #15). A migration command for these files is 0.17.2 work.
143
+ */
144
+ export class LegacySchemaError extends DbRefusedError {
145
+ schemaVersion;
146
+ constructor(schemaVersion, dbPath) {
147
+ super(`[linksee-memory] ${dbPath} is at schema ${schemaVersion}; this version migrates schema ${MIN_SUPPORTED_SCHEMA} and newer only. ` +
148
+ `Stopped before writing anything to the file.
149
+ \n` +
150
+ ` 1. Close every Claude Code / Cursor / other client using linksee-memory.
151
+ \n` +
152
+ ` 2. Back up the folder that holds memory.db (copy memory.db and any memory.db-wal / -shm / -journal) and keep the copy.
153
+ \n` +
154
+ ` 3. Do not open this file with another linksee-memory version in the meantime — older versions can delete or half-migrate rows.
155
+ \n` +
156
+ `A migration command for this schema is planned for 0.17.2. To start fresh instead, point LINKSEE_MEMORY_DIR at an empty folder.`);
157
+ this.name = 'LegacySchemaError';
158
+ this.schemaVersion = schemaVersion;
159
+ }
160
+ }
161
+ /** The read-only check could not run (busy, locked, unreadable): refused rather than guessed. */
162
+ export class PrecheckError extends DbRefusedError {
163
+ reason;
164
+ constructor(dbPath, reason) {
165
+ super(`[linksee-memory] could not check ${dbPath} before opening it for writing (${reason}). ` +
166
+ `Stopped before writing anything. Another client may have it open or locked: close other ` +
167
+ `Claude Code / Cursor / linksee-memory processes and try again.`);
168
+ this.name = 'PrecheckError';
169
+ this.reason = reason;
170
+ }
171
+ }
172
+ /** A rollback journal left by an interrupted write: it cannot be read without being rolled back. */
173
+ export class HotJournalError extends DbRefusedError {
174
+ constructor(dbPath) {
175
+ super(`[linksee-memory] ${dbPath} has an unfinished write from an interrupted process (memory.db-journal), ` +
176
+ `so it cannot be checked without changing it. Stopped before writing anything.
177
+ \n` +
178
+ ` Back up the folder that holds memory.db (all memory.db* files) before anything else opens it. ` +
179
+ `A recovery command is planned for 0.17.2.`);
180
+ this.name = 'HotJournalError';
181
+ }
182
+ }
183
+ /** Read meta.schema_version without writing (0 when the table or row is absent). */
184
+ export function readSchemaVersion(db) {
185
+ const metaTable = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
186
+ if (!metaTable?.name)
187
+ return 0;
188
+ const row = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
189
+ return row ? Number(row.value) || 0 : 0;
190
+ }
57
191
  export function runMigrations(db) {
58
192
  const __filename = fileURLToPath(import.meta.url);
59
193
  const schemaPath = join(dirname(__filename), 'schema.sql');
60
194
  const sql = readFileSync(schemaPath, 'utf8');
61
195
  // Safely read current schema version. On a fresh DB the meta table doesn't
62
196
  // exist yet, which is fine — treat that as "version 0, full schema apply".
63
- let currentVersion = 0;
64
- const metaTable = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
65
- if (metaTable?.name) {
66
- const versionRow = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
67
- if (versionRow)
68
- currentVersion = Number(versionRow.value) || 0;
197
+ const currentVersion = readSchemaVersion(db);
198
+ // 0.17.1 (L-1-106 / audit F3): refuse schema 1–5 BEFORE any write. Their path through here
199
+ // (v5 → v6 generated columns, then the v5 entity merge running after the version has already
200
+ // been bumped to 16, with no transaction around it) can leave a half-migrated file. A safe,
201
+ // tested migration is 0.17.2 work. openDb() already refused these before any write; this is
202
+ // the second line for callers that hand in their own connection.
203
+ if (currentVersion > 0 && currentVersion < MIN_SUPPORTED_SCHEMA) {
204
+ throw new LegacySchemaError(currentVersion, getDbPath());
69
205
  }
70
206
  // v3 → v4: rebuild memories_fts with trigram tokenizer for JP/CJK support.
71
207
  // Only runs when upgrading an existing DB from schema v1-3.
@@ -128,7 +264,12 @@ export function runMigrations(db) {
128
264
  // detector/dashboard (which read the original columns + status active/retired) are unaffected.
129
265
  // `lifecycle` carries the rich state; `status` stays the coarse scan-gate. New tables
130
266
  // (reality_events, memory_write_candidates) are created by db.exec(sql) below (CREATE IF NOT EXISTS).
131
- if (currentVersion > 0 && currentVersion < 9) {
267
+ // 0.17.1 (L-1-106 / audit F3): drift_anchors only exists from v8 on. On an older DB the table is
268
+ // missing, PRAGMA table_info returns nothing, and every ALTER below threw "no such table" — so
269
+ // any pre-0.12 DB could not start. If the table is absent, skip: db.exec(sql) below creates it
270
+ // with all of these columns.
271
+ const hasDriftAnchors = !!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='drift_anchors'").get();
272
+ if (currentVersion > 0 && currentVersion < 9 && hasDriftAnchors) {
132
273
  const have = new Set(db.prepare('PRAGMA table_info(drift_anchors)').all().map((c) => c.name));
133
274
  const addCol = (name, ddl) => {
134
275
  if (!have.has(name))
@@ -13,3 +13,12 @@ export declare function consolidate(db: Database.Database, opts?: {
13
13
  scope?: 'all' | 'session';
14
14
  min_age_days?: number;
15
15
  }): ConsolidateResult;
16
+ /**
17
+ * Should the MCP server run consolidate on its own at start-up? (0.17.1, L-1-106 / audit F1)
18
+ *
19
+ * No, unless the user asked: consolidate deletes the original rows (keeping a 3 × 200-char
20
+ * summary) and their edges, so it must not run without an explicit opt-in.
21
+ * Opt in with LINKSEE_AUTO_CONSOLIDATE=1|true|on|weekly, or `--auto-consolidate` on the server
22
+ * command line. The weekly gate inside the server still applies once enabled.
23
+ */
24
+ export declare function autoConsolidateEnabled(env: Record<string, string | undefined>, argv: readonly string[]): boolean;
@@ -186,4 +186,18 @@ export function consolidate(db, opts = {}) {
186
186
  }
187
187
  return result;
188
188
  }
189
+ /**
190
+ * Should the MCP server run consolidate on its own at start-up? (0.17.1, L-1-106 / audit F1)
191
+ *
192
+ * No, unless the user asked: consolidate deletes the original rows (keeping a 3 × 200-char
193
+ * summary) and their edges, so it must not run without an explicit opt-in.
194
+ * Opt in with LINKSEE_AUTO_CONSOLIDATE=1|true|on|weekly, or `--auto-consolidate` on the server
195
+ * command line. The weekly gate inside the server still applies once enabled.
196
+ */
197
+ export function autoConsolidateEnabled(env, argv) {
198
+ if (argv.includes('--auto-consolidate'))
199
+ return true;
200
+ const v = (env.LINKSEE_AUTO_CONSOLIDATE ?? '').trim().toLowerCase();
201
+ return v === '1' || v === 'true' || v === 'on' || v === 'yes' || v === 'weekly';
202
+ }
189
203
  //# sourceMappingURL=consolidate.js.map
@@ -16,7 +16,53 @@ export declare const GUARD_EVENTS: readonly ["SessionStart", "PreToolUse"];
16
16
  export type GuardEvent = (typeof GUARD_EVENTS)[number];
17
17
  /** The bin every wiring form resolves to; used as the idempotency key. */
18
18
  export declare const GUARD_BIN = "linksee-memory-guard";
19
+ /** The npx form setup wrote before 0.17.1. Still the fallback when no stable install exists. */
19
20
  export declare const GUARD_COMMAND = "npx -y linksee-memory guard";
21
+ export declare const SYNC_COMMAND = "npx -y linksee-memory sync";
22
+ export type HookKind = 'guard' | 'sync';
23
+ export type HookCommands = Record<HookKind, string>;
24
+ export declare const NPX_HOOK_COMMANDS: HookCommands;
25
+ /**
26
+ * Marker setup appends to every direct-node hook it writes. It is an ordinary trailing argument
27
+ * (the hook scripts ignore argv), so it survives cmd.exe and sh alike — a `#` comment would not
28
+ * (cmd.exe has no inline comments). Only a command carrying it is treated as setup-owned.
29
+ */
30
+ export declare const MANAGED_MARKER = "--linksee-managed";
31
+ /**
32
+ * Direct `node` form (0.17.1, L-1-106 / audit F11): `npx -y` costs 6–9 s per call on a warm
33
+ * cache (npm start-up + a registry check), against an 8 s PreToolUse timeout — so the guard
34
+ * could time out and silently not fire. `"<node>" "<root>/dist/bin/<bin>.js" --linksee-managed`
35
+ * starts in well under a second.
36
+ *
37
+ * Shells: Claude Code runs a hook command through cmd.exe on Windows and through sh on POSIX
38
+ * (PowerShell is not used for hooks — assumed here; under PowerShell this form would need `&`).
39
+ * Double quotes protect spaces in both. They do NOT neutralise `$` or backticks (sh) or `%`
40
+ * (cmd.exe), and a path containing `"` cannot be quoted at all — see `shellSafePath`; setup falls
41
+ * back to the npx form for such paths instead of writing a command that might expand.
42
+ */
43
+ export declare function nodeHookCommands(nodePath: string, packageRoot: string): HookCommands;
44
+ /** Can this path go inside double quotes in both cmd.exe and sh without being expanded? */
45
+ export declare function shellSafePath(p: string): boolean;
46
+ /**
47
+ * Is this command one setup wrote — (a) the exact 0.17.0-and-earlier npx string, or (b) the
48
+ * 0.17.1+ direct form carrying MANAGED_MARKER? Anything else (wrappers, unquoted paths, extra
49
+ * flags, someone else's script) is not ours to change.
50
+ */
51
+ export declare function setupWrittenKind(command: string | undefined): HookKind | null;
52
+ /**
53
+ * Point the setup-written hooks of the given kinds at `commands`. Exec-form hooks (`args`), other
54
+ * tools' hooks and hand-edited commands are never touched. Only `command` changes — matcher,
55
+ * timeout and any other field stay. Mutates `settings`; returns the replaced commands.
56
+ */
57
+ export declare function rewireLegacyHooks(settings: ClaudeSettings, commands: HookCommands, kinds?: readonly HookKind[]): {
58
+ replaced: string[];
59
+ };
60
+ /**
61
+ * Hooks that look like ours (they run the guard or the sync script) but were not written by setup —
62
+ * hand-wired paths, wrappers, exec form. setup leaves them alone and lists them so the user knows.
63
+ */
64
+ export declare function unmanagedLinkseeHooks(settings: ClaudeSettings): string[];
65
+ export declare function guardHooks(command?: string): Record<GuardEvent, HookEntry>;
20
66
  export declare const GUARD_HOOKS: Record<GuardEvent, HookEntry>;
21
67
  /**
22
68
  * Is one of OUR hooks of `kind` already wired for this event?
@@ -48,7 +94,7 @@ export declare function guardFullyWired(settings: ClaudeSettings): boolean;
48
94
  * Add the guard to any event it does not already own. Mutates and returns `settings`, plus the
49
95
  * events that were actually added (empty when it was already wired).
50
96
  */
51
- export declare function wireGuard(settings: ClaudeSettings): {
97
+ export declare function wireGuard(settings: ClaudeSettings, command?: string): {
52
98
  settings: ClaudeSettings;
53
99
  added: GuardEvent[];
54
100
  };
@@ -10,17 +10,119 @@
10
10
  export const GUARD_EVENTS = ['SessionStart', 'PreToolUse'];
11
11
  /** The bin every wiring form resolves to; used as the idempotency key. */
12
12
  export const GUARD_BIN = 'linksee-memory-guard';
13
+ /** The npx form setup wrote before 0.17.1. Still the fallback when no stable install exists. */
13
14
  export const GUARD_COMMAND = 'npx -y linksee-memory guard';
14
- export const GUARD_HOOKS = {
15
- SessionStart: {
16
- matcher: 'startup|resume|compact',
17
- hooks: [{ type: 'command', command: GUARD_COMMAND, timeout: 15 }],
18
- },
19
- PreToolUse: {
20
- matcher: 'Edit|Write|Bash',
21
- hooks: [{ type: 'command', command: GUARD_COMMAND, timeout: 8 }],
22
- },
15
+ export const SYNC_COMMAND = 'npx -y linksee-memory sync';
16
+ export const NPX_HOOK_COMMANDS = { guard: GUARD_COMMAND, sync: SYNC_COMMAND };
17
+ /**
18
+ * Marker setup appends to every direct-node hook it writes. It is an ordinary trailing argument
19
+ * (the hook scripts ignore argv), so it survives cmd.exe and sh alike — a `#` comment would not
20
+ * (cmd.exe has no inline comments). Only a command carrying it is treated as setup-owned.
21
+ */
22
+ export const MANAGED_MARKER = '--linksee-managed';
23
+ /**
24
+ * Direct `node` form (0.17.1, L-1-106 / audit F11): `npx -y` costs 6–9 s per call on a warm
25
+ * cache (npm start-up + a registry check), against an 8 s PreToolUse timeout — so the guard
26
+ * could time out and silently not fire. `"<node>" "<root>/dist/bin/<bin>.js" --linksee-managed`
27
+ * starts in well under a second.
28
+ *
29
+ * Shells: Claude Code runs a hook command through cmd.exe on Windows and through sh on POSIX
30
+ * (PowerShell is not used for hooks — assumed here; under PowerShell this form would need `&`).
31
+ * Double quotes protect spaces in both. They do NOT neutralise `$` or backticks (sh) or `%`
32
+ * (cmd.exe), and a path containing `"` cannot be quoted at all — see `shellSafePath`; setup falls
33
+ * back to the npx form for such paths instead of writing a command that might expand.
34
+ */
35
+ export function nodeHookCommands(nodePath, packageRoot) {
36
+ const fwd = (p) => p.replace(/\\/g, '/');
37
+ const bin = (file) => `"${fwd(nodePath)}" "${fwd(packageRoot).replace(/\/$/, '')}/dist/bin/${file}" ${MANAGED_MARKER}`;
38
+ return { guard: bin('guard-hook.js'), sync: bin('sync-session.js') };
39
+ }
40
+ /** Can this path go inside double quotes in both cmd.exe and sh without being expanded? */
41
+ export function shellSafePath(p) {
42
+ return !/["$`%!\r\n]/.test(p);
43
+ }
44
+ /** Exactly the npx strings setup wrote up to 0.17.0. */
45
+ const LEGACY_NPX = {
46
+ guard: 'npx -y linksee-memory guard',
47
+ sync: 'npx -y linksee-memory sync',
23
48
  };
49
+ /** The form setup itself writes from 0.17.1 on — quoted node, quoted script, the marker. */
50
+ const MANAGED_NODE_FORM = /^"[^"]+" "[^"]+\/dist\/bin\/(guard-hook|sync-session)\.js" --linksee-managed$/;
51
+ /**
52
+ * Is this command one setup wrote — (a) the exact 0.17.0-and-earlier npx string, or (b) the
53
+ * 0.17.1+ direct form carrying MANAGED_MARKER? Anything else (wrappers, unquoted paths, extra
54
+ * flags, someone else's script) is not ours to change.
55
+ */
56
+ export function setupWrittenKind(command) {
57
+ if (typeof command !== 'string')
58
+ return null;
59
+ const c = command.trim();
60
+ for (const kind of ['guard', 'sync'])
61
+ if (LEGACY_NPX[kind] === c)
62
+ return kind;
63
+ const m = MANAGED_NODE_FORM.exec(c);
64
+ if (m)
65
+ return m[1] === 'guard-hook' ? 'guard' : 'sync';
66
+ return null;
67
+ }
68
+ function eachCommandHook(settings, fn) {
69
+ for (const entries of Object.values(settings.hooks ?? {})) {
70
+ if (!Array.isArray(entries))
71
+ continue;
72
+ for (const entry of entries)
73
+ for (const h of entry?.hooks ?? [])
74
+ if (h && h.type === 'command')
75
+ fn(h);
76
+ }
77
+ }
78
+ /**
79
+ * Point the setup-written hooks of the given kinds at `commands`. Exec-form hooks (`args`), other
80
+ * tools' hooks and hand-edited commands are never touched. Only `command` changes — matcher,
81
+ * timeout and any other field stay. Mutates `settings`; returns the replaced commands.
82
+ */
83
+ export function rewireLegacyHooks(settings, commands, kinds = ['guard', 'sync']) {
84
+ const replaced = [];
85
+ eachCommandHook(settings, (h) => {
86
+ if (Array.isArray(h.args) && h.args.length)
87
+ return;
88
+ const kind = setupWrittenKind(h.command);
89
+ if (!kind || !kinds.includes(kind) || h.command === commands[kind])
90
+ return;
91
+ replaced.push(h.command);
92
+ h.command = commands[kind];
93
+ });
94
+ return { replaced };
95
+ }
96
+ /**
97
+ * Hooks that look like ours (they run the guard or the sync script) but were not written by setup —
98
+ * hand-wired paths, wrappers, exec form. setup leaves them alone and lists them so the user knows.
99
+ */
100
+ export function unmanagedLinkseeHooks(settings) {
101
+ const out = [];
102
+ eachCommandHook(settings, (h) => {
103
+ const hay = [h.command, ...(h.args ?? [])].filter((x) => typeof x === 'string').join(' ');
104
+ const looksOurs = /guard-hook|sync-session/.test(hay) || (/linksee-memory/.test(hay) && /\b(guard|sync)\b/.test(hay));
105
+ if (!looksOurs)
106
+ return;
107
+ if ((!h.args || !h.args.length) && setupWrittenKind(h.command))
108
+ return;
109
+ out.push(hay);
110
+ });
111
+ return out;
112
+ }
113
+ export function guardHooks(command = GUARD_COMMAND) {
114
+ return {
115
+ SessionStart: {
116
+ matcher: 'startup|resume|compact',
117
+ hooks: [{ type: 'command', command, timeout: 15 }],
118
+ },
119
+ PreToolUse: {
120
+ matcher: 'Edit|Write|Bash',
121
+ hooks: [{ type: 'command', command, timeout: 8 }],
122
+ },
123
+ };
124
+ }
125
+ export const GUARD_HOOKS = guardHooks();
24
126
  /** Everything a hook entry could carry an identifier in: `command`, or `args` for the exec form. */
25
127
  function hookHaystack(h) {
26
128
  return [h?.command, ...(h?.args ?? [])].filter((x) => typeof x === 'string').join(' ');
@@ -69,14 +171,15 @@ export function guardFullyWired(settings) {
69
171
  * Add the guard to any event it does not already own. Mutates and returns `settings`, plus the
70
172
  * events that were actually added (empty when it was already wired).
71
173
  */
72
- export function wireGuard(settings) {
174
+ export function wireGuard(settings, command = GUARD_COMMAND) {
73
175
  const hooks = (settings.hooks ??= {});
74
176
  const added = [];
177
+ const wanted = guardHooks(command);
75
178
  for (const ev of GUARD_EVENTS) {
76
179
  if (!Array.isArray(hooks[ev]))
77
180
  hooks[ev] = [];
78
181
  if (!guardWiredFor(settings, ev)) {
79
- hooks[ev].push(GUARD_HOOKS[ev]);
182
+ hooks[ev].push(wanted[ev]);
80
183
  added.push(ev);
81
184
  }
82
185
  }
@@ -0,0 +1,41 @@
1
+ import { type HookCommands } from './guard-wiring.js';
2
+ export type HookRuntime = {
3
+ commands: HookCommands;
4
+ /** 'direct' = this install is stable; 'pinned' = installed under runtime/; 'npx' = fallback. */
5
+ mode: 'direct' | 'pinned' | 'npx';
6
+ root?: string;
7
+ note?: string;
8
+ /** runtime/ folder and the version kept there, when pinned (setup reports where runtimes live). */
9
+ runtimeBase?: string;
10
+ version?: string;
11
+ /** Size of the pinned runtime in bytes, when one is in use. */
12
+ bytes?: number;
13
+ };
14
+ /** Is this package root inside a cache that npm / pnpm / bun may rebuild or delete? */
15
+ export declare function isEphemeralRoot(packageRoot: string): boolean;
16
+ /** Can a node process load the native dependency from this root? (the part most likely to break) */
17
+ export declare function verifyRoot(root: string, nodePath: string): boolean;
18
+ /** Locate npm's CLI script so it can be run with this node, without a shell. */
19
+ export declare function findNpmCli(nodePath: string, env?: NodeJS.ProcessEnv): string | null;
20
+ export type Installer = (spec: string, prefix: string, nodePath: string) => {
21
+ ok: boolean;
22
+ detail?: string;
23
+ };
24
+ /** `npm install --prefix <prefix> --no-save --omit=dev <spec>` with this node, no shell. */
25
+ export declare const npmInstall: Installer;
26
+ export declare function dirBytes(dir: string): number;
27
+ export declare function formatBytes(n: number): string;
28
+ export type ResolveOpts = {
29
+ packageRoot: string;
30
+ nodePath: string;
31
+ memoryDir: string;
32
+ version: string;
33
+ /** What to install; defaults to linksee-memory@<version>. */
34
+ spec?: string;
35
+ dryRun?: boolean;
36
+ /** Injected in tests; default = real child-process load check. */
37
+ verify?: (root: string, nodePath: string) => boolean;
38
+ /** Injected in tests; default = npm install with this node. */
39
+ install?: Installer;
40
+ };
41
+ export declare function resolveHookRuntime(o: ResolveOpts): HookRuntime;