agent-recall-core 3.4.41 → 3.4.43

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.
Files changed (40) hide show
  1. package/dist/host-profile.d.ts +35 -0
  2. package/dist/host-profile.d.ts.map +1 -1
  3. package/dist/host-profile.js +37 -0
  4. package/dist/host-profile.js.map +1 -1
  5. package/dist/index.d.ts +4 -2
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +3 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/storage/archive-write.d.ts.map +1 -1
  10. package/dist/storage/archive-write.js +13 -2
  11. package/dist/storage/archive-write.js.map +1 -1
  12. package/dist/storage/consolidation-queue.d.ts.map +1 -1
  13. package/dist/storage/consolidation-queue.js +48 -6
  14. package/dist/storage/consolidation-queue.js.map +1 -1
  15. package/dist/storage/recency-index.d.ts +20 -0
  16. package/dist/storage/recency-index.d.ts.map +1 -1
  17. package/dist/storage/recency-index.js +66 -2
  18. package/dist/storage/recency-index.js.map +1 -1
  19. package/dist/storage/session-card.d.ts +20 -4
  20. package/dist/storage/session-card.d.ts.map +1 -1
  21. package/dist/storage/session-card.js +19 -5
  22. package/dist/storage/session-card.js.map +1 -1
  23. package/dist/storage/working-memory.d.ts +257 -0
  24. package/dist/storage/working-memory.d.ts.map +1 -0
  25. package/dist/storage/working-memory.js +615 -0
  26. package/dist/storage/working-memory.js.map +1 -0
  27. package/dist/tools-logic/resurrect.d.ts +9 -2
  28. package/dist/tools-logic/resurrect.d.ts.map +1 -1
  29. package/dist/tools-logic/resurrect.js +43 -2
  30. package/dist/tools-logic/resurrect.js.map +1 -1
  31. package/dist/tools-logic/session-end.d.ts.map +1 -1
  32. package/dist/tools-logic/session-end.js +118 -15
  33. package/dist/tools-logic/session-end.js.map +1 -1
  34. package/dist/tools-logic/session-start.d.ts +12 -0
  35. package/dist/tools-logic/session-start.d.ts.map +1 -1
  36. package/dist/tools-logic/session-start.js +79 -1
  37. package/dist/tools-logic/session-start.js.map +1 -1
  38. package/dist/types.d.ts +1 -1
  39. package/dist/types.js +1 -1
  40. package/package.json +1 -1
