@remnic/plugin-codex 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,1237 +1,48 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Remnic unified Codex hook runner (issue #1440).
3
+ * Remnic unified Codex hook runner (issues #1440, #2483).
4
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]:
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-codex-hook.cjs <event>
10
12
  *
11
- * Events: session-start | user-prompt-recall | post-tool-observe | session-end
13
+ * Events: session-start | user-prompt-recall | post-tool-observe |
14
+ * session-end | pre-compact
12
15
  *
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.
16
+ * Codex-only surfaces enabled here: the PreCompact drain+flush (#1571) and
17
+ * the session-end Codex-native memory materialization (#378).
19
18
  *
20
19
  * Fail-open everywhere: any unexpected error degrades to `{"continue":true}`.
21
20
  */
22
21
 
23
22
  "use strict";
24
23
 
25
- const fs = require("fs");
26
- const os = require("os");
27
- const path = require("path");
28
- const http = require("http");
29
- const https = require("https");
30
- const { execFileSync, spawn, spawnSync } = require("child_process");
31
-
32
- const HOME = process.env.HOME || process.env.USERPROFILE || os.homedir();
33
-
34
- // Daemon base URL resolution (issue #1571 — remote/network parity with
35
- // @remnic/plugin-pi's `remnicDaemonUrl`). A full REMNIC_DAEMON_URL
36
- // (e.g. "http://macstudio.tailnet:4318" or "https://remnic.internal:443")
37
- // takes precedence and lets a Codex host talk to a shared central daemon
38
- // over Tailscale/LAN/VPN. The legacy REMNIC_HOST/REMNIC_PORT pair remains
39
- // supported as a backward-compat fallback so existing installs and the
40
- // test harness (which spins a mock on 127.0.0.1:<port>) keep working.
41
- const RAW_DAEMON_URL = process.env.REMNIC_DAEMON_URL || process.env.ENGRAM_DAEMON_URL || "";
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
- // Parse once. `protocol` is "http:" or "https:" so https.request is selected
46
- // for TLS daemons (common for remote/private deployments behind a proxy).
47
- //
48
- // An EXPLICIT but invalid REMNIC_DAEMON_URL (missing scheme, typo, e.g.
49
- // "macstudio:4318") must NOT silently fall through to REMNIC_HOST/REMNIC_PORT —
50
- // that would route recall/observe/flush to a local daemon and corrupt the wrong
51
- // memory store. Instead we disable the daemon entirely (all HTTP calls fail
52
- // open) and surface the misconfiguration once on stderr so the operator fixes
53
- // the URL rather than debugging silent cross-store writes (#1571 review).
54
- let DAEMON_CONFIG_ERROR = "";
55
- const DAEMON_URL = (function resolveDaemonUrl() {
56
- if (RAW_DAEMON_URL) {
57
- try {
58
- const parsed = new URL(RAW_DAEMON_URL);
59
- // Require an explicit scheme — a bare "macstudio:4318" parses with
60
- // protocol "macstudio:" and would otherwise silently route to localhost.
61
- if (parsed.protocol === "http:" || parsed.protocol === "https:") return parsed;
62
- } catch {
63
- /* handled below */
64
- }
65
- DAEMON_CONFIG_ERROR =
66
- 'REMNIC_DAEMON_URL="' + RAW_DAEMON_URL + '" is not a valid http(s) URL — ' +
67
- "daemon disabled (recall/observe/flush will no-op). Set a valid " +
68
- "http(s):// URL or unset REMNIC_DAEMON_URL to use REMNIC_HOST/REMNIC_PORT.";
69
- if (process.env.REMNIC_HOOK_QUIET !== "1") {
70
- try { process.stderr.write("[remnic-codex-hook] " + DAEMON_CONFIG_ERROR + "\n"); } catch {}
71
- }
72
- return null;
73
- }
74
- try {
75
- return new URL(`http://${HOST}:${PORT}`);
76
- } catch {
77
- return new URL("http://127.0.0.1:4318");
78
- }
79
- })();
80
-
81
- // Internal re-entrant mode: post-tool-observe spawns a detached copy of itself
82
- // so the (slow) observe runs in the background and never blocks Codex past the
83
- // short PostToolUse timeout — mirroring the original `( … ) & disown`.
84
- const OBSERVE_WORKER = "__observe-worker__";
85
-
86
- // PreCompact tail-drain lock-wait budget (100ms each → ~15s). Bounds how long
87
- // handlePreCompact waits for a detached PostToolUse observe worker (whose own
88
- // /observe can run up to 120s) to release the session lock before skipping the
89
- // drain+flush. 15s covers a typical observe round-trip on a healthy daemon; a
90
- // pathologically slow worker that outlasts this is left for the next cycle
91
- // rather than blocking compaction indefinitely. The hooks.json PreCompact
92
- // timeout accommodates this budget plus the drain observe + LCM flush.
93
- const _pcRaw = process.env.REMNIC_PRECOMPACT_LOCK_RETRIES;
94
- const _pcParsed = _pcRaw != null && _pcRaw !== "" ? Number.parseInt(_pcRaw, 10) : 150;
95
- // 0 is honored (immediate busy-skip); NaN/negative falls back to the 150 default.
96
- const PRECOMPACT_LOCK_RETRIES = Number.isFinite(_pcParsed) && _pcParsed >= 0 ? _pcParsed : 150;
97
-
98
- const LOG_FILES = {
99
- "session-start": "remnic-session-recall.log",
100
- "user-prompt-recall": "remnic-user-prompt-recall.log",
101
- "post-tool-observe": "remnic-post-tool-observe.log",
102
- "session-end": "remnic-codex-session-end.log",
103
- "pre-compact": "remnic-pre-compact.log",
104
- };
105
- const LOG_TAGS = {
106
- "session-start": "codex-session-start",
107
- "user-prompt-recall": "codex-user-prompt",
108
- "post-tool-observe": "codex-post-tool",
109
- "session-end": "codex-stop",
110
- "pre-compact": "codex-pre-compact",
111
- };
112
-
113
- function makeLogger(event) {
114
- const file = path.join(HOME, ".remnic", "logs", LOG_FILES[event] || "remnic-codex-hook.log");
115
- const tag = LOG_TAGS[event] || "codex-hook";
116
- try {
117
- fs.mkdirSync(path.dirname(file), { recursive: true });
118
- } catch {
119
- /* best effort */
120
- }
121
- return (msg) => {
122
- try {
123
- const ts = new Date().toISOString().replace("T", " ").slice(0, 19);
124
- fs.appendFileSync(file, `${ts} [${tag}] ${msg}\n`);
125
- } catch {
126
- /* logging must never throw */
127
- }
128
- };
129
- }
130
-
131
- let emitted = false;
132
- function emit(obj) {
133
- process.stdout.write(`${JSON.stringify(obj)}\n`);
134
- emitted = true;
135
- }
136
-
137
- function readStdin() {
138
- // Always read the real stdin. The foreground hook gets its payload from
139
- // Codex on fd 0; the detached observe worker gets it from the pipe the
140
- // foreground writes. We deliberately do NOT consult an env var here — an
141
- // inherited REMNIC_HOOK_INPUT in the parent environment would otherwise
142
- // override the piped payload and the worker could observe stale/empty input
143
- // (#1443 review).
144
- try {
145
- return fs.readFileSync(0, "utf8");
146
- } catch {
147
- return "";
148
- }
149
- }
150
-
151
- function parseInput(raw) {
152
- try {
153
- const d = JSON.parse(raw);
154
- return d && typeof d === "object" ? d : {};
155
- } catch {
156
- return {};
157
- }
158
- }
159
-
160
- // ── engram → remnic migration (CLAUDE.md rule #9) ──────────────────────────
161
- function ensureMigrated() {
162
- try {
163
- if (fs.existsSync(path.join(HOME, ".remnic", ".migrated-from-engram"))) return;
164
- const hasEngram =
165
- fs.existsSync(path.join(HOME, ".engram")) ||
166
- fs.existsSync(path.join(HOME, ".config", "engram", "config.json"));
167
- if (!hasEngram) return;
168
- // Try `remnic` first, fall through to legacy `engram` when missing on PATH.
169
- // Pre-check PATH with onPath() (which is .cmd/.exe-aware on Windows) rather
170
- // than relying on spawnSync ENOENT — under `shell: true` a missing command
171
- // yields a non-zero shell exit, not ENOENT, so an exit-code check couldn't
172
- // distinguish "missing" from "migration failed" (#1443 review).
173
- // On Windows the CLIs are `.cmd` shims, which Node can only launch via a
174
- // shell. Timeout is 5 min so a large migration can complete (the original
175
- // bash hook had no timeout). Args are fixed literals — safe under a shell.
176
- for (const bin of ["remnic", "engram"]) {
177
- if (!onPath(bin)) continue;
178
- spawnSync(bin, ["migrate"], {
179
- stdio: "ignore",
180
- timeout: 300000,
181
- shell: process.platform === "win32",
182
- windowsHide: true,
183
- });
184
- return;
185
- }
186
- } catch {
187
- /* migration is best effort */
188
- }
189
- }
190
-
191
- // PATH lookup helper (cross-platform equivalent of bash `command -v`).
192
- // Returns true when an executable named `bin` is reachable via $PATH. Used
193
- // before async `spawn()` calls so the remnic → engram fallthrough actually
194
- // happens when only the legacy CLI is installed — `spawn` emits ENOENT
195
- // asynchronously via 'error', so a naive try/break can't see it (#1443 review).
196
- function onPath(bin) {
197
- const PATH = process.env.PATH || process.env.Path || process.env.path || "";
198
- const sep = process.platform === "win32" ? ";" : ":";
199
- // Windows resolves names without an extension by appending PATHEXT entries.
200
- const exts =
201
- process.platform === "win32"
202
- ? (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD")
203
- .split(";")
204
- .map((e) => e.trim())
205
- .filter(Boolean)
206
- : [""];
207
- for (const dir of PATH.split(sep)) {
208
- if (!dir) continue;
209
- for (const ext of exts) {
210
- try {
211
- const candidate = path.join(dir, bin + ext);
212
- const info = fs.statSync(candidate);
213
- if (info.isFile()) return true;
214
- } catch {
215
- /* try next */
216
- }
217
- }
218
- }
219
- return false;
220
- }
221
-
222
- // ── token resolution (per-plugin token store, then env) ────────────────────
223
- // Env precedence is primary-before-legacy per AGENTS.md §9: the two current
224
- // names (OPENCLAW_REMNIC_ACCESS_TOKEN, REMNIC_AUTH_TOKEN) before the two
225
- // legacy aliases (OPENCLAW_ENGRAM_ACCESS_TOKEN, ENGRAM_AUTH_TOKEN), so a
226
- // stale leftover from a pre-rename install cannot outrank the credential the
227
- // daemon is actually running with. REMNIC_AUTH_TOKEN matters because the
228
- // documented standalone-server setup authenticates the daemon with it alone
229
- // and never mints a connector token.
230
- function resolveToken() {
231
- for (const file of [
232
- path.join(HOME, ".remnic", "tokens.json"),
233
- path.join(HOME, ".engram", "tokens.json"),
234
- ]) {
235
- try {
236
- if (!fs.existsSync(file)) continue;
237
- const store = JSON.parse(fs.readFileSync(file, "utf8"));
238
- const tokens = Array.isArray(store.tokens) ? store.tokens : [];
239
- const byConnector = (c) => tokens.find((t) => t && t.connector === c);
240
- const tok =
241
- (byConnector("codex-cli") || {}).token ||
242
- (byConnector("codex") || {}).token ||
243
- (byConnector("openclaw") || {}).token ||
244
- store["codex-cli"] ||
245
- store["codex"] ||
246
- store["openclaw"] ||
247
- "";
248
- if (tok) return tok;
249
- } catch {
250
- /* try next file */
251
- }
252
- }
253
- return (
254
- process.env.OPENCLAW_REMNIC_ACCESS_TOKEN ||
255
- process.env.REMNIC_AUTH_TOKEN ||
256
- process.env.OPENCLAW_ENGRAM_ACCESS_TOKEN ||
257
- process.env.ENGRAM_AUTH_TOKEN ||
258
- ""
259
- );
260
- }
261
-
262
- // ── Namespace chokepoint (#1571) ─────────────────────────────────────────────
263
- // Single source of truth for the optional namespace override. EVERY observe and
264
- // flush body MUST go through withNamespace() so a namespaced Codex install
265
- // archives + flushes under one key — without it, buffered observations land on
266
- // the default key while a namespaced flush drains a different (empty) queue, and
267
- // most in-session memory never flushes before compaction.
268
- function resolveNamespace() {
269
- return process.env.REMNIC_NAMESPACE || process.env.ENGRAM_NAMESPACE || "";
270
- }
271
- function withNamespace(body) {
272
- const ns = resolveNamespace();
273
- if (ns) body.namespace = ns;
274
- return body;
275
- }
276
-
277
- // Base path from the daemon URL (for reverse-proxy subpath mounts, e.g.
278
- // REMNIC_DAEMON_URL=http://gw/remnic). Mirrors plugin-pi's daemon-URL + route
279
- // concatenation — without this, a path-qualified base URL has its prefix
280
- // silently dropped and requests hit the host root (#1571 review). Trailing
281
- // slashes are stripped so "/remnic/" + "/engram/v1/observe" becomes
282
- // "/remnic/engram/v1/observe"; a bare root ("/") yields "" (no prefix).
283
- const DAEMON_BASE_PATH = DAEMON_URL ? DAEMON_URL.pathname.replace(/\/+$/, "") : "";
284
-
285
- // ── HTTP helpers — return a real success signal (2xx) so callers can decide
286
- // whether to advance/clear the cursor (fixes the data-loss bug in #1442).
287
- //
288
- // All requests route through the parsed DAEMON_URL (#1571), so a Codex host
289
- // can target a remote/central daemon (Tailscale/LAN/VPN, plain or TLS) by
290
- // setting REMNIC_DAEMON_URL — same transport contract as @remnic/plugin-pi. ─
291
-
292
- function httpPost(urlPath, token, bodyObj, timeoutMs) {
293
- if (DAEMON_URL === null) {
294
- // Explicit-but-invalid REMNIC_DAEMON_URL — disabled, fail open (see
295
- // resolveDaemonUrl). Callers treat this like a dead daemon.
296
- return Promise.resolve({ ok: false, status: 0, body: "" });
297
- }
298
- const transport = DAEMON_URL.protocol === "https:" ? https : http;
299
- return new Promise((resolve) => {
300
- let data;
301
- try {
302
- data = Buffer.from(JSON.stringify(bodyObj), "utf8");
303
- } catch {
304
- resolve({ ok: false, status: 0, body: "" });
305
- return;
306
- }
307
- const req = transport.request(
308
- {
309
- protocol: DAEMON_URL.protocol,
310
- hostname: DAEMON_URL.hostname,
311
- port: DAEMON_URL.port || (DAEMON_URL.protocol === "https:" ? 443 : 80),
312
- path: DAEMON_BASE_PATH + urlPath,
313
- method: "POST",
314
- headers: {
315
- Authorization: `Bearer ${token}`,
316
- "Content-Type": "application/json",
317
- "X-Engram-Client-Id": "codex",
318
- "Content-Length": data.length,
319
- },
320
- },
321
- (res) => {
322
- let body = "";
323
- res.setEncoding("utf8");
324
- res.on("data", (c) => {
325
- body += c;
326
- });
327
- res.on("end", () =>
328
- resolve({
329
- ok: res.statusCode >= 200 && res.statusCode < 300,
330
- status: res.statusCode || 0,
331
- body,
332
- }),
333
- );
334
- },
335
- );
336
- req.on("error", () => resolve({ ok: false, status: 0, body: "" }));
337
- req.setTimeout(timeoutMs, () => {
338
- req.destroy();
339
- resolve({ ok: false, status: 0, body: "" });
340
- });
341
- req.write(data);
342
- req.end();
343
- });
344
- }
345
-
346
- // `token` is the caller's already-resolved credential, NOT a second
347
- // resolveToken() call: the probe must authenticate with the exact bearer the
348
- // operation it gates will send. Re-resolving could pick up a rotated
349
- // tokens.json (or an inherited REMNIC_HOOK_TOKEN the foreground handlers
350
- // ignore) and green-light a probe whose recall then 401s.
351
- //
352
- // When the daemon has an auth token configured, every route — including
353
- // /engram/v1/health — returns 401 to unauthenticated requests, so an
354
- // unauthenticated probe makes the hook wrongly report "daemon not running"
355
- // and skip recall/observe. Unauthenticated daemons ignore the header.
356
- function httpHealthy(timeoutMs, token) {
357
- if (DAEMON_URL === null) return Promise.resolve(false);
358
- const transport = DAEMON_URL.protocol === "https:" ? https : http;
359
- return new Promise((resolve) => {
360
- const req = transport.request(
361
- {
362
- protocol: DAEMON_URL.protocol,
363
- hostname: DAEMON_URL.hostname,
364
- port: DAEMON_URL.port || (DAEMON_URL.protocol === "https:" ? 443 : 80),
365
- path: DAEMON_BASE_PATH + "/engram/v1/health",
366
- method: "GET",
367
- headers: token ? { Authorization: `Bearer ${token}` } : {},
368
- },
369
- (res) => {
370
- res.resume();
371
- resolve(res.statusCode >= 200 && res.statusCode < 300);
372
- },
373
- );
374
- req.on("error", () => resolve(false));
375
- req.setTimeout(timeoutMs, () => {
376
- req.destroy();
377
- resolve(false);
378
- });
379
- req.end();
380
- });
381
- }
382
-
383
- // ── git coding-context (mirrors @remnic/core git-context.ts) ───────────────
384
- function git(args, cwd) {
385
- try {
386
- return execFileSync("git", args, {
387
- cwd,
388
- encoding: "utf8",
389
- timeout: 5000,
390
- stdio: ["ignore", "pipe", "ignore"],
391
- }).trim();
392
- } catch {
393
- return "";
394
- }
395
- }
396
-
397
- function stableHash(input) {
398
- let hash = 0x811c9dc5;
399
- for (let i = 0; i < input.length; i++) {
400
- hash ^= input.charCodeAt(i);
401
- hash = Math.imul(hash, 0x01000193) >>> 0;
402
- }
403
- return hash.toString(16).padStart(8, "0");
404
- }
405
-
406
- // Mirrors packages/remnic-core/src/coding/git-context.ts normalizeOriginUrl.
407
- // Keep in sync so the hook-computed projectId matches the daemon's.
408
- function normalizeOriginUrl(raw) {
409
- let u = (raw || "").trim();
410
- if (!u) return "";
411
- if (/\.git$/i.test(u)) u = u.slice(0, -4);
412
- if (/^[A-Za-z]:[\\/]/.test(u)) return u.toLowerCase();
413
- const proto = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?(\[[^\]]+\]|[^/:]*)(?::(\d+))?(\/.*)?$/i.exec(u);
414
- if (proto) {
415
- let host = proto[1] || "";
416
- const wasBracketed = host.startsWith("[") && host.endsWith("]");
417
- if (wasBracketed) host = host.slice(1, -1);
418
- const port = proto[2];
419
- const p = (proto[3] || "").replace(/^\/+/, "");
420
- const hostPort = port
421
- ? wasBracketed
422
- ? "[" + host + "]:" + port
423
- : host + ":" + port
424
- : host;
425
- const prefix = hostPort.length > 0 ? hostPort : "localhost";
426
- return (prefix + "/" + p).toLowerCase();
427
- }
428
- const scp = /^(?:([^@\s/]+)@)?(\[[^\]]+\]|[^:@\s/]+):(.+)$/.exec(u);
429
- if (scp) {
430
- let host = scp[2] || "";
431
- if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
432
- const p = scp[3] || "";
433
- if (p.startsWith("//")) return u.toLowerCase();
434
- return (host + "/" + p.replace(/^\/+/, "")).toLowerCase();
435
- }
436
- return u.toLowerCase();
437
- }
438
-
439
- function resolveCodingContext(cwd) {
440
- try {
441
- if (!cwd || !fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) return null;
442
- const top = git(["-C", cwd, "rev-parse", "--show-toplevel"], cwd);
443
- if (!top) return null;
444
- let branch = git(["-C", top, "rev-parse", "--abbrev-ref", "HEAD"], top);
445
- if (branch === "HEAD") branch = "";
446
- const origin = git(["-C", top, "remote", "get-url", "origin"], top);
447
- const defRef = git(["-C", top, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], top);
448
- const defaultBranch = defRef ? defRef.replace(/^refs\/remotes\/origin\//, "") : "";
449
- const normalized = normalizeOriginUrl(origin);
450
- const projectId = normalized ? "origin:" + stableHash(normalized) : "root:" + stableHash(top);
451
- return {
452
- projectId,
453
- branch: branch || null,
454
- rootPath: top,
455
- defaultBranch: defaultBranch || null,
456
- };
457
- } catch {
458
- return null;
459
- }
460
- }
461
-
462
- // ── transcript parsing ─────────────────────────────────────────────────────
463
- function parseTranscript(transcriptPath) {
464
- const lines = fs.readFileSync(transcriptPath, "utf8").split("\n").filter(Boolean);
465
- const messages = [];
466
- for (const line of lines) {
467
- try {
468
- const entry = JSON.parse(line);
469
- if (entry.type !== "user" && entry.type !== "assistant") continue;
470
- const msg = entry.message;
471
- if (!msg || typeof msg !== "object") continue;
472
- const role = msg.role;
473
- if (role !== "user" && role !== "assistant") continue;
474
- let text = "";
475
- if (typeof msg.content === "string") text = msg.content.trim();
476
- else if (Array.isArray(msg.content)) {
477
- text = msg.content
478
- .filter((b) => b.type === "text" && b.text)
479
- .map((b) => b.text.trim())
480
- .join("\n")
481
- .trim();
482
- }
483
- if (text) messages.push({ role, content: text });
484
- } catch {
485
- /* skip malformed line */
486
- }
487
- }
488
- return messages;
489
- }
490
-
491
- // ── cursor / lock state hardening (post-tool + session-end) ────────────────
492
- const SELF_UID = typeof process.getuid === "function" ? process.getuid() : null;
493
-
494
- function ownedByUs(info) {
495
- return SELF_UID === null || info.uid === SELF_UID;
496
- }
497
-
498
- // Returns { cursorFile, lockFile } or null if the state dir is unsafe.
499
- function resolveState(sessionId, log) {
500
- const stateHome = process.env.XDG_STATE_HOME || path.join(HOME, ".local", "state");
501
- const stateDir = path.join(stateHome, "remnic", "hooks");
502
- try {
503
- fs.mkdirSync(stateDir, { recursive: true });
504
- } catch {
505
- return null;
506
- }
507
- try {
508
- const info = fs.lstatSync(stateDir);
509
- if (info.isSymbolicLink() || !info.isDirectory()) {
510
- log(`unsafe state directory ${stateDir}`);
511
- return null;
512
- }
513
- if (!ownedByUs(info)) {
514
- log(`unsafe state directory ${stateDir}`);
515
- return null;
516
- }
517
- if ((info.mode & 0o077) !== 0) {
518
- try {
519
- fs.chmodSync(stateDir, 0o700);
520
- } catch {
521
- /* best effort */
522
- }
523
- }
524
- } catch {
525
- return null;
526
- }
527
- let cursorFile = path.join(stateDir, `remnic-cursor-${sessionId}`);
528
- let lockFile = path.join(stateDir, `remnic-lock-${sessionId}.d`);
529
- const legacyCursor = path.join(stateDir, `engram-cursor-${sessionId}`);
530
- const legacyLock = path.join(stateDir, `engram-lock-${sessionId}.d`);
531
- // Mid-migration fallback: adopt the legacy engram-* cursor/lock so we don't
532
- // re-observe the whole transcript (CLAUDE.md rule #9).
533
- if (!fs.existsSync(cursorFile) && (fs.existsSync(legacyCursor) || fs.existsSync(legacyLock))) {
534
- cursorFile = legacyCursor;
535
- lockFile = legacyLock;
536
- }
537
- return { cursorFile, lockFile, legacyCursor, legacyLock };
538
- }
539
-
540
- // true if the cursor file is safe to read/write (or absent).
541
- function cursorSafe(cursorFile) {
542
- try {
543
- const info = fs.lstatSync(cursorFile);
544
- if (info.isSymbolicLink() || !info.isFile()) return false;
545
- return ownedByUs(info);
546
- } catch (err) {
547
- return err && err.code === "ENOENT";
548
- }
549
- }
550
-
551
- function readCursor(cursorFile, log) {
552
- if (!cursorSafe(cursorFile)) {
553
- log(`unsafe cursor file ${cursorFile}`);
554
- return null;
555
- }
556
- try {
557
- const raw = fs.readFileSync(cursorFile, "utf8").trim();
558
- const n = parseInt(raw, 10);
559
- return Number.isFinite(n) ? n : 0;
560
- } catch {
561
- return 0;
562
- }
563
- }
564
-
565
- function writeCursor(cursorFile, value, log) {
566
- if (!cursorSafe(cursorFile)) {
567
- log(`refusing unsafe cursor file ${cursorFile}`);
568
- return false;
569
- }
570
- try {
571
- const tmp = `${cursorFile}.tmp.${process.pid}.${Math.abs(stableHash(String(value)) | 0)}`;
572
- fs.writeFileSync(tmp, `${value}\n`, { mode: 0o600 });
573
- fs.renameSync(tmp, cursorFile);
574
- return true;
575
- } catch {
576
- return false;
577
- }
578
- }
579
-
580
- function removeCursor(cursorFile, log) {
581
- if (!cursorSafe(cursorFile)) {
582
- log(`refusing unsafe cursor file ${cursorFile}`);
583
- return false;
584
- }
585
- try {
586
- fs.rmSync(cursorFile, { force: true });
587
- } catch {
588
- /* best effort */
589
- }
590
- return true;
591
- }
592
-
593
- // Adopt a higher /tmp cursor written by an older/cross-process run, then clean.
594
- function migrateTmpCursor(sessionId, cursorFile, log) {
595
- for (const tmp of [
596
- path.join(os.tmpdir(), `remnic-cursor-${sessionId}`),
597
- path.join(os.tmpdir(), `engram-cursor-${sessionId}`),
598
- `/tmp/remnic-cursor-${sessionId}`,
599
- `/tmp/engram-cursor-${sessionId}`,
600
- ]) {
601
- try {
602
- if (!fs.existsSync(tmp)) continue;
603
- const info = fs.lstatSync(tmp);
604
- if (info.isSymbolicLink() || !info.isFile() || !ownedByUs(info)) continue;
605
- const raw = fs.readFileSync(tmp, "utf8").trim();
606
- if (!/^\d+$/.test(raw)) continue;
607
- const tmpVal = parseInt(raw, 10);
608
- const current = cursorSafe(cursorFile) ? readCursor(cursorFile, log) : -1;
609
- if (tmpVal > (current === null ? -1 : current)) writeCursor(cursorFile, tmpVal, log);
610
- fs.rmSync(tmp, { force: true });
611
- } catch {
612
- /* skip */
613
- }
614
- }
615
- }
616
-
617
- // mkdir-based mutex with stale-lock reaping (10 min). Returns true if acquired.
618
- // `retries` bounds the synchronous wait (100ms each). The default (50 → ~5s)
619
- // suits foreground hooks; PreCompact's tail drain passes a larger budget so it
620
- // can outlast a detached PostToolUse observe worker holding the lock, ensuring
621
- // the subsequent flush sees the worker's queued messages instead of racing.
622
- // 0 means "try once, don't wait/retry" — a free lock is still taken; only a
623
- // busy lock is skipped immediately (used by the 0-retry test/fleet path). This
624
- // avoids the degenerate "0 retries skips acquisition entirely" case (#1571
625
- // review) where a free lock would be wastefully bypassed.
626
- function acquireLock(lockFile, log, retries = 50) {
627
- const attempts = Math.max(1, retries);
628
- for (let i = 0; i < attempts; i++) {
629
- try {
630
- fs.mkdirSync(lockFile);
631
- return true;
632
- } catch {
633
- if (i === 0) reapStaleLock(lockFile);
634
- sleepSync(100);
635
- }
636
- }
637
- return false;
638
- }
639
-
640
- function reapStaleLock(lockFile) {
641
- try {
642
- const info = fs.lstatSync(lockFile);
643
- if (info.isSymbolicLink() || !info.isDirectory() || !ownedByUs(info)) return;
644
- if (Date.now() - info.mtimeMs < 10 * 60 * 1000) return;
645
- fs.rmSync(lockFile, { recursive: true, force: true });
646
- } catch {
647
- /* best effort */
648
- }
649
- }
650
-
651
- function releaseLock(lockFile) {
652
- try {
653
- fs.rmdirSync(lockFile);
654
- } catch {
655
- /* best effort */
656
- }
657
- }
658
-
659
- function sleepSync(ms) {
660
- // Synchronous sleep without busy-spin (Atomics.wait on a throwaway buffer).
661
- try {
662
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
663
- } catch {
664
- const end = Date.now() + ms;
665
- while (Date.now() < end) {
666
- /* fallback spin */
667
- }
668
- }
669
- }
670
-
671
- // ── event handlers ─────────────────────────────────────────────────────────
672
-
673
- async function handleSessionStart(input, token, log) {
674
- const sessionId = input.session_id || "";
675
- const cwd = input.cwd || "";
676
- const projectName = (cwd && path.basename(cwd)) || "unknown";
677
- const codingContext = resolveCodingContext(cwd);
678
- log(`session=${sessionId} project=${projectName} coding-context=${codingContext ? "yes" : ""}`);
679
-
680
- // Health check — start daemon if not running.
681
- if (!(await httpHealthy(2000, token))) {
682
- log("daemon not responding, attempting start...");
683
- // Try `remnic` first, fall through to legacy `engram` when only the older
684
- // CLI is on PATH. spawn() emits ENOENT *asynchronously* via 'error', so we
685
- // pre-check the binary with onPath() instead of relying on try/break
686
- // (#1443 review — the bare try/break never reached `engram`).
687
- for (const bin of ["remnic", "engram"]) {
688
- if (!onPath(bin)) continue;
689
- try {
690
- // Windows: `remnic`/`engram` are `.cmd` shims, which Node can only
691
- // launch via a shell (#1443 review). Args are fixed literals — safe.
692
- const child = spawn(bin, ["daemon", "start"], {
693
- detached: true,
694
- stdio: "ignore",
695
- shell: process.platform === "win32",
696
- windowsHide: true,
697
- });
698
- child.on("error", () => {});
699
- child.unref();
700
- break;
701
- } catch {
702
- /* try next */
703
- }
704
- }
705
- await new Promise((r) => setTimeout(r, 2000));
706
- if (!(await httpHealthy(2000, token))) {
707
- log("daemon still not responding after start attempt");
708
- emit({
709
- continue: true,
710
- hookSpecificOutput: {
711
- hookEventName: "SessionStart",
712
- additionalContext: "[Remnic: daemon not running — start with: remnic daemon start]",
713
- },
714
- });
715
- return;
716
- }
717
- }
718
-
719
- if (!token) {
720
- log("skipping: no token found");
721
- emit({
722
- continue: true,
723
- hookSpecificOutput: {
724
- hookEventName: "SessionStart",
725
- additionalContext: "[Remnic: no auth token — run: remnic connectors install codex-cli]",
726
- },
727
- });
728
- return;
729
- }
730
-
731
- const query =
732
- `Starting a new coding session in project: ${projectName}. ` +
733
- "Recall relevant memories, preferences, decisions, patterns, and context about this project and the user.";
734
-
735
- // codingContext is explicitly null when absent so stale namespace routing is
736
- // cleared when a session moves out of a repo.
737
- let res = await httpPost(
738
- "/engram/v1/recall",
739
- token,
740
- withNamespace({ query, sessionKey: sessionId, topK: 12, mode: "auto", codingContext }),
741
- 45000,
742
- );
743
- if (!res.ok || !res.body) {
744
- log(`full recall failed (http=${res.status}) — falling back to minimal`);
745
- res = await httpPost(
746
- "/engram/v1/recall",
747
- token,
748
- withNamespace({ query, sessionKey: sessionId, topK: 8, mode: "minimal", codingContext }),
749
- 20000,
750
- );
751
- log(res.ok && res.body ? "minimal recall succeeded" : "minimal recall also failed");
752
- }
753
-
754
- let context;
755
- if (res.ok && res.body) {
756
- try {
757
- const d = JSON.parse(res.body);
758
- const ctx = d.context || "";
759
- const count = d.count || 0;
760
- const mode = d.mode || "";
761
- context = ctx
762
- ? `[Remnic Memory Recall — ${count} memories${mode ? `, ${mode} mode` : ""}]\n\n${ctx}`
763
- : "[Remnic: no relevant memories found for this session]";
764
- } catch {
765
- context = "[Remnic: recall parse error]";
766
- }
767
- log(`recall complete: ${context.split("\n")[0]}`);
768
- } else {
769
- context = "[Remnic: server unreachable — continuing without memory recall]";
770
- log(context);
771
- }
772
-
773
- emit({
774
- continue: true,
775
- hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context },
776
- });
777
- }
778
-
779
- async function handleUserPromptRecall(input, token, log) {
780
- // No-token → bare continue (no banner noise on every prompt).
781
- if (!token) {
782
- emit({ continue: true });
783
- return;
784
- }
785
- const sessionId = input.session_id || "";
786
- const prompt = input.prompt || "";
787
- const wordCount = prompt.trim() ? prompt.trim().split(/\s+/).length : 0;
788
- if (wordCount < 4) {
789
- emit({ continue: true });
790
- return;
791
- }
792
- log(`session=${sessionId} words=${wordCount}`);
793
-
794
- const res = await httpPost(
795
- "/engram/v1/recall",
796
- token,
797
- withNamespace({ query: prompt, sessionKey: sessionId, topK: 8, mode: "minimal" }),
798
- 20000,
799
- );
800
- if (!res.ok || !res.body) {
801
- log(`recall failed (http=${res.status})`);
802
- emit({ continue: true });
803
- return;
804
- }
805
- try {
806
- const d = JSON.parse(res.body);
807
- const ctx = d.context || "";
808
- const count = d.count || 0;
809
- if (!ctx || count === 0) {
810
- emit({ continue: true });
811
- } else {
812
- emit({
813
- continue: true,
814
- hookSpecificOutput: {
815
- hookEventName: "UserPromptSubmit",
816
- additionalContext: `<remnic-memory count="${count}">\n${ctx}\n</remnic-memory>`,
817
- },
818
- });
819
- log(`done: ${count} memories injected`);
820
- }
821
- } catch {
822
- emit({ continue: true });
823
- }
824
- }
825
-
826
- // Background worker: lock + cursor + observe the transcript delta. Detached
827
- // from the foreground hook so a slow observe never blocks Codex past the
828
- // PostToolUse timeout.
829
- async function observeWorker(input, token, log) {
830
- const sessionId = input.session_id || "";
831
- const transcriptPath = input.transcript_path || "";
832
- const projectName = (input.cwd && path.basename(input.cwd)) || "unknown";
833
- const toolName = input.tool_name || "";
834
-
835
- if (!sessionId || /[^A-Za-z0-9._-]/.test(sessionId)) {
836
- log(`invalid session id: ${sessionId}`);
837
- return;
838
- }
839
- if (!transcriptPath || !fs.existsSync(transcriptPath) || !fs.statSync(transcriptPath).isFile()) {
840
- return;
841
- }
842
- const state = resolveState(sessionId, log);
843
- if (!state) return;
844
- const { cursorFile, lockFile } = state;
845
-
846
- if (!acquireLock(lockFile, log)) return;
847
- try {
848
- migrateTmpCursor(sessionId, cursorFile, log);
849
- const lastCount = readCursor(cursorFile, log);
850
- if (lastCount === null) return;
851
-
852
- let messages;
853
- try {
854
- messages = parseTranscript(transcriptPath);
855
- } catch {
856
- log(`parse failed for ${sessionId}`);
857
- return;
858
- }
859
- const newMessages = messages.slice(lastCount);
860
- if (newMessages.length === 0) {
861
- writeCursor(cursorFile, messages.length, log);
862
- return;
863
- }
864
- log(
865
- `observing ${newMessages.length} new messages (cursor ${lastCount}->${messages.length}) ` +
866
- `project=${projectName} tool=${toolName}`,
867
- );
868
- const res = await httpPost(
869
- "/engram/v1/observe",
870
- token,
871
- withNamespace({ sessionKey: sessionId, messages: newMessages }),
872
- 120000,
873
- );
874
- if (res.ok) {
875
- log(`observe OK for ${sessionId}`);
876
- writeCursor(cursorFile, messages.length, log);
877
- } else {
878
- log(`observe failed (http=${res.status}) — cursor not advanced`);
879
- }
880
- } finally {
881
- releaseLock(lockFile);
882
- }
883
- }
884
-
885
- function handlePostToolObserve(rawInput, input, token, log) {
886
- // Return immediately — never block the tool.
887
- emit({ continue: true });
888
- if (!token) return;
889
- // Spawn a detached copy to do the observe in the background (mirrors the
890
- // original `( … ) & disown`). Pass the raw hook payload via the worker's
891
- // STDIN, not the environment — Windows caps the environment block at ~32 KB,
892
- // so large PostToolUse payloads (big file edits, command output) would fail
893
- // with E2BIG/ENAMETOOLONG and the observation would silently drop (#1443
894
- // review). Stdin has no comparable limit.
895
- try {
896
- const child = spawn(process.execPath, [__filename, OBSERVE_WORKER], {
897
- detached: true,
898
- stdio: ["pipe", "ignore", "ignore"],
899
- env: { ...process.env, REMNIC_HOOK_TOKEN: token },
900
- });
901
- child.on("error", (e) => log(`observe worker spawn error: ${e && e.message}`));
902
- child.stdin.on("error", () => {
903
- /* ignore EPIPE if the worker exits before we finish writing */
904
- });
905
- child.stdin.end(rawInput);
906
- child.unref();
907
- } catch (err) {
908
- log(`failed to spawn observe worker: ${err && err.message}`);
909
- }
910
- }
911
-
912
- async function handleSessionEnd(input, token, log) {
913
- // Acknowledge immediately.
914
- emit({ continue: true });
915
-
916
- const sessionId = input.session_id || "";
917
- const transcriptPath = input.transcript_path || "";
918
- const safe = sessionId !== "" && !/[^A-Za-z0-9._-]/.test(sessionId);
919
-
920
- let state = null;
921
- if (safe) state = resolveState(sessionId, log);
922
-
923
- let removeCursorAfterFlush = true;
924
-
925
- if (token && state && transcriptPath && fs.existsSync(transcriptPath)) {
926
- const { cursorFile } = state;
927
- migrateTmpCursor(sessionId, cursorFile, log);
928
- const lastCount = readCursor(cursorFile, log);
929
- if (lastCount === null) {
930
- log(`final flush skipped for ${sessionId} due to unsafe cursor`);
931
- } else {
932
- let newMessages = null;
933
- try {
934
- newMessages = parseTranscript(transcriptPath).slice(lastCount);
935
- } catch {
936
- log(`final flush parse failed for ${sessionId}; cursor retained for retry`);
937
- removeCursorAfterFlush = false;
938
- }
939
- if (newMessages && newMessages.length > 0) {
940
- log(`final flush for ${sessionId}`);
941
- const res = await httpPost(
942
- "/engram/v1/observe",
943
- token,
944
- withNamespace({ sessionKey: sessionId, messages: newMessages }),
945
- 30000,
946
- );
947
- if (res.ok) {
948
- log(`final flush OK for ${sessionId}`);
949
- } else {
950
- // Critical: retain the cursor so the tail is retried, never lost.
951
- log(`final flush failed for ${sessionId} (http=${res.status}); cursor retained for retry`);
952
- removeCursorAfterFlush = false;
953
- }
954
- }
955
- }
956
- }
957
-
958
- // Cleanup — only remove the cursor when the flush succeeded or there was
959
- // nothing pending.
960
- if (state) {
961
- const { cursorFile, lockFile, legacyCursor, legacyLock } = state;
962
- if (removeCursorAfterFlush) removeCursor(cursorFile, log);
963
- releaseLock(lockFile);
964
- if (cursorFile !== legacyCursor) {
965
- try {
966
- const info = fs.lstatSync(legacyCursor);
967
- if (!info.isSymbolicLink()) fs.rmSync(legacyCursor, { force: true });
968
- } catch {
969
- /* absent */
970
- }
971
- }
972
- if (lockFile !== legacyLock) {
973
- try {
974
- fs.rmdirSync(legacyLock);
975
- } catch {
976
- /* absent */
977
- }
978
- }
979
- }
980
-
981
- runMaterialize(log);
982
- }
983
-
984
- // Drain any unobserved transcript tail to /engram/v1/observe under the
985
- // session's cursor/lock, advancing the cursor only on a successful observe.
986
- // Shared mid-session drain used by handlePreCompact (the session-end path in
987
- // handleSessionEnd has its own cursor-removal cleanup and is intentionally not
988
- // refactored onto this helper to avoid perturbing its retention semantics).
989
- //
990
- // Why this exists separately from the LCM flush: /engram/v1/lcm/compaction/flush
991
- // can only drain work ALREADY queued by prior /observe calls. If a turn landed
992
- // after the last PostToolUse (e.g. a long user prompt that triggers auto
993
- // compaction without a Bash tool call in between), that tail is still only in
994
- // the transcript and would be lost when Codex summarizes/replaces context. So
995
- // PreCompact must observe the delta FIRST, then ask LCM to flush.
996
- //
997
- // Returns "busy" when the session lock could not be acquired within the
998
- // caller's budget (a detached PostToolUse observe worker is still holding it),
999
- // so handlePreCompact can SKIP the flush instead of letting it drain nothing
1000
- // and race the worker; true when the tail was observed (or nothing pending);
1001
- // false on parse/observe failure (cursor retained) so the caller can still
1002
- // flush already-queued work. Always fail-open.
1003
- //
1004
- // `lockRetries` (100ms each) bounds how long to wait for a busy worker.
1005
- // The observe body is scoped via withNamespace() so the tail lands on the same
1006
- // key the LCM flush drains (see the namespace chokepoint above).
1007
- async function drainTranscriptTail(sessionId, transcriptPath, token, log, lockRetries = 50) {
1008
- const safe = sessionId !== "" && !/[^A-Za-z0-9._-]/.test(sessionId);
1009
- if (!safe || !token || !transcriptPath || !fs.existsSync(transcriptPath)) {
1010
- return false;
1011
- }
1012
- const state = resolveState(sessionId, log);
1013
- if (!state) return false;
1014
- const { cursorFile, lockFile } = state;
1015
- // The lock guards against the detached post-tool observe worker racing this
1016
- // drain. Wait up to the caller's budget for the worker to finish its /observe
1017
- // and release the lock — once it does, either the worker already advanced the
1018
- // cursor (nothing left to drain) or we observe the remaining delta, and in
1019
- // both cases the subsequent flush sees all queued work. Only if the worker
1020
- // outlasts our budget do we return "busy" so handlePreCompact SKIPS the flush
1021
- // rather than racing ahead of the worker's in-flight /observe.
1022
- if (!acquireLock(lockFile, log, lockRetries)) {
1023
- log(`transcript tail drain skipped for ${sessionId}: lock busy (worker still running)`);
1024
- return "busy";
1025
- }
1026
- try {
1027
- migrateTmpCursor(sessionId, cursorFile, log);
1028
- const lastCount = readCursor(cursorFile, log);
1029
- if (lastCount === null) {
1030
- log(`transcript tail drain skipped for ${sessionId}: unsafe cursor`);
1031
- return false;
1032
- }
1033
- let newMessages;
1034
- try {
1035
- newMessages = parseTranscript(transcriptPath).slice(lastCount);
1036
- } catch {
1037
- log(`transcript tail parse failed for ${sessionId}; cursor retained`);
1038
- return false;
1039
- }
1040
- if (newMessages.length === 0) return true;
1041
- log(`transcript tail drain: ${newMessages.length} new message(s) for ${sessionId}`);
1042
- const res = await httpPost(
1043
- "/engram/v1/observe",
1044
- token,
1045
- withNamespace({ sessionKey: sessionId, messages: newMessages }),
1046
- 30000,
1047
- );
1048
- if (res.ok) {
1049
- // Advance (not remove) the cursor — the session continues after compaction,
1050
- // so the post-compact transcript must not re-observe this tail.
1051
- writeCursor(cursorFile, lastCount + newMessages.length, log);
1052
- return true;
1053
- }
1054
- log(`transcript tail drain failed for ${sessionId} (http=${res.status}); cursor retained`);
1055
- return false;
1056
- } finally {
1057
- releaseLock(lockFile);
1058
- }
1059
- }
1060
-
1061
- // PreCompact (#1571) — coordinate with Remnic's LCM layer before Codex
1062
- // compacts the conversation. Mirrors @remnic/plugin-pi's session_before_compact
1063
- // handler, with one Codex-specific addition: because Codex observes
1064
- // asynchronously (PostToolUse on Bash + Stop), an unobserved transcript tail
1065
- // can exist when compaction fires mid-session. So we drain that tail to
1066
- // /engram/v1/observe FIRST, then POST /engram/v1/lcm/compaction/flush so the
1067
- // daemon flushes the now-complete observe buffer into long-term memory before
1068
- // the transcript is summarized. ALWAYS returns continue:true — a hook failure
1069
- // must never block Codex's compaction (the upstream contract notes
1070
- // continue:false stops the compact entirely), so this handler is fail-open
1071
- // end to end.
1072
- async function handlePreCompact(input, token, log) {
1073
- const sessionId = input.session_id || "";
1074
- const transcriptPath = input.transcript_path || "";
1075
- const trigger = input.trigger || "auto";
1076
- // Acknowledge first so Codex never waits on the network for compaction to
1077
- // proceed — the drain + flush are best-effort coordination, not a gate.
1078
- emit({ continue: true });
1079
- if (!token) {
1080
- log(`skipping pre-compact drain+flush: no token (session=${sessionId} trigger=${trigger})`);
1081
- return;
1082
- }
1083
- // 1. Drain any unobserved transcript tail so it's archived before compaction.
1084
- // Wait up to PRECOMPACT_LOCK_RETRIES for a concurrent observe worker to
1085
- // release the session lock, so the flush below sees the worker's queued
1086
- // messages. If the worker outlasts us, drain returns "busy" and we SKIP
1087
- // the flush entirely — flushing now would drain nothing and the worker's
1088
- // in-flight observe would miss this compaction, so we defer to the next
1089
- // PreCompact/Stop rather than race.
1090
- const drainResult = await drainTranscriptTail(
1091
- sessionId,
1092
- transcriptPath,
1093
- token,
1094
- log,
1095
- PRECOMPACT_LOCK_RETRIES,
1096
- );
1097
- if (drainResult === "busy") {
1098
- log(`skipping LCM flush: tail drain lock busy (session=${sessionId} trigger=${trigger}); deferring to next cycle`);
1099
- return;
1100
- }
1101
- // 2. Ask the LCM layer to flush the (now-complete) observe buffer. The body is
1102
- // scoped via withNamespace() so it drains the same key the observes wrote.
1103
- const res = await httpPost(
1104
- "/engram/v1/lcm/compaction/flush",
1105
- token,
1106
- withNamespace({ sessionKey: sessionId }),
1107
- 20000,
1108
- );
1109
- if (res.ok) {
1110
- log(`LCM compaction flush OK (session=${sessionId} trigger=${trigger})`);
1111
- } else {
1112
- // Fail-open: log and move on. Compaction proceeds regardless.
1113
- log(`LCM compaction flush failed (http=${res.status}) — compaction proceeds`);
1114
- }
1115
- }
1116
-
1117
- // ── Codex-native memory materialization (#378) ─────────────────────────────
1118
- function runMaterialize(log) {
1119
- if (process.env.REMNIC_CODEX_MATERIALIZE === "0") return;
1120
- const hookDir = __dirname;
1121
-
1122
- // 1. explicit override → 2. packaged bin → 3. dev tsx fallback.
1123
- let bin = process.env.REMNIC_CODEX_MATERIALIZE_BIN || "";
1124
- if (!bin) {
1125
- const candidate = path.join(hookDir, "..", "..", "bin", "materialize.cjs");
1126
- try {
1127
- if (fs.existsSync(candidate)) bin = fs.realpathSync(candidate);
1128
- } catch {
1129
- /* ignore */
1130
- }
1131
- }
1132
- let repoRoot = process.env.REMNIC_REPO_ROOT || "";
1133
- if (!repoRoot) {
1134
- try {
1135
- const candidateRoot = fs.realpathSync(path.join(hookDir, "..", "..", "..", ".."));
1136
- if (fs.existsSync(path.join(candidateRoot, "scripts", "codex-materialize.ts"))) {
1137
- repoRoot = candidateRoot;
1138
- }
1139
- } catch {
1140
- /* ignore */
1141
- }
1142
- }
1143
-
1144
- // Force HOME to the home dir the runner resolved (HOME → USERPROFILE →
1145
- // os.homedir()). The materializer resolves config paths from HOME and only
1146
- // falls back to os.homedir(); on Windows, where HOME is typically unset,
1147
- // passing it explicitly guarantees the child uses the SAME home as the hook
1148
- // instead of diverging (#1443 review).
1149
- const childEnv = { ...process.env, HOME };
1150
- try {
1151
- if (bin && fs.existsSync(bin)) {
1152
- const r = spawnSync(process.execPath, [bin, "--reason", "session_end"], {
1153
- stdio: "ignore",
1154
- timeout: 60000,
1155
- env: childEnv,
1156
- });
1157
- if (r.status !== 0) log(`codex-materialize session_end failed (packaged bin=${bin})`);
1158
- } else if (repoRoot) {
1159
- const r = spawnSync("npx", ["--yes", "tsx", "scripts/codex-materialize.ts", "--reason", "session_end"], {
1160
- cwd: repoRoot,
1161
- stdio: "ignore",
1162
- timeout: 120000,
1163
- shell: process.platform === "win32",
1164
- env: childEnv,
1165
- });
1166
- if (r.status !== 0) log("codex-materialize session_end failed (dev script)");
1167
- } else {
1168
- log(`codex-materialize skipped — could not resolve packaged bin or REMNIC_REPO_ROOT (hook_dir=${hookDir})`);
1169
- }
1170
- } catch (err) {
1171
- log(`codex-materialize error: ${err && err.message}`);
1172
- }
1173
- }
1174
-
1175
- // ── entrypoint ─────────────────────────────────────────────────────────────
1176
- async function main() {
1177
- const event = process.argv[2] || "";
1178
-
1179
- // Detached background worker for post-tool-observe.
1180
- if (event === OBSERVE_WORKER) {
1181
- const log = makeLogger("post-tool-observe");
1182
- try {
1183
- const raw = readStdin();
1184
- const input = parseInput(raw);
1185
- const token = process.env.REMNIC_HOOK_TOKEN || resolveToken();
1186
- if (token) await observeWorker(input, token, log);
1187
- } catch (err) {
1188
- log(`observe worker error: ${err && err.message}`);
1189
- }
1190
- return;
1191
- }
1192
-
1193
- if (!Object.prototype.hasOwnProperty.call(LOG_FILES, event)) {
1194
- // Unknown event — fail open without side effects.
1195
- emit({ continue: true });
1196
- if (event) process.stderr.write(`remnic-codex-hook: unknown event "${event}"\n`);
1197
- return;
1198
- }
1199
-
1200
- const log = makeLogger(event);
1201
- const raw = readStdin();
1202
- const input = parseInput(raw);
1203
-
1204
- try {
1205
- ensureMigrated();
1206
- const token = resolveToken();
1207
- switch (event) {
1208
- case "session-start":
1209
- await handleSessionStart(input, token, log);
1210
- break;
1211
- case "user-prompt-recall":
1212
- await handleUserPromptRecall(input, token, log);
1213
- break;
1214
- case "post-tool-observe":
1215
- handlePostToolObserve(raw, input, token, log);
1216
- break;
1217
- case "session-end":
1218
- await handleSessionEnd(input, token, log);
1219
- break;
1220
- case "pre-compact":
1221
- await handlePreCompact(input, token, log);
1222
- break;
1223
- }
1224
- } catch (err) {
1225
- log(`unhandled error in ${event}: ${err && err.message}`);
1226
- // Best-effort fail-open: emit a bare continue only if we haven't already.
1227
- if (!emitted) {
1228
- try {
1229
- emit({ continue: true });
1230
- } catch {
1231
- /* stdout already written */
1232
- }
1233
- }
1234
- }
1235
- }
1236
-
1237
- main();
24
+ const { run } = require("./remnic-hook-core.cjs");
25
+
26
+ run({
27
+ client: "codex",
28
+ tokenConnectors: ["codex-cli", "codex", "openclaw"],
29
+ connectorInstall: "codex-cli",
30
+ progName: "remnic-codex-hook",
31
+ defaultLogFile: "remnic-codex-hook.log",
32
+ logFiles: {
33
+ "session-start": "remnic-session-recall.log",
34
+ "user-prompt-recall": "remnic-user-prompt-recall.log",
35
+ "post-tool-observe": "remnic-post-tool-observe.log",
36
+ "session-end": "remnic-codex-session-end.log",
37
+ "pre-compact": "remnic-pre-compact.log",
38
+ },
39
+ logTags: {
40
+ "session-start": "codex-session-start",
41
+ "user-prompt-recall": "codex-user-prompt",
42
+ "post-tool-observe": "codex-post-tool",
43
+ "session-end": "codex-stop",
44
+ "pre-compact": "codex-pre-compact",
45
+ },
46
+ enablePreCompact: true,
47
+ enableMaterialize: true,
48
+ });