@remnic/plugin-codex 9.3.613 → 9.3.615

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