@@ -0,0 +1,615 @@
1
+ /**
2
+ * working-memory.ts — minutes-level, crash-proof capture tier
3
+ * (v3.4.42 working-memory wave, design doc
4
+ * reports/2026-08-04-working-memory-design.md).
5
+ *
6
+ * WHY: through v3.4.41, AR writes nothing until the Stop hook fires — a
7
+ * crash, `kill -9`, or a context-compact vaporizes the entire live session,
8
+ * and two concurrent Claude Code windows are mutually blind to each other.
9
+ * Owner intent (2026-07-31, verbatim spirit): "like a human brain — you can
10
+ * forget, you can decay, but you need to know what happened 10 minutes
11
+ * before, 5 minutes before." This module is the ONLY new storage primitive
12
+ * for that tier: one JSONL file per session id, appended to on every
13
+ * UserPromptSubmit (hook-ambient), read at hook-start for the cross-window
14
+ * "live" signal and for orphan rescue, and deleted once a session reaches a
15
+ * normal, successful hook-end. WM is NEVER archived — natural forgetting by
16
+ * design; it is a minutes-level cache, not a permanent record.
17
+ *
18
+ * Storage shape: `<AR_ROOT>/working-memory/<sid>.jsonl`, one JSON line per
19
+ * prompt, PLUS a small sidecar counter file `<sid>.jsonl.count` (a bare
20
+ * decimal integer) used ONLY to enforce the per-file line cap in O(1) —
21
+ * see `wmAppend`'s doc comment for why a sidecar counter, not a directory
22
+ * scan or a full-file read, is the right tool here. Per-sid files are a
23
+ * DELIBERATE choice (design doc, non-negotiable): a shared cross-session
24
+ * ledger would need a write-lock on every single prompt across every open
25
+ * window, turning a per-prompt hot path into a cross-process contention
26
+ * point. Per-sid files make that race structurally impossible — two windows
27
+ * literally never touch the same file.
28
+ */
29
+ import * as fs from "node:fs";
30
+ import * as path from "node:path";
31
+ import { getRoot } from "../types.js";
32
+ import { ensureDir, truncateUtf8Bytes } from "./fs-utils.js";
33
+ import { isSystemText, parseJsonlLenient } from "./extraction.js";
34
+ import { recordHookFailure } from "./hook-health.js";
35
+ import { sanitizeSlug, projectsRootDir } from "./paths.js";
36
+ import { isValidProjectSlug, listAllProjects } from "./project.js";
37
+ import { scrubForCloud } from "./content-guard.js";
38
+ import { generateFrontmatter } from "../palace/obsidian.js";
39
+ import { writeSessionCard } from "./session-card.js";
40
+ import { appendRecentSession, readRecentSessions } from "./recency-index.js";
41
+ const WM_DIRNAME = "working-memory";
42
+ const JSONL_EXT = ".jsonl";
43
+ const COUNT_EXT = ".count";
44
+ /** Per-sid line cap (design doc §Mechanism) — bounds disk, not memory. */
45
+ export const WM_LINE_CAP = 2000;
46
+ /** Prompt field byte cap (UTF-8-safe) applied at append time. */
47
+ export const WM_PROMPT_BYTE_CAP = 300;
48
+ /**
49
+ * Cross-window "live" line window (session-start.ts's continuity assembly):
50
+ * a WM file with mtime younger than this is treated as "another session is
51
+ * (or very recently was) active elsewhere". Exported so session-start.ts and
52
+ * this module share ONE threshold instead of two independently-tuned magic
53
+ * numbers.
54
+ */
55
+ export const WM_LIVE_WINDOW_MS = 6 * 60 * 60 * 1000; // 6h
56
+ /**
57
+ * Orphan-rescue window (CLI hook-start): a WM file OLDER than this with no
58
+ * session card and no recency-index entry yet is presumed to belong to a
59
+ * session that crashed/was killed without ever reaching hook-end. Exported
60
+ * for the same single-source-of-truth reason as `WM_LIVE_WINDOW_MS`.
61
+ */
62
+ export const WM_ORPHAN_WINDOW_MS = 60 * 60 * 1000; // 1h
63
+ function wmDir() {
64
+ return path.join(getRoot(), WM_DIRNAME);
65
+ }
66
+ function wmFilePath(sid) {
67
+ return path.join(wmDir(), `${sanitizeSlug(sid)}${JSONL_EXT}`);
68
+ }
69
+ function wmCountPath(sid) {
70
+ return wmFilePath(sid) + COUNT_EXT;
71
+ }
72
+ /** Best-effort read of a tiny decimal-integer counter file. 0 on any failure. */
73
+ function readCounter(countPath) {
74
+ try {
75
+ const raw = fs.readFileSync(countPath, "utf-8").trim();
76
+ const n = parseInt(raw, 10);
77
+ return Number.isFinite(n) && n >= 0 ? n : 0;
78
+ }
79
+ catch {
80
+ return 0; // no counter yet (first append) or unreadable — treat as empty
81
+ }
82
+ }
83
+ /**
84
+ * Append one prompt to a session's working-memory file. Never throws — this
85
+ * runs on the hook-ambient hot path (every UserPromptSubmit) and a failure
86
+ * here must never delay or deny the ambient injection output that follows
87
+ * it in the caller. Any failure is reported via `recordHookFailure` instead.
88
+ *
89
+ * Boilerplate exclusion: a prompt that IS boilerplate (matches
90
+ * `isSystemText` — harness scaffolding, `<system-reminder>` blocks, etc.)
91
+ * appends NOTHING, not even an empty line, and does not consume any of the
92
+ * per-file line-cap budget.
93
+ *
94
+ * Line-cap strategy (documented per design doc constraint — "cheap stat
95
+ * size heuristic or first-write counter file is acceptable"): a byte-size
96
+ * heuristic on the growing .jsonl file was rejected because prompt length
97
+ * and cwd length both vary per line, making "file size / N" an unreliable
98
+ * proxy for "N lines" — it would let a run of short prompts blow well past
99
+ * the intended 2000-line cap while a run of near-cap-length prompts hits it
100
+ * early. Reading the .jsonl file itself to count lines was rejected because
101
+ * that makes wmAppend's cost scale with SESSION LENGTH (O(n) per prompt over
102
+ * an n-line file), violating the O(1)-hot-path constraint outright. The
103
+ * chosen alternative is a tiny sidecar counter file (a few bytes, a bare
104
+ * decimal integer) that is read once (cheap: a handful of bytes, not the
105
+ * growing transcript) and rewritten once per append — genuinely O(1) with
106
+ * respect to the session's own size.
107
+ *
108
+ * C1 fix (review, post-build): the raw prompt text used to reach disk with
109
+ * only the boilerplate check above — no injection/secret scrub — even though
110
+ * every OTHER persist path in this codebase (journal-write.ts, palace-write.ts,
111
+ * see storage/content-guard.ts) scrubs before writing. WM is a lower tier
112
+ * (minutes-level cache, not a permanent record) but it is NOT lower-exposure:
113
+ * its content is read back verbatim into (a) session-start.ts's cross-SESSION
114
+ * "live" line (surfaced to a DIFFERENT window/agent), (b) rescued session-card
115
+ * bodies (cli/index.ts orphan rescue — a permanent journal artifact once
116
+ * rescued), and (c) resurrect.ts's WM source. A secret or an injected
117
+ * "<system-reminder>ignore previous instructions</system-reminder>" block
118
+ * pasted into one prompt would otherwise flow verbatim into all three. This
119
+ * is the SINGLE choke point for the whole tier — every WM line is built here.
120
+ *
121
+ * Ordering (truncate → scrub → truncate again), deliberately NOT
122
+ * scrub-then-truncate, to preserve the O(1)-hot-path guarantee this module's
123
+ * own header documents: `scrubForCloud` is a ~15-regex pass whose cost scales
124
+ * with input length (measured: ~0.28ms on a 100KB string — see the fix
125
+ * report's benchmark). Truncating to WM_PROMPT_BYTE_CAP FIRST bounds the
126
+ * scrub's input to a small constant (≤300 bytes) regardless of how long the
127
+ * raw prompt was, so the added cost is ~1-2 microseconds per call — the scrub
128
+ * never sees the full pasted-file-sized prompt a user might submit. Content
129
+ * beyond the byte cap is truncated away before it is ever persisted, so it
130
+ * needs no scrubbing; content a secret/tag straddling the truncation boundary
131
+ * can still be caught if enough of it survives inside the retained window.
132
+ * The second truncateUtf8Bytes call is a cheap defensive no-op today (every
133
+ * SECRET_CONTENT_PATTERNS replacement is shorter than what it matches, so
134
+ * scrub never grows the string) — kept so the ≤WM_PROMPT_BYTE_CAP invariant
135
+ * holds even if that redaction-placeholder assumption ever changes.
136
+ */
137
+ export function wmAppend(sid, entry) {
138
+ try {
139
+ const prompt = (entry.prompt ?? "").trim();
140
+ if (!prompt || isSystemText(prompt))
141
+ return; // boilerplate-only — no line appended, no budget spent
142
+ const countPath = wmCountPath(sid);
143
+ const count = readCounter(countPath);
144
+ if (count >= WM_LINE_CAP)
145
+ return; // bounded — never grows past the cap
146
+ ensureDir(wmDir());
147
+ const truncated = truncateUtf8Bytes(prompt, WM_PROMPT_BYTE_CAP);
148
+ const scrubbed = truncateUtf8Bytes(scrubForCloud(truncated), WM_PROMPT_BYTE_CAP);
149
+ const line = {
150
+ ts: entry.ts,
151
+ prompt: scrubbed,
152
+ };
153
+ if (entry.cwd)
154
+ line.cwd = entry.cwd;
155
+ fs.appendFileSync(wmFilePath(sid), JSON.stringify(line) + "\n", "utf-8");
156
+ fs.writeFileSync(countPath, String(count + 1), "utf-8");
157
+ }
158
+ catch (err) {
159
+ // Never throw into the hook-ambient hot path — report and move on.
160
+ recordHookFailure("working-memory", err);
161
+ }
162
+ }
163
+ /**
164
+ * List every working-memory file currently on disk. Never throws — returns
165
+ * `[]` on any read error (missing directory, permissions, etc.). Used by
166
+ * BOTH the cross-window "live" line (session-start.ts, filters mtime <
167
+ * `WM_LIVE_WINDOW_MS`) and orphan rescue (CLI hook-start, filters mtime >
168
+ * `WM_ORPHAN_WINDOW_MS`) — not on any per-prompt hot path, so a full
169
+ * directory read here is acceptable (unlike `wmAppend`).
170
+ */
171
+ export function wmList() {
172
+ try {
173
+ const dir = wmDir();
174
+ if (!fs.existsSync(dir))
175
+ return [];
176
+ const files = fs.readdirSync(dir).filter((f) => f.endsWith(JSONL_EXT));
177
+ const out = [];
178
+ for (const f of files) {
179
+ const filePath = path.join(dir, f);
180
+ let mtimeMs;
181
+ try {
182
+ mtimeMs = fs.statSync(filePath).mtimeMs;
183
+ }
184
+ catch {
185
+ continue; // vanished between readdir and stat (concurrent wmDelete) — skip
186
+ }
187
+ const sid = f.slice(0, -JSONL_EXT.length);
188
+ let lines = readCounter(filePath + COUNT_EXT);
189
+ if (lines === 0) {
190
+ // No counter (pre-counter-file data, or a corrupt/missing sidecar) —
191
+ // self-heal by counting the actual file. Not on the hot path.
192
+ try {
193
+ lines = fs.readFileSync(filePath, "utf-8").split("\n").filter(Boolean).length;
194
+ }
195
+ catch {
196
+ lines = 0;
197
+ }
198
+ }
199
+ out.push({ sid, mtimeMs, lines });
200
+ }
201
+ return out;
202
+ }
203
+ catch {
204
+ return [];
205
+ }
206
+ }
207
+ /**
208
+ * Read every parsed line of a session's working-memory file, oldest-first.
209
+ * Never throws — returns `[]` when the file is missing, empty, or every line
210
+ * fails to parse/validate.
211
+ */
212
+ export function wmRead(sid) {
213
+ try {
214
+ const content = fs.readFileSync(wmFilePath(sid), "utf-8");
215
+ const records = parseJsonlLenient(content);
216
+ const out = [];
217
+ for (const rec of records) {
218
+ if (typeof rec.ts === "string" && typeof rec.prompt === "string") {
219
+ const line = { ts: rec.ts, prompt: rec.prompt };
220
+ if (typeof rec.cwd === "string")
221
+ line.cwd = rec.cwd;
222
+ out.push(line);
223
+ }
224
+ }
225
+ return out;
226
+ }
227
+ catch {
228
+ return [];
229
+ }
230
+ }
231
+ /**
232
+ * Delete a session's working-memory file and its counter sidecar. Idempotent
233
+ * (calling twice, or on a sid with no file, is a silent no-op) and never
234
+ * throws — this runs on the hook-end "sleep consolidation" path (after a
235
+ * successful session-card write) and on the orphan-rescue path, neither of
236
+ * which may fail the hook over a best-effort cleanup step.
237
+ */
238
+ export function wmDelete(sid) {
239
+ for (const p of [wmFilePath(sid), wmCountPath(sid)]) {
240
+ try {
241
+ if (fs.existsSync(p))
242
+ fs.unlinkSync(p);
243
+ }
244
+ catch {
245
+ // best-effort — a failed cleanup must never throw into the hook
246
+ }
247
+ }
248
+ }
249
+ /**
250
+ * Cheap, LOCAL cwd-majority slug guess for the two working-memory consumers
251
+ * that live in the CORE package (session-start.ts's live line, resurrect.ts's
252
+ * WM source) and therefore cannot import the CLI package's
253
+ * `resolveSessionProject` (packages/cli/src/utils/transcript-reader.ts) — the
254
+ * core package is a DEPENDENCY of the cli package, never the reverse, so a
255
+ * core module importing cli code would be a layering violation. Uses the
256
+ * SAME regex family as that function's Signal 1 (cwd frequency restricted to
257
+ * paths under `~/Projects/<name>`), deliberately WITHOUT its full three-signal
258
+ * claim-not-generate policy (no existing-slug preference, no content signal —
259
+ * working-memory lines carry only prompts + cwd, not the transcript's
260
+ * user/assistant message records that signal 2 scans).
261
+ *
262
+ * DELIBERATE choice, used by ALL THREE working-memory consumers (this core
263
+ * module's two call sites AND the CLI's orphan rescue, even though the
264
+ * latter COULD reach the real `resolveSessionProject`): F1's own
265
+ * claim-not-generate gate can only mint a BRAND-NEW slug when its content
266
+ * signal (from user/assistant transcript records) sees the name mentioned
267
+ * >=3 times — a signal that structurally never fires from cwd-only
268
+ * working-memory data. Routing orphan rescue through the real F1 function
269
+ * would therefore make it unable to attribute a crashed session's FIRST-EVER
270
+ * interaction with AR to its real project (exactly the case a crash-rescue
271
+ * mechanism most needs to handle) unless that project already has an
272
+ * AR_ROOT/projects/<slug> directory — so all three consumers share this
273
+ * lighter, uniform heuristic instead. Every candidate is still checked
274
+ * against `isValidProjectSlug` (the SAME gate F1 itself applies) so a
275
+ * deny-listed/UUID-shaped/otherwise-invalid cwd segment is never selected.
276
+ * Returns `null` when no line's `cwd` matches the pattern, or when every
277
+ * match was invalid (caller falls back to a literal `"auto"`, the existing
278
+ * convention for an unresolved slug elsewhere in this codebase).
279
+ *
280
+ * H1 fix (review, post-build): F1 (`resolveSessionProject`, transcript-reader.ts)
281
+ * scans its FULL ranked candidate list and lets the first one that already
282
+ * has an on-disk project home win outright ("prefer an existing slug" —
283
+ * Signal 3), even over a noisier top-ranked candidate. The original version
284
+ * of this function had no such tie-break — pure cwd-count majority — so a WM
285
+ * session that happened to visit an unrelated-but-more-frequent cwd (e.g. a
286
+ * quick `cd` into a sibling checkout mid-session) could out-vote the project
287
+ * the session actually belongs to, where F1 itself would have picked the
288
+ * established one. Mirrors F1's tie-break using core's OWN project listing
289
+ * (`listAllProjects`, this same module — no cli import, preserving the
290
+ * core→cli layering direction documented above) instead of duplicating a raw
291
+ * `fs.readdirSync` scan. Wrapped in its own try/catch: this function must
292
+ * never throw (same contract as every other WM helper), and `listAllProjects`
293
+ * is a filesystem read this module does not otherwise need to guard.
294
+ */
295
+ export function guessSlugFromWmLines(lines) {
296
+ const CWD_SLUG_RE = /^\/Users\/[^/]+\/(?:[Pp]rojects?)\/([^/]+)/;
297
+ const counts = new Map();
298
+ for (const l of lines) {
299
+ if (!l.cwd)
300
+ continue;
301
+ const m = CWD_SLUG_RE.exec(l.cwd);
302
+ if (!m)
303
+ continue;
304
+ const slug = m[1].replace(/[`'".,;)>]+$/, "");
305
+ if (!isValidProjectSlug(slug))
306
+ continue; // same safety gate F1 itself applies
307
+ counts.set(slug, (counts.get(slug) ?? 0) + 1);
308
+ }
309
+ if (counts.size === 0)
310
+ return null;
311
+ const ranked = [...counts.entries()]
312
+ .map(([slug, count]) => ({ slug, count }))
313
+ .sort((a, b) => b.count - a.count);
314
+ // Existing-slug tie-break (H1) — mirrors F1's Signal 3. Scan the full
315
+ // ranked list, not just the top candidate: an established project should
316
+ // win even when a noisier candidate happens to have a higher raw count in
317
+ // this particular WM slice.
318
+ try {
319
+ const existingSlugs = new Set(listAllProjects().map((p) => p.slug));
320
+ for (const cand of ranked) {
321
+ if (existingSlugs.has(cand.slug))
322
+ return cand.slug;
323
+ }
324
+ }
325
+ catch {
326
+ // listAllProjects is a best-effort preference signal, not a requirement —
327
+ // fall through to the plain majority below on any read failure.
328
+ }
329
+ return ranked[0]?.slug ?? null;
330
+ }
331
+ /**
332
+ * v3.4.42 working-memory wave — orphan-rescue idempotency guard 1/2: does ANY
333
+ * project already have a session card for this sid? Scans every project's
334
+ * journal/ directory for a `*--card--<sid>.md` file (the exact naming
335
+ * convention `writeSessionCard` uses). Never throws — a missing/unreadable
336
+ * projects dir simply means "no card found".
337
+ *
338
+ * Moved here verbatim from packages/cli/src/index.ts (Train C, C-2, 2026-08-12
339
+ * wave) as part of single-sourcing the orphan-rescue sweep — see
340
+ * `rescueOrphanedWorkingMemory`'s doc comment below for why. NOT quite
341
+ * verbatim, though: the original CLI version built the enumeration root via
342
+ * a raw `path.join(root, "projects")`. This package's own F2 architectural
343
+ * guard (test/projects-literal-bypass-guard.test.mjs) forbids any
344
+ * `packages/core/src/**` file other than storage/paths.ts from inlining the
345
+ * `"projects"` literal — moving this function into core surfaced that guard
346
+ * for the first time. Fixed to use `projectsRootDir()`, the sanctioned
347
+ * enumeration-only helper paths.ts itself documents for exactly this case
348
+ * (joining directly against a slug that came FROM a readdir, not a
349
+ * caller-supplied name that needs the case-fold reuse rule).
350
+ *
351
+ * Rescue-slug-parity fix (Train C, 2026-08-13): returns the FOUND slug (the
352
+ * on-disk directory name the readdir actually matched under) instead of a
353
+ * bare boolean. `distillOneSession` below needs this because, when a card
354
+ * for this sid already exists, THIS slug (not a fresh `guessSlugFromWmLines`
355
+ * re-guess, which could itself have drifted since the card was written) is
356
+ * the only correct value for a not-yet-existing recency-ledger entry — see
357
+ * that function's own comment for the full ledger-vs-disk mismatch this
358
+ * closes. `null` means "no card found for this sid in any project."
359
+ */
360
+ function findCardSlugForSid(sid) {
361
+ try {
362
+ const projectsDir = projectsRootDir();
363
+ if (!fs.existsSync(projectsDir))
364
+ return null;
365
+ for (const slug of fs.readdirSync(projectsDir)) {
366
+ const journalPath = path.join(projectsDir, slug, "journal");
367
+ if (!fs.existsSync(journalPath))
368
+ continue;
369
+ const hit = fs.readdirSync(journalPath).some((f) => f.endsWith(`--card--${sid}.md`));
370
+ if (hit)
371
+ return slug;
372
+ }
373
+ return null;
374
+ }
375
+ catch {
376
+ return null;
377
+ }
378
+ }
379
+ /**
380
+ * C-2 (Train C, 2026-08-12 wave, design doc reports/2026-08-12-trainc-design.md)
381
+ * — the working-memory orphan-rescue sweep, single-sourced.
382
+ *
383
+ * WHY: through the v3.4.42 working-memory wave this sweep lived ONLY inside
384
+ * the CLI's `hook-start` case (packages/cli/src/index.ts) — a session that
385
+ * crashed on a host with no Claude Code hooks (Codex/Cursor/raw MCP) had no
386
+ * path back to a card at all, because nothing but that one CLI command ever
387
+ * ran the sweep. Doctrine (owner, 2026-07-26): the customer's only action is
388
+ * describing intent — the MCP server process itself must carry the memory
389
+ * lifecycle on hook-less hosts. Moved here, byte-for-byte behavior preserved,
390
+ * so BOTH callers — the CLI's `hook-start` case AND core's own `sessionStart()`
391
+ * (tools-logic/session-start.ts, called by the MCP `session_start` tool on
392
+ * every host) — invoke this ONE function. Neither re-implements any part of
393
+ * the sweep; there is exactly one place this logic can drift.
394
+ *
395
+ * Mechanism (unchanged from the original CLI-only version): a working-memory
396
+ * file older than `WM_ORPHAN_WINDOW_MS` with no session card and no
397
+ * recency-index entry yet is presumed to belong to a session that crashed or
398
+ * was `kill -9`'d without ever reaching hook-end (or, on a non-hook host,
399
+ * without the agent ever calling `session_end`). Rescues it into a
400
+ * searchable session card + recency entry, then deletes the WM file.
401
+ * Idempotent (card-exists / recency-exists guards — safe to call on every
402
+ * hook-start AND every session_start, from every open window/process),
403
+ * per-file fault-isolated (one bad orphan can never abort the sweep for its
404
+ * siblings — M1 fix, see the recency-append verification below), and NEVER
405
+ * throws: every failure is reported via `recordHookFailure` instead of
406
+ * propagating, matching every other WM helper's contract in this module.
407
+ *
408
+ * Renamed failure-record hook keys from the CLI original ("hook-start-wm-rescue"
409
+ * -> "wm-orphan-rescue", "hook-start-wm-rescue-recency" -> "wm-orphan-rescue-
410
+ * recency") — cosmetic only, no test or renderer asserts the literal string —
411
+ * because the sweep is no longer CLI-hook-specific; the old names would be
412
+ * actively misleading once an MCP `session_start` call is what triggered a
413
+ * given failure row.
414
+ *
415
+ * The per-file WM→card mechanism itself lives in `distillOneSession` below —
416
+ * factored out so C-3's graceful-exit handler (mcp-server/src/lib/
417
+ * lifecycle-exit.ts, via `distillSessionToCard`) can distill its OWN,
418
+ * still-fresh session immediately (no age gate) through the exact same
419
+ * mechanism this sweep uses for aged orphans, instead of a third
420
+ * reimplementation of "WM lines -> card + recency entry -> delete WM".
421
+ */
422
+ export function rescueOrphanedWorkingMemory() {
423
+ try {
424
+ const now = Date.now();
425
+ const wmFiles = wmList();
426
+ // L1 fix (review, post-build, preserved from the CLI original): hoist the
427
+ // recency-index read OUT of the per-orphan loop. `readRecentSessions(1000)`
428
+ // reads and JSON-parses up to 1000 ledger lines from disk; calling it once
429
+ // PER orphan file made the sweep's total cost scale with orphans ×
430
+ // ledger-size instead of once + an O(1) Set lookup per orphan.
431
+ const recentSids = new Set(readRecentSessions(1000).map((e) => e.sid));
432
+ for (const wmFile of wmFiles) {
433
+ // M1 fix (review, post-build, preserved from the CLI original): per-file
434
+ // try/catch — a thrown error while rescuing ONE orphan must never abort
435
+ // the whole sweep, silently skipping every OTHER orphan file that
436
+ // hadn't been reached yet.
437
+ try {
438
+ if (now - wmFile.mtimeMs <= WM_ORPHAN_WINDOW_MS)
439
+ continue; // still fresh — not orphaned yet
440
+ distillOneSession(wmFile, recentSids);
441
+ }
442
+ catch (e) {
443
+ recordHookFailure("wm-orphan-rescue", e);
444
+ // per-file catch — fall through to the next orphan, sweep continues
445
+ }
446
+ }
447
+ }
448
+ catch (e) {
449
+ recordHookFailure("wm-orphan-rescue", e);
450
+ }
451
+ }
452
+ /**
453
+ * Distill ONE session's working-memory lines into a session card + recency
454
+ * entry, then delete the WM file. No age check here BY DESIGN — that policy
455
+ * decision belongs entirely to the caller: `rescueOrphanedWorkingMemory`
456
+ * only reaches this for files already confirmed older than
457
+ * `WM_ORPHAN_WINDOW_MS`, while `distillSessionToCard` (below, C-3's
458
+ * graceful-exit entry point) calls it immediately for a still-live session.
459
+ * Lets exceptions propagate — both current callers wrap their own call in a
460
+ * try/catch (matching the original inline code's per-item fault isolation),
461
+ * so this extraction changes no failure-handling behavior.
462
+ *
463
+ * Rescue-slug-parity fix (Train C, 2026-08-13): `guessSlugFromWmLines`
464
+ * returns a RAW cwd-captured candidate (e.g. "AgentRecall") that is never
465
+ * itself lowercased/case-folded. `writeSessionCard` → `journalDir` →
466
+ * `resolveProjectDirName` DOES normalize it (lowercases via `sanitizeName`,
467
+ * or reuses whatever casing an existing project dir already has) before the
468
+ * card ever touches disk — so the card can land under `projects/agentrecall/`
469
+ * while the raw guessed value stays "AgentRecall". The recency ledger used
470
+ * to be appended with that same raw, never-normalized value, so a lookup
471
+ * keyed on the ledger's slug (e.g. this file's own
472
+ * `packages/mcp-server/test/kill9-orphan-rescue.test.mjs`, which asserts
473
+ * `recencyLines.some((e) => e.slug === rescuedCard.slug)` against the ACTUAL
474
+ * on-disk directory name) could never find the card it was supposedly
475
+ * pointing at. Fixed by tracking a SEPARATE `ledgerSlug` that is always
476
+ * populated from where the card ACTUALLY is — `writeSessionCard`'s own
477
+ * returned `slug` when this call just wrote it, or `findCardSlugForSid`'s
478
+ * already-resolved slug when the card already existed — never from the raw
479
+ * `guessSlugFromWmLines` guess directly.
480
+ */
481
+ function distillOneSession(wmFile, recentSids) {
482
+ // Idempotency guard: a card and/or recency entry already recorded for this
483
+ // sid means some or all of the rescue already happened (or the session
484
+ // ended normally via hook-end/session_end without WM having been cleaned
485
+ // up yet by some other race). Tracked as two SEPARATE signals (not one
486
+ // OR'd flag) — a card that exists with no matching recency entry must NOT
487
+ // be treated as fully rescued. `existingCardSlug` (not just a boolean) is
488
+ // the ACTUAL on-disk slug of that pre-existing card, needed below.
489
+ const existingCardSlug = findCardSlugForSid(wmFile.sid);
490
+ const hasCard = existingCardSlug !== null;
491
+ const hasRecency = recentSids.has(wmFile.sid);
492
+ if (hasCard && hasRecency) {
493
+ // Both tiers confirmed — nothing left to do but sweep the leftover WM file.
494
+ wmDelete(wmFile.sid);
495
+ return;
496
+ }
497
+ const wmLines = wmRead(wmFile.sid);
498
+ if (wmLines.length === 0) {
499
+ wmDelete(wmFile.sid); // empty/corrupt — nothing to rescue, stop retrying
500
+ return;
501
+ }
502
+ const first = wmLines[0];
503
+ const last = wmLines[wmLines.length - 1];
504
+ const guessedSlug = guessSlugFromWmLines(wmLines) ?? "auto";
505
+ const title = truncateUtf8Bytes(first.prompt, 120);
506
+ const date = new Date(wmFile.mtimeMs).toISOString().slice(0, 10);
507
+ // The slug the RECENCY LEDGER must record — always the card's real on-disk
508
+ // slug, never the raw guess. Defaults to the already-resolved
509
+ // `existingCardSlug` (the hasCard branch below never overwrites it); the
510
+ // !hasCard branch overwrites it with `written.slug` once the card write
511
+ // confirms where it actually landed.
512
+ let ledgerSlug = existingCardSlug ?? guessedSlug;
513
+ // Card-write is attempted ONLY when a card doesn't already exist (hasCard
514
+ // tracks that precisely). When hasCard is already true, the ONLY
515
+ // remaining gap this sweep needs to close is the recency entry.
516
+ let cardOk = hasCard;
517
+ if (!hasCard) {
518
+ const frontmatter = generateFrontmatter({
519
+ sid: wmFile.sid,
520
+ date,
521
+ slug: guessedSlug,
522
+ slug_confidence: 0,
523
+ slug_candidates: [],
524
+ source: "working-memory-rescue",
525
+ });
526
+ const body = [
527
+ `# ${title}`,
528
+ "",
529
+ `- rescued from working memory after ${wmLines.length} recorded prompt${wmLines.length === 1 ? "" : "s"} (no hook-end ever fired for this session)`,
530
+ `- ts range: ${first.ts} → ${last.ts}`,
531
+ "",
532
+ "## First prompt",
533
+ first.prompt,
534
+ "",
535
+ "## Last prompt",
536
+ last.prompt,
537
+ "",
538
+ ].join("\n");
539
+ const written = writeSessionCard({
540
+ markdown: frontmatter + body,
541
+ title,
542
+ artifacts: [],
543
+ linearRefs: [],
544
+ decisions: [],
545
+ nextStep: [],
546
+ sid: wmFile.sid,
547
+ slug: guessedSlug,
548
+ date,
549
+ });
550
+ cardOk = !!written.path;
551
+ if (cardOk)
552
+ ledgerSlug = written.slug || guessedSlug; // the ACTUAL on-disk slug, per WriteSessionCardResult.slug's contract
553
+ }
554
+ if (!cardOk) {
555
+ // The card write itself failed — leave the WM file in place so a future
556
+ // sweep (or the next graceful exit) can retry instead of losing the only
557
+ // remaining record of this session.
558
+ return;
559
+ }
560
+ // M1 fix (preserved from the CLI original): verify the recency append
561
+ // actually landed instead of trusting that it didn't throw.
562
+ // `appendRecentSession` is a DELIBERATELY best-effort, never-throws
563
+ // telemetry ledger — an unwritable root, a full disk, or a permissions
564
+ // error fails SILENTLY inside it. Re-read the ledger after the append and
565
+ // only delete WM once BOTH tiers are confirmed present, so a
566
+ // card-written-but-recency-failed session never becomes permanently
567
+ // invisible to continuity.
568
+ if (!hasRecency) {
569
+ appendRecentSession({
570
+ ts: new Date(wmFile.mtimeMs).toISOString(),
571
+ sid: wmFile.sid,
572
+ slug: ledgerSlug,
573
+ title,
574
+ artifact_count: 0,
575
+ });
576
+ const confirmedRecency = readRecentSessions(1000).some((e) => e.sid === wmFile.sid);
577
+ if (!confirmedRecency) {
578
+ recordHookFailure("wm-orphan-rescue-recency", new Error(`appendRecentSession did not persist for sid=${wmFile.sid}`));
579
+ return; // do NOT delete WM — retry the recency append on the next sweep/exit
580
+ }
581
+ }
582
+ wmDelete(wmFile.sid);
583
+ }
584
+ /**
585
+ * C-3 (Train C, 2026-08-12 wave) — best-effort freshness for a graceful
586
+ * client close. `mcp-server/src/lib/lifecycle-exit.ts` calls this for the
587
+ * CURRENT process's own `sid` (core's `getSessionId()`) on `stdin` "end"/
588
+ * "close" and on SIGTERM/SIGINT, so a graceful disconnect gets a card
589
+ * immediately instead of waiting up to `WM_ORPHAN_WINDOW_MS` for the NEXT
590
+ * session's orphan sweep to find it. Reuses `distillOneSession` — the SAME
591
+ * WM→card mechanism `rescueOrphanedWorkingMemory` uses for aged orphans —
592
+ * with no age gate, since this is called precisely because the session is
593
+ * ending RIGHT NOW, not because it went stale. A `kill -9` bypasses this
594
+ * entirely by construction (no signal, no stdin event ever fires) and falls
595
+ * through to `rescueOrphanedWorkingMemory` on a LATER session_start/hook-start,
596
+ * exactly as the design doc specifies.
597
+ *
598
+ * No-op (silent) when this session has no working-memory file at all — a
599
+ * session that never had a tool call captured (or whose WM was already
600
+ * cleaned up by a normal `session_end`) has nothing to distill. Never
601
+ * throws: reported via `recordHookFailure` like every other WM helper.
602
+ */
603
+ export function distillSessionToCard(sid) {
604
+ try {
605
+ const wmFile = wmList().find((f) => f.sid === sid);
606
+ if (!wmFile)
607
+ return; // nothing captured for this session — silent no-op
608
+ const recentSids = new Set(readRecentSessions(1000).map((e) => e.sid));
609
+ distillOneSession(wmFile, recentSids);
610
+ }
611
+ catch (e) {
612
+ recordHookFailure("wm-session-distill", e);
613
+ }
614
+ }
615
+ //# sourceMappingURL=working-memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"working-memory.js","sourceRoot":"","sources":["../../src/storage/working-memory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,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G,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC;QACnD,IAAI,CAAC,MAAM;YAAE,OAAO,CAAC,mDAAmD;QACxE,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACvE,iBAAiB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACxC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,iBAAiB,CAAC,oBAAoB,EAAE,CAAC,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC"}
@@ -16,10 +16,17 @@
16
16
  * - <root>/recent-sessions.jsonl (F2, optional — may not exist yet)
17
17
  * - <root>/projects/<slug>/journal/archive/raw/*.md (lossless verbatim tier)
18
18
  * - <root>/projects/<slug>/journal/*--card--*.md (F3 mechanical session card)
19
- * All three are merged by (slug, sid) — the SAME session recorded via
19
+ * - <root>/working-memory/*.jsonl (v3.4.42 working-memory wave — LIVE,
20
+ * not-yet-ended sessions; the FRESHEST possible source, since a file
21
+ * here means the session is still running, or crashed with no hook-end
22
+ * at all yet, RIGHT NOW)
23
+ * All four are merged by (slug, sid) — the SAME session recorded via
20
24
  * multiple tiers becomes ONE ContinuityBrief with fields backfilled from
21
25
  * whichever source has them, cards preferred over raw for title/goal since
22
- * they are the higher-fidelity, already-distilled tier.
26
+ * they are the higher-fidelity, already-distilled tier. A live WM entry's
27
+ * `provenance` carries the literal marker `[working-memory · live]` instead
28
+ * of a file path, so a caller can tell at a glance that a brief is backed by
29
+ * an in-progress session rather than a completed one.
23
30
  *
24
31
  * Precision note (fixture report §2): naive path/Linear-ID regexes over raw
25
32
  * transcript text are exactly what misled the incident's own forensics —
@@ -1 +1 @@
1
- {"version":3,"file":"resurrect.d.ts","sourceRoot":"","sources":["../../src/tools-logic/resurrect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AAyBH,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,+EAA+E;IAC/E,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,qFAAqF;IACrF,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,cAAc;IAC7B,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8CAA8C;IAC9C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AA+QD;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,KAAK,GAAE,cAAmB,GAAG,eAAe,EAAE,CAwNvE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,CA0BzE"}
1
+ {"version":3,"file":"resurrect.d.ts","sourceRoot":"","sources":["../../src/tools-logic/resurrect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2EG;AA0BH,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;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