@remnic/plugin-claude-code 9.63.6 → 9.63.7

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,957 +1,49 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Remnic unified Claude Code hook runner (issue #1518).
3
+ * Remnic unified Claude Code hook runner (issues #1518, #2483).
4
4
  *
5
- * A single cross-platform Node.js implementation of all four Claude Code
6
- * hooks. Thin `.sh` (POSIX) and `.ps1` (Windows) wrappers exec this file with
7
- * the event name as argv[2]:
5
+ * Thin per-host config for the shared runner in remnic-hook-core.cjs (kept
6
+ * byte-identical across host packages; canonical source:
7
+ * scripts/hook-runner/remnic-hook-core.cjs run `npm run sync:hook-runner`
8
+ * after editing). The thin `.sh` (POSIX) and `.ps1` (Windows) wrappers exec
9
+ * this file with the event name as argv[2]:
8
10
  *
9
11
  * node remnic-cc-hook.cjs <event>
10
12
  *
11
13
  * Events: session-start | user-prompt-recall | post-tool-observe | session-end
12
14
  *
13
- * This is a faithful port of the original four bash scripts — same endpoints,
14
- * env vars, token resolution, cursor/lock hardening, engram→remnic migration,
15
- * daemon health/auto-start, and git coding-context projectId derivation. Node
16
- * replaces the per-script `node -e` one-liners and Unix tools
17
- * (curl/git/sed/mktemp/…) so the exact same logic runs on Windows, macOS, and
18
- * Linux. This mirrors the proven @remnic/plugin-codex runner (issue #1440);
19
- * the only differences are the client-id header, token connector priority,
20
- * log tags, and the absence of Codex-native memory materialization.
21
- *
22
- * Security note (issue #1518 "guard shell interpolation"): every value that
23
- * originates from the hook payload (session id, cwd, transcript path, prompt,
24
- * tool name) is passed to child processes via argv or stdin — NEVER via a
25
- * string-interpolated shell command. `spawn`/`spawnSync` are called with
26
- * fixed literal argument arrays and `shell: false` (except on Windows, where
27
- * `.cmd` shims require `shell: true` with fixed literal args), so a payload
28
- * field containing shell metacharacters cannot achieve command injection.
15
+ * NOTE: Claude Code does not currently emit a Stop/SessionEnd event. The
16
+ * session-end handler runs only when invoked manually or once Claude Code
17
+ * adds the event. It is kept so the final-flush + cursor-cleanup parity with
18
+ * the Codex runner is in place from day one (issue #1518). Claude Code has
19
+ * no PreCompact/materialization equivalent, so both stay disabled here but
20
+ * REMNIC_DAEMON_URL/HTTPS routing is inherited from the shared core.
29
21
  *
30
22
  * Fail-open everywhere: any unexpected error degrades to `{"continue":true}`.
31
23
  */
32
24
 
33
25
  "use strict";
34
26
 
35
- const fs = require("fs");
36
- const os = require("os");
37
- const path = require("path");
38
- const http = require("http");
39
- const { execFileSync, spawn, spawnSync } = require("child_process");
40
-
41
- const HOME = process.env.HOME || process.env.USERPROFILE || os.homedir();
42
- const HOST = process.env.REMNIC_HOST || process.env.ENGRAM_HOST || "127.0.0.1";
43
- const PORT = process.env.REMNIC_PORT || process.env.ENGRAM_PORT || "4318";
44
-
45
- // Internal re-entrant mode: post-tool-observe spawns a detached copy of itself
46
- // so the (slow) observe runs in the background and never blocks Claude Code
47
- // past the short PostToolUse timeout — mirroring the original `( … ) & disown`.
48
- const OBSERVE_WORKER = "__observe-worker__";
49
-
50
- const LOG_FILES = {
51
- "session-start": "remnic-session-recall.log",
52
- "user-prompt-recall": "remnic-user-prompt-recall.log",
53
- "post-tool-observe": "remnic-post-tool-observe.log",
54
- "session-end": "remnic-cc-session-end.log",
55
- };
56
- const LOG_TAGS = {
57
- "session-start": "cc-session-start",
58
- "user-prompt-recall": "cc-user-prompt",
59
- "post-tool-observe": "cc-post-tool",
60
- "session-end": "cc-stop",
61
- };
62
-
63
- function makeLogger(event) {
64
- const file = path.join(HOME, ".remnic", "logs", LOG_FILES[event] || "remnic-cc-hook.log");
65
- const tag = LOG_TAGS[event] || "cc-hook";
66
- try {
67
- fs.mkdirSync(path.dirname(file), { recursive: true });
68
- } catch {
69
- /* best effort */
70
- }
71
- return (msg) => {
72
- try {
73
- const ts = new Date().toISOString().replace("T", " ").slice(0, 19);
74
- fs.appendFileSync(file, `${ts} [${tag}] ${msg}\n`);
75
- } catch {
76
- /* logging must never throw */
77
- }
78
- };
79
- }
80
-
81
- let emitted = false;
82
- function emit(obj) {
83
- process.stdout.write(`${JSON.stringify(obj)}\n`);
84
- emitted = true;
85
- }
86
-
87
- function readStdin() {
88
- // Always read the real stdin. The foreground hook gets its payload from
89
- // Claude Code on fd 0; the detached observe worker gets it from the pipe the
90
- // foreground writes. We deliberately do NOT consult an env var here — an
91
- // inherited REMNIC_HOOK_INPUT in the parent environment would otherwise
92
- // override the piped payload and the worker could observe stale/empty input.
93
- try {
94
- return fs.readFileSync(0, "utf8");
95
- } catch {
96
- return "";
97
- }
98
- }
99
-
100
- function parseInput(raw) {
101
- try {
102
- const d = JSON.parse(raw);
103
- return d && typeof d === "object" ? d : {};
104
- } catch {
105
- return {};
106
- }
107
- }
108
-
109
- // ── engram → remnic migration (CLAUDE.md rule #9) ──────────────────────────
110
- function ensureMigrated() {
111
- try {
112
- if (fs.existsSync(path.join(HOME, ".remnic", ".migrated-from-engram"))) return;
113
- const hasEngram =
114
- fs.existsSync(path.join(HOME, ".engram")) ||
115
- fs.existsSync(path.join(HOME, ".config", "engram", "config.json"));
116
- if (!hasEngram) return;
117
- // Try `remnic` first, fall through to legacy `engram` when missing on PATH.
118
- // Pre-check PATH with onPath() (which is .cmd/.exe-aware on Windows) rather
119
- // than relying on spawnSync ENOENT — under `shell: true` a missing command
120
- // yields a non-zero shell exit, not ENOENT, so an exit-code check couldn't
121
- // distinguish "missing" from "migration failed".
122
- // On Windows the CLIs are `.cmd` shims, which Node can only launch via a
123
- // shell. Timeout is 5 min so a large migration can complete. Args are
124
- // fixed literals — safe under a shell.
125
- for (const bin of ["remnic", "engram"]) {
126
- if (!onPath(bin)) continue;
127
- spawnSync(bin, ["migrate"], {
128
- stdio: "ignore",
129
- timeout: 300000,
130
- shell: process.platform === "win32",
131
- windowsHide: true,
132
- });
133
- return;
134
- }
135
- } catch {
136
- /* migration is best effort */
137
- }
138
- }
139
-
140
- // PATH lookup helper (cross-platform equivalent of bash `command -v`).
141
- // Returns true when an executable named `bin` is reachable via $PATH. Used
142
- // before async `spawn()` calls so the remnic → engram fallthrough actually
143
- // happens when only the legacy CLI is installed — `spawn` emits ENOENT
144
- // asynchronously via 'error', so a naive try/break can't see it.
145
- function onPath(bin) {
146
- const PATH = process.env.PATH || process.env.Path || process.env.path || "";
147
- const sep = process.platform === "win32" ? ";" : ":";
148
- // Windows resolves names without an extension by appending PATHEXT entries.
149
- const exts =
150
- process.platform === "win32"
151
- ? (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD")
152
- .split(";")
153
- .map((e) => e.trim())
154
- .filter(Boolean)
155
- : [""];
156
- for (const dir of PATH.split(sep)) {
157
- if (!dir) continue;
158
- for (const ext of exts) {
159
- try {
160
- const candidate = path.join(dir, bin + ext);
161
- const info = fs.statSync(candidate);
162
- if (info.isFile()) return true;
163
- } catch {
164
- /* try next */
165
- }
166
- }
167
- }
168
- return false;
169
- }
170
-
171
- // ── token resolution (per-plugin token store, then env) ────────────────────
172
- // Env precedence is primary-before-legacy per AGENTS.md §9: the two current
173
- // names (OPENCLAW_REMNIC_ACCESS_TOKEN, REMNIC_AUTH_TOKEN) before the two
174
- // legacy aliases (OPENCLAW_ENGRAM_ACCESS_TOKEN, ENGRAM_AUTH_TOKEN), so a
175
- // stale leftover from a pre-rename install cannot outrank the credential the
176
- // daemon is actually running with. REMNIC_AUTH_TOKEN matters because the
177
- // documented standalone-server setup authenticates the daemon with it alone
178
- // and never mints a connector token — without it the health probe 401s and
179
- // the hook wrongly reports "daemon not running", silently skipping
180
- // recall/observe.
181
- function resolveToken() {
182
- for (const file of [
183
- path.join(HOME, ".remnic", "tokens.json"),
184
- path.join(HOME, ".engram", "tokens.json"),
185
- ]) {
186
- try {
187
- if (!fs.existsSync(file)) continue;
188
- const store = JSON.parse(fs.readFileSync(file, "utf8"));
189
- const tokens = Array.isArray(store.tokens) ? store.tokens : [];
190
- const byConnector = (c) => tokens.find((t) => t && t.connector === c);
191
- const tok =
192
- (byConnector("claude-code") || {}).token ||
193
- (byConnector("openclaw") || {}).token ||
194
- store["claude-code"] ||
195
- store["openclaw"] ||
196
- "";
197
- if (tok) return tok;
198
- } catch {
199
- /* try next file */
200
- }
201
- }
202
- return (
203
- process.env.OPENCLAW_REMNIC_ACCESS_TOKEN ||
204
- process.env.REMNIC_AUTH_TOKEN ||
205
- process.env.OPENCLAW_ENGRAM_ACCESS_TOKEN ||
206
- process.env.ENGRAM_AUTH_TOKEN ||
207
- ""
208
- );
209
- }
210
-
211
- // ── HTTP helpers — return a real success signal (2xx) so callers can decide
212
- // whether to advance/clear the cursor. ─────────────────────────────────────
213
- function httpPost(urlPath, token, bodyObj, timeoutMs) {
214
- return new Promise((resolve) => {
215
- let data;
216
- try {
217
- // Namespace targeting for namespaced daemons: when REMNIC_NAMESPACE (or
218
- // ENGRAM_NAMESPACE) is set, include it in the request body. On the REST
219
- // surface the namespace is read from the body, not a header, and the
220
- // "claude-code" client id otherwise resolves to the adapter's own
221
- // (empty) namespace — so recall/observe silently return nothing. Opt-in:
222
- // when the env var is unset this is a no-op and behaviour is unchanged.
223
- // An explicit bodyObj.namespace still takes precedence.
224
- const ns = process.env.REMNIC_NAMESPACE || process.env.ENGRAM_NAMESPACE;
225
- const outBody =
226
- ns && bodyObj && typeof bodyObj === "object" && !Array.isArray(bodyObj)
227
- ? { namespace: ns, ...bodyObj }
228
- : bodyObj;
229
- data = Buffer.from(JSON.stringify(outBody), "utf8");
230
- } catch {
231
- resolve({ ok: false, status: 0, body: "" });
232
- return;
233
- }
234
- const req = http.request(
235
- {
236
- host: HOST,
237
- port: PORT,
238
- path: urlPath,
239
- method: "POST",
240
- headers: {
241
- Authorization: `Bearer ${token}`,
242
- "Content-Type": "application/json",
243
- "X-Engram-Client-Id": "claude-code",
244
- "Content-Length": data.length,
245
- },
246
- },
247
- (res) => {
248
- let body = "";
249
- res.setEncoding("utf8");
250
- res.on("data", (c) => {
251
- body += c;
252
- });
253
- res.on("end", () =>
254
- resolve({
255
- ok: res.statusCode >= 200 && res.statusCode < 300,
256
- status: res.statusCode || 0,
257
- body,
258
- }),
259
- );
260
- },
261
- );
262
- req.on("error", () => resolve({ ok: false, status: 0, body: "" }));
263
- req.setTimeout(timeoutMs, () => {
264
- req.destroy();
265
- resolve({ ok: false, status: 0, body: "" });
266
- });
267
- req.write(data);
268
- req.end();
269
- });
270
- }
271
-
272
- // `token` is the caller's already-resolved credential, NOT a second
273
- // resolveToken() call: the probe must authenticate with the exact bearer the
274
- // operation it gates will send. Re-resolving could pick up a rotated
275
- // tokens.json (or an inherited REMNIC_HOOK_TOKEN the foreground handlers
276
- // ignore) and green-light a probe whose recall then 401s.
277
- //
278
- // When the daemon has an auth token configured (REMNIC_AUTH_TOKEN), every
279
- // route — including /engram/v1/health — returns 401 to unauthenticated
280
- // requests, so an unauthenticated probe makes the hook wrongly report
281
- // "daemon not running" and skip recall/observe. Unauthenticated daemons
282
- // ignore the header.
283
- function httpHealthy(timeoutMs, token) {
284
- return new Promise((resolve) => {
285
- const req = http.request(
286
- {
287
- host: HOST,
288
- port: PORT,
289
- path: "/engram/v1/health",
290
- method: "GET",
291
- headers: token ? { Authorization: `Bearer ${token}` } : {},
292
- },
293
- (res) => {
294
- res.resume();
295
- resolve(res.statusCode >= 200 && res.statusCode < 300);
296
- },
297
- );
298
- req.on("error", () => resolve(false));
299
- req.setTimeout(timeoutMs, () => {
300
- req.destroy();
301
- resolve(false);
302
- });
303
- req.end();
304
- });
305
- }
306
-
307
- // ── git coding-context (mirrors @remnic/core git-context.ts) ───────────────
308
- function git(args, cwd) {
309
- try {
310
- return execFileSync("git", args, {
311
- cwd,
312
- encoding: "utf8",
313
- timeout: 5000,
314
- stdio: ["ignore", "pipe", "ignore"],
315
- }).trim();
316
- } catch {
317
- return "";
318
- }
319
- }
320
-
321
- function stableHash(input) {
322
- let hash = 0x811c9dc5;
323
- for (let i = 0; i < input.length; i++) {
324
- hash ^= input.charCodeAt(i);
325
- hash = Math.imul(hash, 0x01000193) >>> 0;
326
- }
327
- return hash.toString(16).padStart(8, "0");
328
- }
329
-
330
- // Mirrors packages/remnic-core/src/coding/git-context.ts normalizeOriginUrl.
331
- // Keep in sync so the hook-computed projectId matches the daemon's.
332
- function normalizeOriginUrl(raw) {
333
- let u = (raw || "").trim();
334
- if (!u) return "";
335
- if (/\.git$/i.test(u)) u = u.slice(0, -4);
336
- if (/^[A-Za-z]:[\\/]/.test(u)) return u.toLowerCase();
337
- const proto = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?(\[[^\]]+\]|[^/:]*)(?::(\d+))?(\/.*)?$/i.exec(u);
338
- if (proto) {
339
- let host = proto[1] || "";
340
- const wasBracketed = host.startsWith("[") && host.endsWith("]");
341
- if (wasBracketed) host = host.slice(1, -1);
342
- const port = proto[2];
343
- const p = (proto[3] || "").replace(/^\/+/, "");
344
- const hostPort = port
345
- ? wasBracketed
346
- ? "[" + host + "]:" + port
347
- : host + ":" + port
348
- : host;
349
- const prefix = hostPort.length > 0 ? hostPort : "localhost";
350
- return (prefix + "/" + p).toLowerCase();
351
- }
352
- const scp = /^(?:([^@\s/]+)@)?(\[[^\]]+\]|[^:@\s/]+):(.+)$/.exec(u);
353
- if (scp) {
354
- let host = scp[2] || "";
355
- if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
356
- const p = scp[3] || "";
357
- if (p.startsWith("//")) return u.toLowerCase();
358
- return (host + "/" + p.replace(/^\/+/, "")).toLowerCase();
359
- }
360
- return u.toLowerCase();
361
- }
362
-
363
- function resolveCodingContext(cwd) {
364
- try {
365
- if (!cwd || !fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) return null;
366
- const top = git(["-C", cwd, "rev-parse", "--show-toplevel"], cwd);
367
- if (!top) return null;
368
- let branch = git(["-C", top, "rev-parse", "--abbrev-ref", "HEAD"], top);
369
- if (branch === "HEAD") branch = "";
370
- const origin = git(["-C", top, "remote", "get-url", "origin"], top);
371
- const defRef = git(["-C", top, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], top);
372
- const defaultBranch = defRef ? defRef.replace(/^refs\/remotes\/origin\//, "") : "";
373
- const normalized = normalizeOriginUrl(origin);
374
- const projectId = normalized ? "origin:" + stableHash(normalized) : "root:" + stableHash(top);
375
- return {
376
- projectId,
377
- branch: branch || null,
378
- rootPath: top,
379
- defaultBranch: defaultBranch || null,
380
- };
381
- } catch {
382
- return null;
383
- }
384
- }
385
-
386
- // ── transcript parsing ─────────────────────────────────────────────────────
387
- function parseTranscript(transcriptPath) {
388
- const lines = fs.readFileSync(transcriptPath, "utf8").split("\n").filter(Boolean);
389
- const messages = [];
390
- for (const line of lines) {
391
- try {
392
- const entry = JSON.parse(line);
393
- if (entry.type !== "user" && entry.type !== "assistant") continue;
394
- const msg = entry.message;
395
- if (!msg || typeof msg !== "object") continue;
396
- const role = msg.role;
397
- if (role !== "user" && role !== "assistant") continue;
398
- let text = "";
399
- if (typeof msg.content === "string") text = msg.content.trim();
400
- else if (Array.isArray(msg.content)) {
401
- text = msg.content
402
- .filter((b) => b.type === "text" && b.text)
403
- .map((b) => b.text.trim())
404
- .join("\n")
405
- .trim();
406
- }
407
- if (text) messages.push({ role, content: text });
408
- } catch {
409
- /* skip malformed line */
410
- }
411
- }
412
- return messages;
413
- }
414
-
415
- // ── cursor / lock state hardening (post-tool + session-end) ────────────────
416
- const SELF_UID = typeof process.getuid === "function" ? process.getuid() : null;
417
-
418
- function ownedByUs(info) {
419
- return SELF_UID === null || info.uid === SELF_UID;
420
- }
421
-
422
- // Returns { cursorFile, lockFile } or null if the state dir is unsafe.
423
- function resolveState(sessionId, log) {
424
- const stateHome = process.env.XDG_STATE_HOME || path.join(HOME, ".local", "state");
425
- const stateDir = path.join(stateHome, "remnic", "hooks");
426
- try {
427
- fs.mkdirSync(stateDir, { recursive: true });
428
- } catch {
429
- return null;
430
- }
431
- try {
432
- const info = fs.lstatSync(stateDir);
433
- if (info.isSymbolicLink() || !info.isDirectory()) {
434
- log(`unsafe state directory ${stateDir}`);
435
- return null;
436
- }
437
- if (!ownedByUs(info)) {
438
- log(`unsafe state directory ${stateDir}`);
439
- return null;
440
- }
441
- if ((info.mode & 0o077) !== 0) {
442
- try {
443
- fs.chmodSync(stateDir, 0o700);
444
- } catch {
445
- /* best effort */
446
- }
447
- }
448
- } catch {
449
- return null;
450
- }
451
- let cursorFile = path.join(stateDir, `remnic-cursor-${sessionId}`);
452
- let lockFile = path.join(stateDir, `remnic-lock-${sessionId}.d`);
453
- const legacyCursor = path.join(stateDir, `engram-cursor-${sessionId}`);
454
- const legacyLock = path.join(stateDir, `engram-lock-${sessionId}.d`);
455
- // Mid-migration fallback: adopt the legacy engram-* cursor/lock so we don't
456
- // re-observe the whole transcript (CLAUDE.md rule #9).
457
- if (!fs.existsSync(cursorFile) && (fs.existsSync(legacyCursor) || fs.existsSync(legacyLock))) {
458
- cursorFile = legacyCursor;
459
- lockFile = legacyLock;
460
- }
461
- return { cursorFile, lockFile, legacyCursor, legacyLock };
462
- }
463
-
464
- // true if the cursor file is safe to read/write (or absent).
465
- function cursorSafe(cursorFile) {
466
- try {
467
- const info = fs.lstatSync(cursorFile);
468
- if (info.isSymbolicLink() || !info.isFile()) return false;
469
- return ownedByUs(info);
470
- } catch (err) {
471
- return err && err.code === "ENOENT";
472
- }
473
- }
474
-
475
- function readCursor(cursorFile, log) {
476
- if (!cursorSafe(cursorFile)) {
477
- log(`unsafe cursor file ${cursorFile}`);
478
- return null;
479
- }
480
- try {
481
- const raw = fs.readFileSync(cursorFile, "utf8").trim();
482
- const n = parseInt(raw, 10);
483
- return Number.isFinite(n) ? n : 0;
484
- } catch {
485
- return 0;
486
- }
487
- }
488
-
489
- function writeCursor(cursorFile, value, log) {
490
- if (!cursorSafe(cursorFile)) {
491
- log(`refusing unsafe cursor file ${cursorFile}`);
492
- return false;
493
- }
494
- try {
495
- const tmp = `${cursorFile}.tmp.${process.pid}.${Math.abs(stableHash(String(value)) | 0)}`;
496
- fs.writeFileSync(tmp, `${value}\n`, { mode: 0o600 });
497
- fs.renameSync(tmp, cursorFile);
498
- return true;
499
- } catch {
500
- return false;
501
- }
502
- }
503
-
504
- function removeCursor(cursorFile, log) {
505
- if (!cursorSafe(cursorFile)) {
506
- log(`refusing unsafe cursor file ${cursorFile}`);
507
- return false;
508
- }
509
- try {
510
- fs.rmSync(cursorFile, { force: true });
511
- } catch {
512
- /* best effort */
513
- }
514
- return true;
515
- }
516
-
517
- // Adopt a higher os.tmpdir() cursor written by an older/cross-process run.
518
- function migrateTmpCursor(sessionId, cursorFile, log) {
519
- for (const tmp of [
520
- path.join(os.tmpdir(), `remnic-cursor-${sessionId}`),
521
- path.join(os.tmpdir(), `engram-cursor-${sessionId}`),
522
- ]) {
523
- try {
524
- if (!fs.existsSync(tmp)) continue;
525
- const info = fs.lstatSync(tmp);
526
- if (info.isSymbolicLink() || !info.isFile() || !ownedByUs(info)) continue;
527
- const raw = fs.readFileSync(tmp, "utf8").trim();
528
- if (!/^\d+$/.test(raw)) continue;
529
- const tmpVal = parseInt(raw, 10);
530
- const current = cursorSafe(cursorFile) ? readCursor(cursorFile, log) : -1;
531
- if (tmpVal > (current === null ? -1 : current)) writeCursor(cursorFile, tmpVal, log);
532
- fs.rmSync(tmp, { force: true });
533
- } catch {
534
- /* skip */
535
- }
536
- }
537
- }
538
-
539
- // mkdir-based mutex with stale-lock reaping (10 min). Returns true if acquired.
540
- function acquireLock(lockFile, log) {
541
- for (let i = 0; i < 50; i++) {
542
- try {
543
- fs.mkdirSync(lockFile);
544
- return true;
545
- } catch {
546
- if (i === 0) reapStaleLock(lockFile);
547
- sleepSync(100);
548
- }
549
- }
550
- return false;
551
- }
552
-
553
- function reapStaleLock(lockFile) {
554
- try {
555
- const info = fs.lstatSync(lockFile);
556
- if (info.isSymbolicLink() || !info.isDirectory() || !ownedByUs(info)) return;
557
- if (Date.now() - info.mtimeMs < 10 * 60 * 1000) return;
558
- fs.rmSync(lockFile, { recursive: true, force: true });
559
- } catch {
560
- /* best effort */
561
- }
562
- }
563
-
564
- function releaseLock(lockFile) {
565
- try {
566
- fs.rmdirSync(lockFile);
567
- } catch {
568
- /* best effort */
569
- }
570
- }
571
-
572
- function sleepSync(ms) {
573
- // Synchronous sleep without busy-spin (Atomics.wait on a throwaway buffer).
574
- try {
575
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
576
- } catch {
577
- const end = Date.now() + ms;
578
- while (Date.now() < end) {
579
- /* fallback spin */
580
- }
581
- }
582
- }
583
-
584
- // ── event handlers ─────────────────────────────────────────────────────────
585
-
586
- async function handleSessionStart(input, token, log) {
587
- const sessionId = input.session_id || "";
588
- const cwd = input.cwd || "";
589
- const projectName = (cwd && path.basename(cwd)) || "unknown";
590
- const codingContext = resolveCodingContext(cwd);
591
- log(`session=${sessionId} project=${projectName} coding-context=${codingContext ? "yes" : ""}`);
592
-
593
- // Health check — start daemon if not running.
594
- if (!(await httpHealthy(2000, token))) {
595
- log("daemon not responding, attempting start...");
596
- // Try `remnic` first, fall through to legacy `engram` when only the older
597
- // CLI is on PATH. spawn() emits ENOENT *asynchronously* via 'error', so we
598
- // pre-check the binary with onPath() instead of relying on try/break.
599
- for (const bin of ["remnic", "engram"]) {
600
- if (!onPath(bin)) continue;
601
- try {
602
- // Windows: `remnic`/`engram` are `.cmd` shims, which Node can only
603
- // launch via a shell. Args are fixed literals — safe.
604
- const child = spawn(bin, ["daemon", "start"], {
605
- detached: true,
606
- stdio: "ignore",
607
- shell: process.platform === "win32",
608
- windowsHide: true,
609
- });
610
- child.on("error", () => {});
611
- child.unref();
612
- break;
613
- } catch {
614
- /* try next */
615
- }
616
- }
617
- await new Promise((r) => setTimeout(r, 2000));
618
- if (!(await httpHealthy(2000, token))) {
619
- log("daemon still not responding after start attempt");
620
- emit({
621
- continue: true,
622
- hookSpecificOutput: {
623
- hookEventName: "SessionStart",
624
- additionalContext: "[Remnic: daemon not running — start with: remnic daemon start]",
625
- },
626
- });
627
- return;
628
- }
629
- }
630
-
631
- if (!token) {
632
- log("skipping: no token found");
633
- emit({
634
- continue: true,
635
- hookSpecificOutput: {
636
- hookEventName: "SessionStart",
637
- additionalContext: "[Remnic: no auth token — run: remnic connectors install claude-code]",
638
- },
639
- });
640
- return;
641
- }
642
-
643
- const query =
644
- `Starting a new coding session in project: ${projectName}. ` +
645
- "Recall relevant memories, preferences, decisions, patterns, and context about this project and the user.";
646
-
647
- // codingContext is explicitly null when absent so stale namespace routing is
648
- // cleared when a session moves out of a repo.
649
- let res = await httpPost(
650
- "/engram/v1/recall",
651
- token,
652
- { query, sessionKey: sessionId, topK: 12, mode: "auto", codingContext },
653
- 45000,
654
- );
655
- if (!res.ok || !res.body) {
656
- log(`full recall failed (http=${res.status}) — falling back to minimal`);
657
- res = await httpPost(
658
- "/engram/v1/recall",
659
- token,
660
- { query, sessionKey: sessionId, topK: 8, mode: "minimal", codingContext },
661
- 20000,
662
- );
663
- log(res.ok && res.body ? "minimal recall succeeded" : "minimal recall also failed");
664
- }
665
-
666
- let context;
667
- if (res.ok && res.body) {
668
- try {
669
- const d = JSON.parse(res.body);
670
- const ctx = d.context || "";
671
- const count = d.count || 0;
672
- const mode = d.mode || "";
673
- context = ctx
674
- ? `[Remnic Memory Recall — ${count} memories${mode ? `, ${mode} mode` : ""}]\n\n${ctx}`
675
- : "[Remnic: no relevant memories found for this session]";
676
- } catch {
677
- context = "[Remnic: recall parse error]";
678
- }
679
- log(`recall complete: ${context.split("\n")[0]}`);
680
- } else {
681
- context = "[Remnic: server unreachable — continuing without memory recall]";
682
- log(context);
683
- }
684
-
685
- emit({
686
- continue: true,
687
- hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context },
688
- });
689
- }
690
-
691
- async function handleUserPromptRecall(input, token, log) {
692
- // No-token → bare continue (no banner noise on every prompt).
693
- if (!token) {
694
- emit({ continue: true });
695
- return;
696
- }
697
- const sessionId = input.session_id || "";
698
- const prompt = input.prompt || "";
699
- const wordCount = prompt.trim() ? prompt.trim().split(/\s+/).length : 0;
700
- if (wordCount < 4) {
701
- emit({ continue: true });
702
- return;
703
- }
704
- log(`session=${sessionId} words=${wordCount}`);
705
-
706
- const res = await httpPost(
707
- "/engram/v1/recall",
708
- token,
709
- { query: prompt, sessionKey: sessionId, topK: 8, mode: "minimal" },
710
- 20000,
711
- );
712
- if (!res.ok || !res.body) {
713
- log(`recall failed (http=${res.status})`);
714
- emit({ continue: true });
715
- return;
716
- }
717
- try {
718
- const d = JSON.parse(res.body);
719
- const ctx = d.context || "";
720
- const count = d.count || 0;
721
- if (!ctx || count === 0) {
722
- emit({ continue: true });
723
- } else {
724
- emit({
725
- continue: true,
726
- hookSpecificOutput: {
727
- hookEventName: "UserPromptSubmit",
728
- additionalContext: `<remnic-memory count="${count}">\n${ctx}\n</remnic-memory>`,
729
- },
730
- });
731
- log(`done: ${count} memories injected`);
732
- }
733
- } catch {
734
- emit({ continue: true });
735
- }
736
- }
737
-
738
- // Background worker: lock + cursor + observe the transcript delta. Detached
739
- // from the foreground hook so a slow observe never blocks Claude Code past the
740
- // PostToolUse timeout.
741
- async function observeWorker(input, token, log) {
742
- const sessionId = input.session_id || "";
743
- const transcriptPath = input.transcript_path || "";
744
- const projectName = (input.cwd && path.basename(input.cwd)) || "unknown";
745
- const toolName = input.tool_name || "";
746
-
747
- if (!sessionId || /[^A-Za-z0-9._-]/.test(sessionId)) {
748
- log(`invalid session id: ${sessionId}`);
749
- return;
750
- }
751
- if (!transcriptPath || !fs.existsSync(transcriptPath) || !fs.statSync(transcriptPath).isFile()) {
752
- return;
753
- }
754
- const state = resolveState(sessionId, log);
755
- if (!state) return;
756
- const { cursorFile, lockFile } = state;
757
-
758
- if (!acquireLock(lockFile, log)) return;
759
- try {
760
- migrateTmpCursor(sessionId, cursorFile, log);
761
- const lastCount = readCursor(cursorFile, log);
762
- if (lastCount === null) return;
763
-
764
- let messages;
765
- try {
766
- messages = parseTranscript(transcriptPath);
767
- } catch {
768
- log(`parse failed for ${sessionId}`);
769
- return;
770
- }
771
- const newMessages = messages.slice(lastCount);
772
- if (newMessages.length === 0) {
773
- writeCursor(cursorFile, messages.length, log);
774
- return;
775
- }
776
- log(
777
- `observing ${newMessages.length} new messages (cursor ${lastCount}->${messages.length}) ` +
778
- `project=${projectName} tool=${toolName}`,
779
- );
780
- const res = await httpPost(
781
- "/engram/v1/observe",
782
- token,
783
- { sessionKey: sessionId, messages: newMessages },
784
- 120000,
785
- );
786
- if (res.ok) {
787
- log(`observe OK for ${sessionId}`);
788
- writeCursor(cursorFile, messages.length, log);
789
- } else {
790
- log(`observe failed (http=${res.status}) — cursor not advanced`);
791
- }
792
- } finally {
793
- releaseLock(lockFile);
794
- }
795
- }
796
-
797
- function handlePostToolObserve(rawInput, input, token, log) {
798
- // Return immediately — never block the tool.
799
- emit({ continue: true });
800
- if (!token) return;
801
- // Spawn a detached copy to do the observe in the background (mirrors the
802
- // original `( … ) & disown`). Pass the raw hook payload via the worker's
803
- // STDIN, not the environment — Windows caps the environment block at ~32 KB,
804
- // so large PostToolUse payloads (big file edits, command output) would fail
805
- // with E2BIG/ENAMETOOLONG and the observation would silently drop. Stdin has
806
- // no comparable limit.
807
- try {
808
- const child = spawn(process.execPath, [__filename, OBSERVE_WORKER], {
809
- detached: true,
810
- stdio: ["pipe", "ignore", "ignore"],
811
- env: { ...process.env, REMNIC_HOOK_TOKEN: token },
812
- });
813
- child.on("error", (e) => log(`observe worker spawn error: ${e && e.message}`));
814
- child.stdin.on("error", () => {
815
- /* ignore EPIPE if the worker exits before we finish writing */
816
- });
817
- child.stdin.end(rawInput);
818
- child.unref();
819
- } catch (err) {
820
- log(`failed to spawn observe worker: ${err && err.message}`);
821
- }
822
- }
823
-
824
- async function handleSessionEnd(input, token, log) {
825
- // Acknowledge immediately.
826
- emit({ continue: true });
827
-
828
- const sessionId = input.session_id || "";
829
- const transcriptPath = input.transcript_path || "";
830
- const safe = sessionId !== "" && !/[^A-Za-z0-9._-]/.test(sessionId);
831
-
832
- // NOTE: Claude Code does not currently emit a Stop/SessionEnd event. This
833
- // handler runs only when invoked manually or once Claude Code adds the
834
- // event. It is kept here so the final-flush + cursor-cleanup parity with
835
- // the Codex runner is in place from day one (issue #1518).
836
- let state = null;
837
- if (safe) state = resolveState(sessionId, log);
838
-
839
- let removeCursorAfterFlush = true;
840
-
841
- if (token && state && transcriptPath && fs.existsSync(transcriptPath)) {
842
- const { cursorFile } = state;
843
- migrateTmpCursor(sessionId, cursorFile, log);
844
- const lastCount = readCursor(cursorFile, log);
845
- if (lastCount === null) {
846
- log(`final flush skipped for ${sessionId} due to unsafe cursor`);
847
- } else {
848
- let newMessages = null;
849
- try {
850
- newMessages = parseTranscript(transcriptPath).slice(lastCount);
851
- } catch {
852
- log(`final flush parse failed for ${sessionId}; cursor retained for retry`);
853
- removeCursorAfterFlush = false;
854
- }
855
- if (newMessages && newMessages.length > 0) {
856
- log(`final flush for ${sessionId}`);
857
- const res = await httpPost(
858
- "/engram/v1/observe",
859
- token,
860
- { sessionKey: sessionId, messages: newMessages },
861
- 30000,
862
- );
863
- if (res.ok) {
864
- log(`final flush OK for ${sessionId}`);
865
- } else {
866
- // Critical: retain the cursor so the tail is retried, never lost.
867
- log(`final flush failed for ${sessionId} (http=${res.status}); cursor retained for retry`);
868
- removeCursorAfterFlush = false;
869
- }
870
- }
871
- }
872
- }
873
-
874
- // Cleanup — only remove the cursor when the flush succeeded or there was
875
- // nothing pending.
876
- if (state) {
877
- const { cursorFile, lockFile, legacyCursor, legacyLock } = state;
878
- if (removeCursorAfterFlush) removeCursor(cursorFile, log);
879
- releaseLock(lockFile);
880
- if (cursorFile !== legacyCursor) {
881
- try {
882
- const info = fs.lstatSync(legacyCursor);
883
- if (!info.isSymbolicLink()) fs.rmSync(legacyCursor, { force: true });
884
- } catch {
885
- /* absent */
886
- }
887
- }
888
- if (lockFile !== legacyLock) {
889
- try {
890
- fs.rmdirSync(legacyLock);
891
- } catch {
892
- /* absent */
893
- }
894
- }
895
- }
896
- }
897
-
898
- // ── entrypoint ─────────────────────────────────────────────────────────────
899
- async function main() {
900
- const event = process.argv[2] || "";
901
-
902
- // Detached background worker for post-tool-observe.
903
- if (event === OBSERVE_WORKER) {
904
- const log = makeLogger("post-tool-observe");
905
- try {
906
- const raw = readStdin();
907
- const input = parseInput(raw);
908
- const token = process.env.REMNIC_HOOK_TOKEN || resolveToken();
909
- if (token) await observeWorker(input, token, log);
910
- } catch (err) {
911
- log(`observe worker error: ${err && err.message}`);
912
- }
913
- return;
914
- }
915
-
916
- if (!Object.prototype.hasOwnProperty.call(LOG_FILES, event)) {
917
- // Unknown event — fail open without side effects.
918
- emit({ continue: true });
919
- if (event) process.stderr.write(`remnic-cc-hook: unknown event "${event}"\n`);
920
- return;
921
- }
922
-
923
- const log = makeLogger(event);
924
- const raw = readStdin();
925
- const input = parseInput(raw);
926
-
927
- try {
928
- ensureMigrated();
929
- const token = resolveToken();
930
- switch (event) {
931
- case "session-start":
932
- await handleSessionStart(input, token, log);
933
- break;
934
- case "user-prompt-recall":
935
- await handleUserPromptRecall(input, token, log);
936
- break;
937
- case "post-tool-observe":
938
- handlePostToolObserve(raw, input, token, log);
939
- break;
940
- case "session-end":
941
- await handleSessionEnd(input, token, log);
942
- break;
943
- }
944
- } catch (err) {
945
- log(`unhandled error in ${event}: ${err && err.message}`);
946
- // Best-effort fail-open: emit a bare continue only if we haven't already.
947
- if (!emitted) {
948
- try {
949
- emit({ continue: true });
950
- } catch {
951
- /* stdout already written */
952
- }
953
- }
954
- }
955
- }
956
-
957
- main();
27
+ const { run } = require("./remnic-hook-core.cjs");
28
+
29
+ run({
30
+ client: "claude-code",
31
+ tokenConnectors: ["claude-code", "openclaw"],
32
+ connectorInstall: "claude-code",
33
+ progName: "remnic-cc-hook",
34
+ defaultLogFile: "remnic-cc-hook.log",
35
+ logFiles: {
36
+ "session-start": "remnic-session-recall.log",
37
+ "user-prompt-recall": "remnic-user-prompt-recall.log",
38
+ "post-tool-observe": "remnic-post-tool-observe.log",
39
+ "session-end": "remnic-cc-session-end.log",
40
+ },
41
+ logTags: {
42
+ "session-start": "cc-session-start",
43
+ "user-prompt-recall": "cc-user-prompt",
44
+ "post-tool-observe": "cc-post-tool",
45
+ "session-end": "cc-stop",
46
+ },
47
+ enablePreCompact: false,
48
+ enableMaterialize: false,
49
+ });