@remnic/plugin-claude-code 10.0.120 → 10.0.122

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,7 +1,7 @@
1
1
  {
2
2
  "name": "remnic",
3
3
  "description": "Universal memory for AI agents — automatic recall, observation, and cross-agent knowledge sharing",
4
- "version": "10.0.120",
4
+ "version": "10.0.122",
5
5
  "author": {
6
6
  "name": "Joshua Warren"
7
7
  },
@@ -107,12 +107,56 @@ function run(config) {
107
107
  // becomes "/remnic/engram/v1/observe"; a bare root ("/") yields "".
108
108
  const DAEMON_BASE_PATH = DAEMON_URL ? DAEMON_URL.pathname.replace(/\/+$/, "") : "";
109
109
 
110
+ // URL.hostname keeps the brackets on IPv6 literals ("[::1]"); Node's
111
+ // http(s).request options.hostname does not accept them, so strip them
112
+ // once here for every request path below.
113
+ const DAEMON_HOSTNAME = DAEMON_URL
114
+ ? DAEMON_URL.hostname.replace(/^\[|\]$/g, "")
115
+ : "";
116
+
117
+ // Plain-http daemon URLs to non-loopback hosts send the bearer token
118
+ // cleartext. Remote-daemon-over-http is a supported deployment shape
119
+ // (trusted LAN/Tailscale), so this warns rather than refuses — but the
120
+ // operator should see the exposure once per hook invocation batch.
121
+ if (DAEMON_URL && DAEMON_URL.protocol === "http:" && !isLoopbackHost(DAEMON_HOSTNAME)) {
122
+ if (process.env.REMNIC_HOOK_QUIET !== "1") {
123
+ try {
124
+ process.stderr.write(
125
+ `[${PROG_NAME}] REMNIC_DAEMON_URL uses plain http:// to a non-loopback host; ` +
126
+ "the bearer token will be sent cleartext — prefer https:// for remote daemons.\n",
127
+ );
128
+ } catch {}
129
+ }
130
+ }
131
+
132
+ function isLoopbackHost(hostname) {
133
+ const h = (hostname || "").toLowerCase();
134
+ if (h === "localhost") return true;
135
+ if (h === "::1") return true;
136
+ return /^127(?:\.\d{1,3}){3}$/.test(h);
137
+ }
138
+
110
139
  // Internal re-entrant mode: post-tool-observe spawns a detached copy of
111
140
  // itself so the (slow) observe runs in the background and never blocks the
112
141
  // host past the short PostToolUse timeout — mirroring the original
113
142
  // `( … ) & disown`.
114
143
  const OBSERVE_WORKER = "__observe-worker__";
115
144
 
145
+ // Detached worker that retries the SessionEnd tail drain after lock
146
+ // contention. The foreground session-end hook gives up after ~5s so the
147
+ // host is never blocked; this worker waits longer for a still-running
148
+ // observe worker to release the session lock, then performs the same
149
+ // drain + cursor cleanup.
150
+ const SESSION_END_DRAIN = "__session-end-drain__";
151
+
152
+ // Lock-wait budget (100ms each → ~120s) for the detached session-end
153
+ // drain: an in-flight observe worker's /engram/v1/observe can take up to
154
+ // 120s, so the drain waits roughly that long before giving up and leaving
155
+ // cursor state for the stale-lock reaper.
156
+ const _sedRaw = process.env.REMNIC_SESSION_END_DRAIN_LOCK_RETRIES;
157
+ const _sedParsed = _sedRaw != null && _sedRaw !== "" ? Number.parseInt(_sedRaw, 10) : 1200;
158
+ const SESSION_END_DRAIN_LOCK_RETRIES = Number.isFinite(_sedParsed) && _sedParsed >= 0 ? _sedParsed : 1200;
159
+
116
160
  // PreCompact tail-drain lock-wait budget (100ms each → ~15s). Bounds how
117
161
  // long handlePreCompact waits for a detached PostToolUse observe worker
118
162
  // (whose own /observe can run up to 120s) to release the session lock
@@ -323,7 +367,7 @@ function run(config) {
323
367
  const req = transport.request(
324
368
  {
325
369
  protocol: DAEMON_URL.protocol,
326
- hostname: DAEMON_URL.hostname,
370
+ hostname: DAEMON_HOSTNAME,
327
371
  port: DAEMON_URL.port || (DAEMON_URL.protocol === "https:" ? 443 : 80),
328
372
  path: DAEMON_BASE_PATH + urlPath,
329
373
  method: "POST",
@@ -384,7 +428,7 @@ function run(config) {
384
428
  const req = transport.request(
385
429
  {
386
430
  protocol: DAEMON_URL.protocol,
387
- hostname: DAEMON_URL.hostname,
431
+ hostname: DAEMON_HOSTNAME,
388
432
  port: DAEMON_URL.port || (DAEMON_URL.protocol === "https:" ? 443 : 80),
389
433
  path: DAEMON_BASE_PATH + path,
390
434
  method: "GET",
@@ -490,7 +534,9 @@ function run(config) {
490
534
  }
491
535
 
492
536
  // ── transcript parsing ─────────────────────────────────────────────────────
493
- function parseTranscript(transcriptPath) {
537
+ // JSONL hosts (Claude Code, Codex): one JSON object per line with
538
+ // {type:"user"|"assistant", message:{role, content}}.
539
+ function parseJsonlTranscript(transcriptPath) {
494
540
  const lines = fs.readFileSync(transcriptPath, "utf8").split("\n").filter(Boolean);
495
541
  const messages = [];
496
542
  for (const line of lines) {
@@ -518,6 +564,118 @@ function run(config) {
518
564
  return messages;
519
565
  }
520
566
 
567
+ // ATIF hosts (Devin CLI): a single JSON document
568
+ // {schema_version, session_id, steps:[{source, message, tool_calls,
569
+ // observation, ...}]}. Agent steps carry tool_calls and observation
570
+ // results alongside the assistant text; we fold a bounded rendering of
571
+ // both into the observed content so tool activity reaches memory, not
572
+ // just prose. System steps are skipped (they are prompt scaffolding).
573
+ const ATIF_MESSAGE_CAP = 8000;
574
+ const ATIF_TOOL_CALL_ARG_CAP = 500;
575
+ const ATIF_TOOL_RESULT_CAP = 2000;
576
+ // JSON.parse only yields plain objects, arrays, and primitives, so
577
+ // `instanceof Object && !Array.isArray` is an exact plain-object test.
578
+ function isJsonObject(v) {
579
+ return v instanceof Object && !Array.isArray(v);
580
+ }
581
+ function isString(v) {
582
+ return Object.prototype.toString.call(v) === "[object String]";
583
+ }
584
+ // ATIF `message` and `content` are a string or an array of ContentPart
585
+ // objects. Return the concatenated text of text parts; images are skipped.
586
+ function atifText(v) {
587
+ if (isString(v)) return v;
588
+ if (!Array.isArray(v)) return "";
589
+ return v
590
+ .filter((p) => isJsonObject(p) && p.type === "text" && isString(p.text))
591
+ .map((p) => p.text)
592
+ .join("\n");
593
+ }
594
+ function parseAtifTranscript(transcriptPath) {
595
+ const doc = JSON.parse(fs.readFileSync(transcriptPath, "utf8"));
596
+ const steps = doc && Array.isArray(doc.steps) ? doc.steps : [];
597
+ const messages = [];
598
+ for (const step of steps) {
599
+ if (!isJsonObject(step)) continue;
600
+ const source = step.source;
601
+ if (source !== "user" && source !== "agent") continue;
602
+ const parts = [];
603
+ const message = atifText(step.message).trim();
604
+ if (message) {
605
+ parts.push(message);
606
+ }
607
+ if (source === "agent") {
608
+ const toolCalls = Array.isArray(step.tool_calls) ? step.tool_calls : [];
609
+ for (const tc of toolCalls) {
610
+ if (!isJsonObject(tc)) continue;
611
+ const name = tc.function_name || tc.name || "tool";
612
+ let argStr = "";
613
+ try {
614
+ argStr = isString(tc.arguments)
615
+ ? tc.arguments
616
+ : JSON.stringify(tc.arguments);
617
+ } catch {
618
+ argStr = "";
619
+ }
620
+ if (argStr && argStr !== "{}") {
621
+ parts.push(`[tool call] ${name}(${argStr.slice(0, ATIF_TOOL_CALL_ARG_CAP)})`);
622
+ } else {
623
+ parts.push(`[tool call] ${name}`);
624
+ }
625
+ }
626
+ const results =
627
+ step.observation && Array.isArray(step.observation.results)
628
+ ? step.observation.results
629
+ : [];
630
+ for (const r of results) {
631
+ const content = isJsonObject(r) ? atifText(r.content) : "";
632
+ if (content.trim()) {
633
+ parts.push(`[tool result] ${content.trim().slice(0, ATIF_TOOL_RESULT_CAP)}`);
634
+ }
635
+ }
636
+ }
637
+ const content = parts.join("\n").trim();
638
+ if (!content) continue;
639
+ messages.push({
640
+ role: source === "user" ? "user" : "assistant",
641
+ content: content.slice(0, ATIF_MESSAGE_CAP),
642
+ });
643
+ }
644
+ return messages;
645
+ }
646
+
647
+ function parseTranscript(transcriptPath) {
648
+ if (config.transcriptFormat === "atif") return parseAtifTranscript(transcriptPath);
649
+ return parseJsonlTranscript(transcriptPath);
650
+ }
651
+
652
+ // Hosts that do not put transcript_path in the hook payload (Devin CLI)
653
+ // can supply config.resolveTranscriptPath(input) to derive it — e.g. from
654
+ // the session id and a well-known transcript directory.
655
+ function transcriptPathFor(input) {
656
+ const transcriptPath = input.transcript_path || "";
657
+ if (isString(transcriptPath) && transcriptPath) {
658
+ return transcriptPath;
659
+ }
660
+ if (config.resolveTranscriptPath instanceof Function) {
661
+ try {
662
+ const resolved = config.resolveTranscriptPath(input);
663
+ return isString(resolved) ? resolved : "";
664
+ } catch {
665
+ return "";
666
+ }
667
+ }
668
+ return "";
669
+ }
670
+
671
+ // Hosts that omit cwd from the hook payload still export a project-dir
672
+ // env var (Devin: DEVIN_PROJECT_DIR; Claude Code compat: CLAUDE_PROJECT_DIR).
673
+ function cwdFor(input) {
674
+ const cwd = input.cwd || "";
675
+ if (isString(cwd) && cwd) return cwd;
676
+ return process.env.DEVIN_PROJECT_DIR || process.env.CLAUDE_PROJECT_DIR || "";
677
+ }
678
+
521
679
  // ── cursor / lock state hardening (post-tool + session-end) ────────────────
522
680
  const SELF_UID = typeof process.getuid === "function" ? process.getuid() : null;
523
681
 
@@ -564,7 +722,8 @@ function run(config) {
564
722
  cursorFile = legacyCursor;
565
723
  lockFile = legacyLock;
566
724
  }
567
- return { cursorFile, lockFile, legacyCursor, legacyLock };
725
+ const doneFile = path.join(stateDir, `remnic-done-${sessionId}`);
726
+ return { cursorFile, lockFile, doneFile, legacyCursor, legacyLock };
568
727
  }
569
728
 
570
729
  // true if the cursor file is safe to read/write (or absent).
@@ -620,6 +779,44 @@ function run(config) {
620
779
  return true;
621
780
  }
622
781
 
782
+ // Completion tombstone: written by the session-end drain once the final
783
+ // flush succeeds (or there is nothing left to flush). Its content is the
784
+ // observed-message checkpoint, which handleSessionStart restores into the
785
+ // cursor when a session resumes under the same id. Detached observe
786
+ // workers queued behind the session lock check this under the lock and
787
+ // exit instead of treating the missing cursor as 0 and replaying the
788
+ // whole transcript. The file is tiny and persists for the life of the
789
+ // state dir, like leftover locks from crashed sessions.
790
+ function sessionDone(doneFile) {
791
+ try {
792
+ const info = fs.lstatSync(doneFile);
793
+ return !info.isSymbolicLink() && info.isFile() && ownedByUs(info);
794
+ } catch {
795
+ return false;
796
+ }
797
+ }
798
+
799
+ function markSessionDone(doneFile, checkpoint, log) {
800
+ try {
801
+ const tmp = `${doneFile}.tmp.${process.pid}`;
802
+ fs.writeFileSync(tmp, `${checkpoint}\n`, { mode: 0o600 });
803
+ fs.renameSync(tmp, doneFile);
804
+ return true;
805
+ } catch (err) {
806
+ log(`failed to write session-done marker ${doneFile}: ${err && err.message}`);
807
+ return false;
808
+ }
809
+ }
810
+
811
+ function readDoneCheckpoint(doneFile) {
812
+ try {
813
+ const n = parseInt(fs.readFileSync(doneFile, "utf8").trim(), 10);
814
+ return Number.isFinite(n) && n >= 0 ? n : null;
815
+ } catch {
816
+ return null;
817
+ }
818
+ }
819
+
623
820
  // Adopt a higher os.tmpdir() (or /tmp) cursor written by an older
624
821
  // cross-process run, then clean.
625
822
  function migrateTmpCursor(sessionId, cursorFile, log) {
@@ -703,11 +900,31 @@ function run(config) {
703
900
 
704
901
  async function handleSessionStart(input, token, log) {
705
902
  const sessionId = input.session_id || "";
706
- const cwd = input.cwd || "";
903
+ const cwd = cwdFor(input);
707
904
  const projectName = (cwd && path.basename(cwd)) || "unknown";
708
905
  const codingContext = resolveCodingContext(cwd);
709
906
  log(`session=${sessionId} project=${projectName} coding-context=${codingContext ? "yes" : ""}`);
710
907
 
908
+ // A session-start means this session id is active again — Devin and
909
+ // Claude Code reuse the id across resume. Restore the observation
910
+ // checkpoint stored in the done tombstone into the cursor, then clear
911
+ // the tombstone so queued and future workers observe the new tail
912
+ // instead of exiting early. Without this, a resumed session would never
913
+ // observe again.
914
+ if (sessionId && !/[^A-Za-z0-9._-]/.test(sessionId)) {
915
+ const st = resolveState(sessionId, log);
916
+ if (st && sessionDone(st.doneFile)) {
917
+ const checkpoint = readDoneCheckpoint(st.doneFile);
918
+ if (checkpoint !== null) writeCursor(st.cursorFile, checkpoint, log);
919
+ try {
920
+ fs.rmSync(st.doneFile, { force: true });
921
+ } catch {
922
+ /* best effort */
923
+ }
924
+ log(`cleared done marker for session ${sessionId} (checkpoint=${checkpoint})`);
925
+ }
926
+ }
927
+
711
928
  // Health check — start daemon if not running.
712
929
  if (!(await httpHealthy(2000, token))) {
713
930
  log("daemon not responding, attempting start...");
@@ -860,8 +1077,8 @@ function run(config) {
860
1077
  // PostToolUse timeout.
861
1078
  async function observeWorker(input, token, log) {
862
1079
  const sessionId = input.session_id || "";
863
- const transcriptPath = input.transcript_path || "";
864
- const projectName = (input.cwd && path.basename(input.cwd)) || "unknown";
1080
+ const transcriptPath = transcriptPathFor(input);
1081
+ const projectName = (cwdFor(input) && path.basename(cwdFor(input))) || "unknown";
865
1082
  const toolName = input.tool_name || "";
866
1083
 
867
1084
  if (!sessionId || /[^A-Za-z0-9._-]/.test(sessionId)) {
@@ -877,6 +1094,13 @@ function run(config) {
877
1094
 
878
1095
  if (!acquireLock(lockFile, log)) return;
879
1096
  try {
1097
+ // A queued worker that acquires the lock after SessionEnd removed the
1098
+ // cursor must not treat the missing cursor as 0 and replay the whole
1099
+ // transcript — the done tombstone marks completed sessions.
1100
+ if (sessionDone(state.doneFile)) {
1101
+ log(`session ${sessionId} already flushed; skipping queued observe`);
1102
+ return;
1103
+ }
880
1104
  migrateTmpCursor(sessionId, cursorFile, log);
881
1105
  const lastCount = readCursor(cursorFile, log);
882
1106
  if (lastCount === null) return;
@@ -941,73 +1165,138 @@ function run(config) {
941
1165
  }
942
1166
  }
943
1167
 
944
- async function handleSessionEnd(input, token, log) {
1168
+ async function handleSessionEnd(input, token, log, raw, opts) {
1169
+ const drainRetry = !!(opts && opts.drainRetry);
945
1170
  // Acknowledge immediately.
946
1171
  emit({ continue: true });
947
1172
 
948
1173
  const sessionId = input.session_id || "";
949
- const transcriptPath = input.transcript_path || "";
1174
+ const transcriptPath = transcriptPathFor(input);
950
1175
  const safe = sessionId !== "" && !/[^A-Za-z0-9._-]/.test(sessionId);
951
1176
 
952
1177
  let state = null;
953
1178
  if (safe) state = resolveState(sessionId, log);
954
1179
 
955
- let removeCursorAfterFlush = true;
956
-
957
- if (token && state && transcriptPath && fs.existsSync(transcriptPath)) {
958
- const { cursorFile } = state;
959
- migrateTmpCursor(sessionId, cursorFile, log);
960
- const lastCount = readCursor(cursorFile, log);
961
- if (lastCount === null) {
962
- log(`final flush skipped for ${sessionId} due to unsafe cursor`);
963
- } else {
964
- let newMessages = null;
965
- try {
966
- newMessages = parseTranscript(transcriptPath).slice(lastCount);
967
- } catch {
968
- log(`final flush parse failed for ${sessionId}; cursor retained for retry`);
969
- removeCursorAfterFlush = false;
970
- }
971
- if (newMessages && newMessages.length > 0) {
972
- log(`final flush for ${sessionId}`);
973
- const res = await httpPost(
974
- "/engram/v1/observe",
975
- token,
976
- { sessionKey: sessionId, messages: newMessages },
977
- 30000,
978
- );
979
- if (res.ok) {
980
- log(`final flush OK for ${sessionId}`);
981
- } else {
982
- // Critical: retain the cursor so the tail is retried, never lost.
983
- log(`final flush failed for ${sessionId} (http=${res.status}); cursor retained for retry`);
984
- removeCursorAfterFlush = false;
1180
+ // Serialize the final drain and cleanup with the per-session lock so a
1181
+ // still-running detached observe worker cannot race the cursor read,
1182
+ // duplicate the tail observation, or have its lock removed mid-flight.
1183
+ // The foreground hook waits ~5s; on contention it hands the drain to a
1184
+ // detached worker with a much longer budget so messages that land after
1185
+ // the in-flight worker's snapshot are still observed before the session
1186
+ // state is cleaned up. If even that worker gives up, cursor and lock stay
1187
+ // for the stale-lock reaper — a forced cleanup could drop queued work.
1188
+ let lockAcquired = false;
1189
+ if (state) {
1190
+ lockAcquired = acquireLock(
1191
+ state.lockFile,
1192
+ log,
1193
+ drainRetry ? SESSION_END_DRAIN_LOCK_RETRIES : 50,
1194
+ );
1195
+ if (!lockAcquired) {
1196
+ log(`final flush skipped for ${sessionId}: session lock busy`);
1197
+ if (!drainRetry && raw) {
1198
+ try {
1199
+ const child = spawn(process.execPath, [ENTRY_FILE, SESSION_END_DRAIN], {
1200
+ detached: true,
1201
+ stdio: ["pipe", "ignore", "ignore"],
1202
+ env: { ...process.env, REMNIC_HOOK_TOKEN: token || "" },
1203
+ });
1204
+ child.on("error", (e) => log(`session-end drain spawn error: ${e && e.message}`));
1205
+ child.stdin.on("error", () => {
1206
+ /* ignore EPIPE if the worker exits before we finish writing */
1207
+ });
1208
+ child.stdin.end(raw);
1209
+ child.unref();
1210
+ } catch (err) {
1211
+ log(`failed to spawn session-end drain: ${err && err.message}`);
985
1212
  }
986
1213
  }
1214
+ if (config.enableMaterialize && !drainRetry) runMaterialize(log);
1215
+ return;
987
1216
  }
988
1217
  }
989
1218
 
990
- // Cleanup — only remove the cursor when the flush succeeded or there was
991
- // nothing pending.
992
- if (state) {
993
- const { cursorFile, lockFile, legacyCursor, legacyLock } = state;
994
- if (removeCursorAfterFlush) removeCursor(cursorFile, log);
995
- releaseLock(lockFile);
996
- if (cursorFile !== legacyCursor) {
997
- try {
998
- const info = fs.lstatSync(legacyCursor);
999
- if (!info.isSymbolicLink()) fs.rmSync(legacyCursor, { force: true });
1000
- } catch {
1001
- /* absent */
1219
+ // `finalized` becomes true only when the tail was observed or confirmed
1220
+ // empty — the done tombstone (which stores the observed-message
1221
+ // checkpoint) is written solely then. The cursor is removed only after
1222
+ // the marker lands; if marker creation fails the checkpointed cursor
1223
+ // stays, so a queued worker reads the observed count instead of
1224
+ // replaying from 0. When the drain cannot run at all (no token, no
1225
+ // transcript, unsafe cursor, parse or observe failure) neither the
1226
+ // marker nor the cursor changes, leaving state intact for a retry.
1227
+ let finalized = false;
1228
+ let checkpoint = 0;
1229
+
1230
+ try {
1231
+ if (state && sessionDone(state.doneFile)) {
1232
+ log(`final flush skipped for ${sessionId}: session already marked done`);
1233
+ } else if (state && token && transcriptPath && fs.existsSync(transcriptPath)) {
1234
+ const { cursorFile } = state;
1235
+ migrateTmpCursor(sessionId, cursorFile, log);
1236
+ const lastCount = readCursor(cursorFile, log);
1237
+ if (lastCount === null) {
1238
+ log(`final flush skipped for ${sessionId} due to unsafe cursor`);
1239
+ } else {
1240
+ let messages = null;
1241
+ try {
1242
+ messages = parseTranscript(transcriptPath);
1243
+ } catch {
1244
+ log(`final flush parse failed for ${sessionId}; cursor retained for retry`);
1245
+ }
1246
+ const newMessages = messages ? messages.slice(lastCount) : null;
1247
+ if (newMessages && newMessages.length > 0) {
1248
+ log(`final flush for ${sessionId}`);
1249
+ const res = await httpPost(
1250
+ "/engram/v1/observe",
1251
+ token,
1252
+ { sessionKey: sessionId, messages: newMessages },
1253
+ 30000,
1254
+ );
1255
+ if (res.ok) {
1256
+ log(`final flush OK for ${sessionId}`);
1257
+ writeCursor(cursorFile, messages.length, log);
1258
+ checkpoint = messages.length;
1259
+ finalized = true;
1260
+ } else {
1261
+ // Critical: retain the cursor so the tail is retried, never lost.
1262
+ log(`final flush failed for ${sessionId} (http=${res.status}); cursor retained for retry`);
1263
+ }
1264
+ } else if (newMessages) {
1265
+ // Confirmed empty tail — nothing left to observe.
1266
+ writeCursor(cursorFile, messages.length, log);
1267
+ checkpoint = messages.length;
1268
+ finalized = true;
1269
+ }
1002
1270
  }
1271
+ } else {
1272
+ log(`final flush skipped for ${sessionId}: drain unavailable; cursor retained`);
1003
1273
  }
1004
- if (lockFile !== legacyLock) {
1005
- try {
1006
- fs.rmdirSync(legacyLock);
1007
- } catch {
1008
- /* absent */
1274
+
1275
+ // Tombstone + legacy migration cleanup. The lock we hold is released
1276
+ // in `finally`.
1277
+ if (state) {
1278
+ const { cursorFile, doneFile, legacyCursor, legacyLock } = state;
1279
+ if (finalized && markSessionDone(doneFile, checkpoint, log)) {
1280
+ removeCursor(cursorFile, log);
1281
+ }
1282
+ if (cursorFile !== legacyCursor) {
1283
+ try {
1284
+ const info = fs.lstatSync(legacyCursor);
1285
+ if (!info.isSymbolicLink()) fs.rmSync(legacyCursor, { force: true });
1286
+ } catch {
1287
+ /* absent */
1288
+ }
1289
+ }
1290
+ if (state.lockFile !== legacyLock) {
1291
+ try {
1292
+ fs.rmdirSync(legacyLock);
1293
+ } catch {
1294
+ /* absent */
1295
+ }
1009
1296
  }
1010
1297
  }
1298
+ } finally {
1299
+ if (lockAcquired && state) releaseLock(state.lockFile);
1011
1300
  }
1012
1301
 
1013
1302
  if (config.enableMaterialize) runMaterialize(log);
@@ -1057,6 +1346,7 @@ function run(config) {
1057
1346
  return "busy";
1058
1347
  }
1059
1348
  try {
1349
+ if (sessionDone(state.doneFile)) return true;
1060
1350
  migrateTmpCursor(sessionId, cursorFile, log);
1061
1351
  const lastCount = readCursor(cursorFile, log);
1062
1352
  if (lastCount === null) {
@@ -1105,7 +1395,7 @@ function run(config) {
1105
1395
  // compact entirely), so this handler is fail-open end to end.
1106
1396
  async function handlePreCompact(input, token, log) {
1107
1397
  const sessionId = input.session_id || "";
1108
- const transcriptPath = input.transcript_path || "";
1398
+ const transcriptPath = transcriptPathFor(input);
1109
1399
  const trigger = input.trigger || "auto";
1110
1400
  // Acknowledge first so the host never waits on the network for compaction
1111
1401
  // to proceed — the drain + flush are best-effort coordination, not a gate.
@@ -1223,6 +1513,20 @@ function run(config) {
1223
1513
  return;
1224
1514
  }
1225
1515
 
1516
+ // Detached retry of the SessionEnd tail drain after lock contention.
1517
+ if (event === SESSION_END_DRAIN) {
1518
+ const log = makeLogger("session-end");
1519
+ try {
1520
+ const raw = readStdin();
1521
+ const input = parseInput(raw);
1522
+ const token = process.env.REMNIC_HOOK_TOKEN || resolveToken();
1523
+ await handleSessionEnd(input, token, log, raw, { drainRetry: true });
1524
+ } catch (err) {
1525
+ log(`session-end drain error: ${err && err.message}`);
1526
+ }
1527
+ return;
1528
+ }
1529
+
1226
1530
  if (!Object.prototype.hasOwnProperty.call(LOG_FILES, event)) {
1227
1531
  // Unknown event — fail open without side effects.
1228
1532
  emit({ continue: true });
@@ -1240,7 +1544,12 @@ function run(config) {
1240
1544
  "post-tool-observe": handlePostToolObserve,
1241
1545
  "session-end": handleSessionEnd,
1242
1546
  };
1243
- if (config.enablePreCompact) handlers["pre-compact"] = handlePreCompact;
1547
+ if (config.enablePreCompact) {
1548
+ handlers["pre-compact"] = handlePreCompact;
1549
+ // Devin CLI emits PostCompaction (after the fact) rather than a
1550
+ // pre-compact event; the drain+flush is equally correct there.
1551
+ handlers["post-compaction"] = handlePreCompact;
1552
+ }
1244
1553
 
1245
1554
  try {
1246
1555
  ensureMigrated();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remnic/plugin-claude-code",
3
- "version": "10.0.120",
3
+ "version": "10.0.122",
4
4
  "description": "Remnic memory plugin for Claude Code — hooks, skills, MCP integration",
5
5
  "type": "module",
6
6
  "license": "MIT",