agent-recall-core 3.4.40 → 3.4.41

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 (68) hide show
  1. package/dist/helpers/auto-name.d.ts +2 -1
  2. package/dist/helpers/auto-name.d.ts.map +1 -1
  3. package/dist/helpers/auto-name.js +45 -6
  4. package/dist/helpers/auto-name.js.map +1 -1
  5. package/dist/helpers/journal-sig-theme.d.ts +18 -0
  6. package/dist/helpers/journal-sig-theme.d.ts.map +1 -1
  7. package/dist/helpers/journal-sig-theme.js +6 -1
  8. package/dist/helpers/journal-sig-theme.js.map +1 -1
  9. package/dist/index.d.ts +9 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +10 -0
  12. package/dist/index.js.map +1 -1
  13. package/dist/storage/extraction.d.ts +136 -0
  14. package/dist/storage/extraction.d.ts.map +1 -0
  15. package/dist/storage/extraction.js +368 -0
  16. package/dist/storage/extraction.js.map +1 -0
  17. package/dist/storage/fs-utils.d.ts +21 -0
  18. package/dist/storage/fs-utils.d.ts.map +1 -1
  19. package/dist/storage/fs-utils.js +86 -0
  20. package/dist/storage/fs-utils.js.map +1 -1
  21. package/dist/storage/hook-health.d.ts +50 -0
  22. package/dist/storage/hook-health.d.ts.map +1 -0
  23. package/dist/storage/hook-health.js +183 -0
  24. package/dist/storage/hook-health.js.map +1 -0
  25. package/dist/storage/paths.d.ts +23 -4
  26. package/dist/storage/paths.d.ts.map +1 -1
  27. package/dist/storage/paths.js +26 -9
  28. package/dist/storage/paths.js.map +1 -1
  29. package/dist/storage/recency-index.d.ts +79 -0
  30. package/dist/storage/recency-index.d.ts.map +1 -0
  31. package/dist/storage/recency-index.js +204 -0
  32. package/dist/storage/recency-index.js.map +1 -0
  33. package/dist/storage/session-card.d.ts +74 -0
  34. package/dist/storage/session-card.d.ts.map +1 -0
  35. package/dist/storage/session-card.js +219 -0
  36. package/dist/storage/session-card.js.map +1 -0
  37. package/dist/supabase/recall-backend.d.ts +1 -1
  38. package/dist/supabase/recall-backend.d.ts.map +1 -1
  39. package/dist/supabase/recall-backend.js.map +1 -1
  40. package/dist/supabase/sync.d.ts.map +1 -1
  41. package/dist/supabase/sync.js +13 -2
  42. package/dist/supabase/sync.js.map +1 -1
  43. package/dist/tools-logic/drill-down.d.ts +9 -2
  44. package/dist/tools-logic/drill-down.d.ts.map +1 -1
  45. package/dist/tools-logic/drill-down.js +32 -1
  46. package/dist/tools-logic/drill-down.js.map +1 -1
  47. package/dist/tools-logic/journal-search.d.ts.map +1 -1
  48. package/dist/tools-logic/journal-search.js +7 -1
  49. package/dist/tools-logic/journal-search.js.map +1 -1
  50. package/dist/tools-logic/resurrect.d.ts +106 -0
  51. package/dist/tools-logic/resurrect.d.ts.map +1 -0
  52. package/dist/tools-logic/resurrect.js +561 -0
  53. package/dist/tools-logic/resurrect.js.map +1 -0
  54. package/dist/tools-logic/session-start-lite.d.ts +6 -0
  55. package/dist/tools-logic/session-start-lite.d.ts.map +1 -1
  56. package/dist/tools-logic/session-start-lite.js +15 -0
  57. package/dist/tools-logic/session-start-lite.js.map +1 -1
  58. package/dist/tools-logic/session-start.d.ts +17 -0
  59. package/dist/tools-logic/session-start.d.ts.map +1 -1
  60. package/dist/tools-logic/session-start.js +52 -1
  61. package/dist/tools-logic/session-start.js.map +1 -1
  62. package/dist/tools-logic/smart-recall.d.ts +9 -4
  63. package/dist/tools-logic/smart-recall.d.ts.map +1 -1
  64. package/dist/tools-logic/smart-recall.js +170 -4
  65. package/dist/tools-logic/smart-recall.js.map +1 -1
  66. package/dist/types.d.ts +1 -1
  67. package/dist/types.js +1 -1
  68. package/package.json +1 -1
@@ -0,0 +1,106 @@
1
+ /**
2
+ * resurrect.ts — F6, read-only cross-slug dead-session finder (continuity
3
+ * wave, 2026-07-31).
4
+ *
5
+ * WHY: this encodes the incident-recovery forensics from
6
+ * reports/2026-07-31-continuity-fixture.md as a function. A session that hit
7
+ * F4's gap (no `ar capture` that day → only journal/archive/raw/ + a no-op
8
+ * consolidation job) is otherwise unrecoverable except by hand-grepping raw
9
+ * dumps and cross-checking the palace/insight graph, exactly as that fixture
10
+ * had to do. `resurrect()` scans every project's raw archive + session cards
11
+ * + the cross-project recency index and ranks candidates by recency and
12
+ * (when a query is given) keyword match, so a "how much can you recall on
13
+ * X?" moment can be answered mechanically instead of by manual forensics.
14
+ *
15
+ * Sources (read-only — this module never writes to the store):
16
+ * - <root>/recent-sessions.jsonl (F2, optional — may not exist yet)
17
+ * - <root>/projects/<slug>/journal/archive/raw/*.md (lossless verbatim tier)
18
+ * - <root>/projects/<slug>/journal/*--card--*.md (F3 mechanical session card)
19
+ * All three are merged by (slug, sid) — the SAME session recorded via
20
+ * multiple tiers becomes ONE ContinuityBrief with fields backfilled from
21
+ * whichever source has them, cards preferred over raw for title/goal since
22
+ * they are the higher-fidelity, already-distilled tier.
23
+ *
24
+ * Precision note (fixture report §2): naive path/Linear-ID regexes over raw
25
+ * transcript text are exactly what misled the incident's own forensics —
26
+ * hook-injected boilerplate (folder-lint warnings, orchestrator briefs) can
27
+ * contain plausible-looking file paths and ticket IDs unrelated to the
28
+ * session's real content.
29
+ *
30
+ * fix2 (2026-07-31 — root-cause consolidation): artifact/Linear-ref/
31
+ * next-step extraction used to be a SEPARATE, lower-rigor reimplementation
32
+ * of the logic already fixed (M9's tool_result exclusion) in
33
+ * storage/session-card.ts — so that fix, and a markdown-heading exclusion,
34
+ * never reached this module's copies (verifier-report V3 + "additional
35
+ * findings" #3/#5). Extraction now lives in ONE place,
36
+ * `../storage/extraction.js`, consumed by BOTH this module and
37
+ * session-card.ts:
38
+ * - Source 2 (raw archive bodies) embeds near-verbatim JSONL transcript
39
+ * lines after a frontmatter block — exactly session-card.ts's rawHead/
40
+ * rawTail shape — so it is parsed via `parseJsonlLenient` and scanned
41
+ * with the SAME record-based, M9-protected extractors session-card.ts
42
+ * uses (`extractArtifactPathsFromRecords` / `extractLinearRefsFromRecords`).
43
+ * A tool_result-embedded ref genuinely cannot leak here anymore.
44
+ * - Source 3 (session-card markdown bodies) has no record structure to
45
+ * recover — it is the ALREADY-RENDERED OUTPUT of session-card.ts's own
46
+ * M9-protected extractors, so a raw tool_result JSON blob never appears
47
+ * in it to begin with; the text-level `extractArtifactPathsFromText` /
48
+ * `extractLinearRefsFromText` helpers are the right (and only sensible)
49
+ * tool there. This module still does NOT import session-card.ts's
50
+ * renderer itself (`buildSessionCard`/`writeSessionCard`) — cards are
51
+ * parsed generically via the documented on-disk shape (frontmatter keys
52
+ * `sid`/`date`/`slug`/`slug_confidence`/`source` per design §F3) so this
53
+ * stays buildable independent of W1's parallel work; only the shared
54
+ * extraction PRIMITIVES are imported, not the card build/write path.
55
+ *
56
+ * fix3 (2026-07-31 — round 2 of the same root-cause consolidation): fix2
57
+ * covered artifacts/Linear-refs/next-step-line-cosmetics; a real-store
58
+ * read-only acceptance run then found title/goalExcerpt AND the actual
59
+ * next-step VALUES for Source 2 were still derived by flat TEXT-level
60
+ * scanning of the raw JSONL body (a global `"text":"..."` regex for the
61
+ * goal; a per-line `NEXT_STEP_LINE_RE` grep over the whole raw body for
62
+ * next-steps) — the exact same class of bug fix2 fixed for artifacts/refs,
63
+ * just not yet extended to these two fields. Both now go through the SAME
64
+ * shared, record-based reduction session-card.ts uses for its own title
65
+ * fallback and finalAssistantText: `extractFirstUserTextFromRecords` (goal)
66
+ * and `extractLinesMatching` over `extractFinalRecordText(..., "assistant")`
67
+ * (next-steps) — see the Source 2 loop below for the full rationale and the
68
+ * "empty beats garbage" fallback rule this closes.
69
+ */
70
+ export interface ContinuityBrief {
71
+ slug: string;
72
+ sid: string;
73
+ /** YYYY-MM-DD, best available across sources; "unknown" if none parsed. */
74
+ date: string;
75
+ title: string;
76
+ goalExcerpt: string;
77
+ artifacts: string[];
78
+ linearRefs: string[];
79
+ nextSteps: string[];
80
+ /** Absolute source file paths (or the recency-index path) that contributed. */
81
+ provenance: string[];
82
+ /** Ranking score — exposed for debuggability/testing, not part of the spec shape. */
83
+ score: number;
84
+ }
85
+ export interface ResurrectInput {
86
+ /** Free-text query (any language). Omit/empty for pure-recency ranking. */
87
+ query?: string;
88
+ /** How many days back to scan. Default 14. */
89
+ days?: number;
90
+ /** Max briefs returned, sorted by score descending. Default 20. */
91
+ limit?: number;
92
+ }
93
+ /**
94
+ * Read-only cross-slug dead-session finder. Never throws: any per-file or
95
+ * per-project read failure is skipped, and an empty/missing store simply
96
+ * yields an empty array (never a crash — Worker Done-Definition error path).
97
+ */
98
+ export declare function resurrect(input?: ResurrectInput): ContinuityBrief[];
99
+ /**
100
+ * Markdown renderer for a list of ContinuityBriefs (CLI command wiring for
101
+ * `ar resurrect` is Wave-2's job — this is just the render function it will
102
+ * call). Never returns an empty string: an empty result set still renders a
103
+ * one-line "nothing found" message so a caller always has something to print.
104
+ */
105
+ export declare function renderResurrectMarkdown(briefs: ContinuityBrief[]): string;
106
+ //# sourceMappingURL=resurrect.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,561 @@
1
+ /**
2
+ * resurrect.ts — F6, read-only cross-slug dead-session finder (continuity
3
+ * wave, 2026-07-31).
4
+ *
5
+ * WHY: this encodes the incident-recovery forensics from
6
+ * reports/2026-07-31-continuity-fixture.md as a function. A session that hit
7
+ * F4's gap (no `ar capture` that day → only journal/archive/raw/ + a no-op
8
+ * consolidation job) is otherwise unrecoverable except by hand-grepping raw
9
+ * dumps and cross-checking the palace/insight graph, exactly as that fixture
10
+ * had to do. `resurrect()` scans every project's raw archive + session cards
11
+ * + the cross-project recency index and ranks candidates by recency and
12
+ * (when a query is given) keyword match, so a "how much can you recall on
13
+ * X?" moment can be answered mechanically instead of by manual forensics.
14
+ *
15
+ * Sources (read-only — this module never writes to the store):
16
+ * - <root>/recent-sessions.jsonl (F2, optional — may not exist yet)
17
+ * - <root>/projects/<slug>/journal/archive/raw/*.md (lossless verbatim tier)
18
+ * - <root>/projects/<slug>/journal/*--card--*.md (F3 mechanical session card)
19
+ * All three are merged by (slug, sid) — the SAME session recorded via
20
+ * multiple tiers becomes ONE ContinuityBrief with fields backfilled from
21
+ * whichever source has them, cards preferred over raw for title/goal since
22
+ * they are the higher-fidelity, already-distilled tier.
23
+ *
24
+ * Precision note (fixture report §2): naive path/Linear-ID regexes over raw
25
+ * transcript text are exactly what misled the incident's own forensics —
26
+ * hook-injected boilerplate (folder-lint warnings, orchestrator briefs) can
27
+ * contain plausible-looking file paths and ticket IDs unrelated to the
28
+ * session's real content.
29
+ *
30
+ * fix2 (2026-07-31 — root-cause consolidation): artifact/Linear-ref/
31
+ * next-step extraction used to be a SEPARATE, lower-rigor reimplementation
32
+ * of the logic already fixed (M9's tool_result exclusion) in
33
+ * storage/session-card.ts — so that fix, and a markdown-heading exclusion,
34
+ * never reached this module's copies (verifier-report V3 + "additional
35
+ * findings" #3/#5). Extraction now lives in ONE place,
36
+ * `../storage/extraction.js`, consumed by BOTH this module and
37
+ * session-card.ts:
38
+ * - Source 2 (raw archive bodies) embeds near-verbatim JSONL transcript
39
+ * lines after a frontmatter block — exactly session-card.ts's rawHead/
40
+ * rawTail shape — so it is parsed via `parseJsonlLenient` and scanned
41
+ * with the SAME record-based, M9-protected extractors session-card.ts
42
+ * uses (`extractArtifactPathsFromRecords` / `extractLinearRefsFromRecords`).
43
+ * A tool_result-embedded ref genuinely cannot leak here anymore.
44
+ * - Source 3 (session-card markdown bodies) has no record structure to
45
+ * recover — it is the ALREADY-RENDERED OUTPUT of session-card.ts's own
46
+ * M9-protected extractors, so a raw tool_result JSON blob never appears
47
+ * in it to begin with; the text-level `extractArtifactPathsFromText` /
48
+ * `extractLinearRefsFromText` helpers are the right (and only sensible)
49
+ * tool there. This module still does NOT import session-card.ts's
50
+ * renderer itself (`buildSessionCard`/`writeSessionCard`) — cards are
51
+ * parsed generically via the documented on-disk shape (frontmatter keys
52
+ * `sid`/`date`/`slug`/`slug_confidence`/`source` per design §F3) so this
53
+ * stays buildable independent of W1's parallel work; only the shared
54
+ * extraction PRIMITIVES are imported, not the card build/write path.
55
+ *
56
+ * fix3 (2026-07-31 — round 2 of the same root-cause consolidation): fix2
57
+ * covered artifacts/Linear-refs/next-step-line-cosmetics; a real-store
58
+ * read-only acceptance run then found title/goalExcerpt AND the actual
59
+ * next-step VALUES for Source 2 were still derived by flat TEXT-level
60
+ * scanning of the raw JSONL body (a global `"text":"..."` regex for the
61
+ * goal; a per-line `NEXT_STEP_LINE_RE` grep over the whole raw body for
62
+ * next-steps) — the exact same class of bug fix2 fixed for artifacts/refs,
63
+ * just not yet extended to these two fields. Both now go through the SAME
64
+ * shared, record-based reduction session-card.ts uses for its own title
65
+ * fallback and finalAssistantText: `extractFirstUserTextFromRecords` (goal)
66
+ * and `extractLinesMatching` over `extractFinalRecordText(..., "assistant")`
67
+ * (next-steps) — see the Source 2 loop below for the full rationale and the
68
+ * "empty beats garbage" fallback rule this closes.
69
+ */
70
+ import * as fs from "node:fs";
71
+ import * as path from "node:path";
72
+ import { getRoot } from "../types.js";
73
+ import { archiveRawDir, journalDir, projectsRootDir } from "../storage/paths.js";
74
+ import { parseMemoryFile } from "../supabase/sync.js";
75
+ import { truncateUtf8Bytes } from "../storage/fs-utils.js";
76
+ import { NEXT_STEP_LINE_RE, parseJsonlLenient, extractArtifactPathsFromRecords, extractLinearRefsFromRecords, extractArtifactPathsFromText, extractLinearRefsFromText, extractLinesMatching, extractFirstUserTextFromRecords, extractFinalRecordText, unescapeJsonString, } from "../storage/extraction.js";
77
+ // ---------------------------------------------------------------------------
78
+ // Tuning constants
79
+ // ---------------------------------------------------------------------------
80
+ const DEFAULT_DAYS = 14;
81
+ const DEFAULT_LIMIT = 20;
82
+ const MAX_ARTIFACTS = 20;
83
+ const MAX_LINEAR_REFS = 20;
84
+ const MAX_NEXT_STEPS = 3;
85
+ const MIN_PROSE_LEN = 20; // shorter "text" blocks are almost never real content
86
+ const MAX_PROSE_LEN = 1500; // longer blocks are almost always a hook/system dump
87
+ const DAY_MS = 24 * 60 * 60 * 1000;
88
+ /**
89
+ * fix3 (2026-07-31): title/goal byte caps for Source 2's record-aware
90
+ * extraction (first real user-authored text) — UTF-8-safe via the shared
91
+ * `truncateUtf8Bytes` helper, never a raw `.slice()` on JS char count, which
92
+ * can split a surrogate pair. RAW_TITLE_BYTE_CAP matches
93
+ * `extractTitleAndGoal`'s pre-existing markdown-heading title cap (160) for
94
+ * continuity across sources.
95
+ */
96
+ const RAW_GOAL_BYTE_CAP = 200;
97
+ const RAW_TITLE_BYTE_CAP = 160;
98
+ const BOILERPLATE_MARKERS = [
99
+ "system-reminder",
100
+ "sessionstart:startup",
101
+ "folder-lint",
102
+ "hook success",
103
+ "memory-stale-check",
104
+ "plywood protocol",
105
+ ];
106
+ const HIGH_CONFIDENCE_KEYWORD_WEIGHT = 10;
107
+ const LOW_CONFIDENCE_KEYWORD_WEIGHT = 3;
108
+ function keyOf(slug, sid) {
109
+ return `${slug}::${sid}`;
110
+ }
111
+ function getOrCreate(map, slug, sid) {
112
+ const key = keyOf(slug, sid);
113
+ let entry = map.get(key);
114
+ if (!entry) {
115
+ entry = {
116
+ slug,
117
+ sid,
118
+ date: "",
119
+ ts: 0,
120
+ artifacts: new Set(),
121
+ linearRefs: new Set(),
122
+ nextSteps: [],
123
+ provenance: new Set(),
124
+ rawBodies: [],
125
+ };
126
+ map.set(key, entry);
127
+ }
128
+ return entry;
129
+ }
130
+ function dedupPush(arr, item, cap) {
131
+ const trimmed = item.trim();
132
+ if (!trimmed || arr.includes(trimmed) || arr.length >= cap)
133
+ return arr;
134
+ return [...arr, trimmed];
135
+ }
136
+ function dedupPushAll(arr, items, cap) {
137
+ let out = arr;
138
+ for (const item of items)
139
+ out = dedupPush(out, item, cap);
140
+ return out;
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // Filesystem enumeration
144
+ // ---------------------------------------------------------------------------
145
+ /** All project slugs on disk under <root>/projects/. Never throws — [] on any fs error. */
146
+ function enumerateProjectSlugs() {
147
+ try {
148
+ return fs
149
+ .readdirSync(projectsRootDir(), { withFileTypes: true })
150
+ .filter((e) => e.isDirectory())
151
+ .map((e) => e.name);
152
+ }
153
+ catch {
154
+ return [];
155
+ }
156
+ }
157
+ /**
158
+ * Read <root>/recent-sessions.jsonl (F2's format, per design §F2 — this
159
+ * module depends ONLY on the documented shape, not on W2's implementation).
160
+ * Optional: an absent file is simply zero entries, never an error.
161
+ */
162
+ function readRecentSessions() {
163
+ const p = path.join(getRoot(), "recent-sessions.jsonl");
164
+ let content;
165
+ try {
166
+ content = fs.readFileSync(p, "utf-8");
167
+ }
168
+ catch {
169
+ return [];
170
+ }
171
+ const out = [];
172
+ for (const line of content.split("\n")) {
173
+ const trimmed = line.trim();
174
+ if (!trimmed)
175
+ continue;
176
+ try {
177
+ const row = JSON.parse(trimmed);
178
+ if (row && typeof row.ts === "string" && typeof row.sid === "string" && typeof row.slug === "string") {
179
+ out.push({ ts: row.ts, sid: row.sid, slug: row.slug, title: row.title, next_step: row.next_step });
180
+ }
181
+ }
182
+ catch {
183
+ // skip malformed line
184
+ }
185
+ }
186
+ return out;
187
+ }
188
+ // ---------------------------------------------------------------------------
189
+ // Text extraction (shared by raw archive bodies and session-card bodies)
190
+ // ---------------------------------------------------------------------------
191
+ // unescapeJsonString is also used below, imported from ../storage/extraction.js
192
+ // (fix2, 2026-07-31) — single source, not a second local copy.
193
+ function looksLikeBoilerplate(text) {
194
+ if (text.length > MAX_PROSE_LEN)
195
+ return true;
196
+ const lower = text.toLowerCase();
197
+ return BOILERPLATE_MARKERS.some((marker) => lower.includes(marker));
198
+ }
199
+ /**
200
+ * Best-effort extraction of the first real prose "text" JSON field out of a
201
+ * raw (non-markdown) transcript body. Raw archive bodies are near-JSONL, not
202
+ * valid line-delimited JSON (fixture report §1) — this deliberately does NOT
203
+ * attempt a full JSON parse; it regex-scans for `"text":"..."` values, skips
204
+ * ones too short to be content or that match a known hook-boilerplate
205
+ * marker, and returns the first survivor. Returns null if nothing qualifies.
206
+ */
207
+ function extractFirstProseTextBlock(body) {
208
+ const re = /"text"\s*:\s*"((?:\\.|[^"\\])*)"/g;
209
+ let match;
210
+ while ((match = re.exec(body)) !== null) {
211
+ const text = unescapeJsonString(match[1]);
212
+ if (text.length < MIN_PROSE_LEN)
213
+ continue;
214
+ if (looksLikeBoilerplate(text))
215
+ continue;
216
+ return text;
217
+ }
218
+ return null;
219
+ }
220
+ /**
221
+ * Derive {title, goalExcerpt} from a body of text. Markdown bodies (session
222
+ * cards) have a leading heading — use it, plus the first paragraph after it
223
+ * as the goal excerpt. Non-markdown bodies (raw transcript dumps) fall back
224
+ * to the first qualifying prose "text" block; if even that fails, fall back
225
+ * to a trimmed slice of the body itself so a title is never empty.
226
+ */
227
+ function extractTitleAndGoal(body) {
228
+ const heading = body.match(/^#{1,3}\s+(.+)$/m);
229
+ if (heading && heading.index !== undefined) {
230
+ const title = heading[1].trim().slice(0, 160);
231
+ const afterHeading = body.slice(heading.index + heading[0].length);
232
+ const paragraph = afterHeading
233
+ .split(/\n\s*\n/)
234
+ .map((p) => p.trim())
235
+ .find((p) => p.length > 0);
236
+ const goalExcerpt = (paragraph ?? title).replace(/\s+/g, " ").slice(0, 240);
237
+ return { title, goalExcerpt };
238
+ }
239
+ const prose = extractFirstProseTextBlock(body);
240
+ if (prose) {
241
+ const clipped = prose.replace(/\s+/g, " ").trim();
242
+ return { title: clipped.slice(0, 160), goalExcerpt: clipped.slice(0, 240) };
243
+ }
244
+ const fallback = body.replace(/\s+/g, " ").trim().slice(0, 160);
245
+ return { title: fallback || "(untitled session)", goalExcerpt: fallback };
246
+ }
247
+ // Artifact-path / Linear-ref / next-step-line extraction (record-based for
248
+ // Source 2's embedded JSONL, text-based for Source 3's card markdown) now
249
+ // live in ../storage/extraction.ts — imported above. Single source shared
250
+ // with storage/session-card.ts (fix2, 2026-07-31); see the file header for
251
+ // which variant each source uses and why.
252
+ // ---------------------------------------------------------------------------
253
+ // Ranking
254
+ // ---------------------------------------------------------------------------
255
+ function queryTermsOf(query) {
256
+ const trimmed = (query ?? "").trim();
257
+ if (!trimmed)
258
+ return [];
259
+ return trimmed
260
+ .toLowerCase()
261
+ .split(/\s+/)
262
+ .filter((t) => t.length >= 2);
263
+ }
264
+ /**
265
+ * recency × keyword ranking. Pure recency when no query terms are given.
266
+ *
267
+ * Date logic vs TODAY (Worker Done-Definition #4): `ageDays` is clamped to
268
+ * >= 0 — a future-dated entry (clock skew, malformed fixture, hostile input)
269
+ * must not compute a NEGATIVE age, which would otherwise inflate
270
+ * recencyScore above 1 and let a bogus future timestamp silently out-rank
271
+ * every genuine "just happened" entry. Clamping treats it as "as fresh as
272
+ * right now" (score 1), never "the future" (score > 1).
273
+ */
274
+ function computeScore(entry, queryTerms, now, days) {
275
+ const rawAgeDays = (now - entry.ts) / 86_400_000; // negative when entry.ts is in the future
276
+ const isFuture = rawAgeDays < 0;
277
+ const ageDays = Math.max(0, rawAgeDays);
278
+ let recencyScore = Math.max(0, 1 - ageDays / Math.max(1, days));
279
+ // A future timestamp is clamped to the SAME age as "right now" above, which
280
+ // would otherwise let it TIE (or, by floating-point luck, nose ahead of) a
281
+ // genuinely-current entry scored a few milliseconds later than its own
282
+ // creation timestamp. Apply a small deliberate penalty so a clock-skew /
283
+ // malformed future entry always ranks strictly BELOW a real "now" entry,
284
+ // while still landing comfortably above any older genuine entry — this is
285
+ // the "consumer filters" half of Worker Done-Definition #4: a future date
286
+ // must never win the recency race, only ever be treated as suspect-fresh.
287
+ if (isFuture)
288
+ recencyScore *= 0.99;
289
+ if (queryTerms.length === 0)
290
+ return recencyScore;
291
+ const highText = [entry.title ?? "", entry.goalExcerpt ?? "", ...entry.linearRefs, ...entry.artifacts]
292
+ .join(" ")
293
+ .toLowerCase();
294
+ const lowText = entry.rawBodies.join(" ").toLowerCase();
295
+ let keywordScore = 0;
296
+ for (const term of queryTerms) {
297
+ if (highText.includes(term))
298
+ keywordScore += HIGH_CONFIDENCE_KEYWORD_WEIGHT;
299
+ else if (lowText.includes(term))
300
+ keywordScore += LOW_CONFIDENCE_KEYWORD_WEIGHT;
301
+ }
302
+ return keywordScore + recencyScore;
303
+ }
304
+ // ---------------------------------------------------------------------------
305
+ // Main entry point
306
+ // ---------------------------------------------------------------------------
307
+ /**
308
+ * Read-only cross-slug dead-session finder. Never throws: any per-file or
309
+ * per-project read failure is skipped, and an empty/missing store simply
310
+ * yields an empty array (never a crash — Worker Done-Definition error path).
311
+ */
312
+ export function resurrect(input = {}) {
313
+ const days = Number.isFinite(input.days) && input.days > 0 ? input.days : DEFAULT_DAYS;
314
+ const limit = Number.isFinite(input.limit) && input.limit > 0 ? input.limit : DEFAULT_LIMIT;
315
+ const queryTerms = queryTermsOf(input.query);
316
+ const now = Date.now();
317
+ const windowMs = days * 24 * 60 * 60 * 1000;
318
+ const cutoff = now - windowMs;
319
+ const merged = new Map();
320
+ // ---- Source 1: recent-sessions.jsonl (cross-project recency index, F2) ----
321
+ for (const row of readRecentSessions()) {
322
+ const ts = Date.parse(row.ts);
323
+ if (!Number.isFinite(ts) || ts > now || ts < cutoff)
324
+ continue;
325
+ const entry = getOrCreate(merged, row.slug, row.sid);
326
+ if (!entry.date)
327
+ entry.date = row.ts.slice(0, 10);
328
+ entry.ts = Math.max(entry.ts, ts);
329
+ if (!entry.title && row.title)
330
+ entry.title = row.title;
331
+ if (row.next_step)
332
+ entry.nextSteps = dedupPush(entry.nextSteps, row.next_step, MAX_NEXT_STEPS);
333
+ entry.provenance.add(path.join(getRoot(), "recent-sessions.jsonl"));
334
+ }
335
+ const slugs = enumerateProjectSlugs();
336
+ // ---- Source 2: journal/archive/raw/*.md (lossless verbatim tier) ----
337
+ for (const slug of slugs) {
338
+ const dir = archiveRawDir(slug);
339
+ let files;
340
+ try {
341
+ files = fs.readdirSync(dir).filter((f) => f.endsWith(".md"));
342
+ }
343
+ catch {
344
+ continue;
345
+ }
346
+ for (const file of files) {
347
+ const nameMatch = file.match(/^(\d{4}-\d{2}-\d{2})--(.+)\.md$/);
348
+ if (!nameMatch)
349
+ continue;
350
+ const [, fileDate, sid] = nameMatch;
351
+ const fileTs = Date.parse(`${fileDate}T00:00:00.000Z`);
352
+ if (!Number.isFinite(fileTs) || fileTs < cutoff)
353
+ continue;
354
+ const filePath = path.join(dir, file);
355
+ let content;
356
+ try {
357
+ content = fs.readFileSync(filePath, "utf-8");
358
+ }
359
+ catch {
360
+ continue;
361
+ }
362
+ const entry = getOrCreate(merged, slug, sid);
363
+ if (!entry.date)
364
+ entry.date = fileDate;
365
+ entry.ts = Math.max(entry.ts, fileTs);
366
+ // Raw archive bodies embed near-verbatim JSONL transcript lines after
367
+ // a frontmatter block — the SAME shape session-card.ts's rawHead/
368
+ // rawTail parses — so title/goal/artifacts/linearRefs/next-steps ALL
369
+ // use the shared RECORD-based extractors (M9-protected: a
370
+ // tool_result-embedded ref/echo cannot leak into any of them). Parsed
371
+ // ONCE and reused below — no separate per-field re-parse.
372
+ //
373
+ // fix3 (2026-07-31 — root-cause consolidation, round 2): title/goal
374
+ // and next-steps used to be derived by TEXT-level scanning of `content`
375
+ // itself (a flat `"text":"..."` regex scan for the goal, a per-line
376
+ // `NEXT_STEP_LINE_RE` grep over the raw JSONL for next-steps) — neither
377
+ // is record-aware, so (a) a `tool_result` block's nested text (e.g. a
378
+ // `remember()` call's own "Saved → ... Find again: recall(...)" echo)
379
+ // could win the flat regex scan and be reported AS the session's goal,
380
+ // and (b) a whole raw JSONL LINE containing the substring "next"/"待"
381
+ // anywhere inside an embedded JSON blob (attachment record, tool_use
382
+ // input, tool_result echo, system-reminder text, ...) was pushed
383
+ // VERBATIM as a "next step" (real-store acceptance run: rendered
384
+ // briefs showed raw `{"parentUuid":...}` records in this field). Both
385
+ // are now derived the SAME way session-card.ts derives its own
386
+ // title-fallback / finalAssistantText: `extractFirstUserTextFromRecords`
387
+ // (first real user-authored text; a `tool_result` block never
388
+ // qualifies — see that function's doc) for the goal, and
389
+ // `extractLinesMatching` run over ONLY `extractFinalRecordText(...,
390
+ // "assistant")`'s real text — never over raw `content` — for next
391
+ // steps, so a next-step line can only ever be something the assistant
392
+ // itself actually said.
393
+ //
394
+ // "Empty beats garbage" (Worker Done-Definition-adjacent rule stated
395
+ // explicitly for this fix): when nothing real parses at all — every
396
+ // line boilerplate/system-text/tool_result-only, or truncated
397
+ // mid-JSON (see the PRE-EXISTING recall-cost tradeoff note below) —
398
+ // `extractFirstUserTextFromRecords` returns null and title/goalExcerpt
399
+ // are left UNSET for this source (never a fallback slice of the raw
400
+ // frontmatter+JSONL body, which is exactly the garbage this fix
401
+ // removes). The per-project fallback to "(untitled session)" /
402
+ // goalExcerpt:"" at brief-build time (below) already handles an
403
+ // entirely-unset field.
404
+ //
405
+ // Known, PRE-EXISTING recall-cost tradeoff (not introduced by this
406
+ // fix, only extended to this call site): archive-write.ts writes the
407
+ // verbatim rawTranscript as-is, but that transcript is itself a
408
+ // byte-offset head/tail SAMPLE (transcript-reader.ts's readHeadTail),
409
+ // not a line-boundary-safe one — the last head line / first tail line
410
+ // can be truncated mid-JSON-object. `parseJsonlLenient` requires a
411
+ // whole line to `JSON.parse` and silently drops one that doesn't, so
412
+ // a `file_path`/Linear-ref/goal/next-step sitting in exactly that
413
+ // truncated boundary line is missed here, whereas the OLD flat-regex
414
+ // scan (which pattern-matched substrings, not whole records) could
415
+ // sometimes still catch it — at the cost of the garbage this fix
416
+ // removes. session-card.ts's own rawHead/rawTail parsing already
417
+ // accepted this exact tradeoff; this fix keeps resurrect.ts consistent
418
+ // with it rather than introducing a new one.
419
+ const records = parseJsonlLenient(content);
420
+ const firstUserText = extractFirstUserTextFromRecords(records);
421
+ if (firstUserText) {
422
+ const clipped = firstUserText.replace(/\s+/g, " ").trim();
423
+ if (!entry.title)
424
+ entry.title = truncateUtf8Bytes(clipped, RAW_TITLE_BYTE_CAP);
425
+ if (!entry.goalExcerpt)
426
+ entry.goalExcerpt = truncateUtf8Bytes(clipped, RAW_GOAL_BYTE_CAP);
427
+ }
428
+ for (const a of extractArtifactPathsFromRecords(records, MAX_ARTIFACTS))
429
+ entry.artifacts.add(a);
430
+ for (const r of extractLinearRefsFromRecords(records, MAX_LINEAR_REFS))
431
+ entry.linearRefs.add(r);
432
+ const finalAssistantText = extractFinalRecordText(records, "assistant") ?? "";
433
+ entry.nextSteps = dedupPushAll(entry.nextSteps, extractLinesMatching(finalAssistantText, NEXT_STEP_LINE_RE, MAX_NEXT_STEPS), MAX_NEXT_STEPS);
434
+ entry.provenance.add(filePath);
435
+ entry.rawBodies.push(content);
436
+ }
437
+ }
438
+ // ---- Source 3: journal/*--card--*.md (F3 mechanical session card) ----
439
+ for (const slug of slugs) {
440
+ const dir = journalDir(slug);
441
+ let files;
442
+ try {
443
+ files = fs.readdirSync(dir).filter((f) => f.endsWith(".md"));
444
+ }
445
+ catch {
446
+ continue;
447
+ }
448
+ for (const file of files) {
449
+ const nameMatch = file.match(/^(\d{4}-\d{2}-\d{2})--card--(.+)\.md$/);
450
+ if (!nameMatch)
451
+ continue;
452
+ const [, fileDateFromName, sidFromName] = nameMatch;
453
+ // M6 fix (review, 2026-07-31): coarse pre-filter on the FILENAME date
454
+ // BEFORE opening/parsing the file — mirrors Source 2's raw-archive
455
+ // loop above, which already rejects out-of-window files by filename
456
+ // alone. Without this, resurrect() read+parsed EVERY card file ever
457
+ // written across every project on every call, scaling with
458
+ // total-cards-ever-written instead of with the requested window. ±1
459
+ // day padding because a card's FRONTMATTER date (which wins below,
460
+ // unchanged) can legitimately differ from its filename date by up to
461
+ // a day (e.g. a session that crossed local-midnight) — this coarse
462
+ // filter must never be stricter than the precise post-parse check
463
+ // that follows it.
464
+ const fileNameTs = Date.parse(`${fileDateFromName}T00:00:00.000Z`);
465
+ if (Number.isFinite(fileNameTs) && fileNameTs < cutoff - DAY_MS)
466
+ continue;
467
+ const filePath = path.join(dir, file);
468
+ let content;
469
+ try {
470
+ content = fs.readFileSync(filePath, "utf-8");
471
+ }
472
+ catch {
473
+ continue;
474
+ }
475
+ const parsed = parseMemoryFile(content);
476
+ const sid = typeof parsed.metadata.sid === "string" && parsed.metadata.sid ? parsed.metadata.sid : sidFromName;
477
+ const cardSlug = typeof parsed.metadata.slug === "string" && parsed.metadata.slug ? parsed.metadata.slug : slug;
478
+ const cardDate = typeof parsed.metadata.date === "string" && parsed.metadata.date ? parsed.metadata.date : fileDateFromName;
479
+ const cardTs = Date.parse(`${cardDate}T00:00:00.000Z`);
480
+ if (!Number.isFinite(cardTs) || cardTs < cutoff)
481
+ continue;
482
+ const entry = getOrCreate(merged, cardSlug, sid);
483
+ entry.date = cardDate;
484
+ entry.ts = Math.max(entry.ts, cardTs);
485
+ // Card fields are the higher-confidence, already-distilled tier —
486
+ // they win outright for title/goal rather than only filling gaps.
487
+ const { goalExcerpt: bodyGoal } = extractTitleAndGoal(parsed.body);
488
+ entry.title = parsed.title || entry.title || "(untitled session)";
489
+ entry.goalExcerpt = bodyGoal || entry.goalExcerpt || "";
490
+ // Card bodies are already-rendered markdown (session-card.ts's OWN
491
+ // output, itself built from the M9-protected record extractors) — no
492
+ // record structure survives to recover, and no raw tool_result JSON
493
+ // blob is ever present to exclude, so the TEXT-based shared
494
+ // extractors are the right (and only sensible) tool here.
495
+ for (const a of extractArtifactPathsFromText(parsed.body, MAX_ARTIFACTS))
496
+ entry.artifacts.add(a);
497
+ for (const r of extractLinearRefsFromText(parsed.body, MAX_LINEAR_REFS))
498
+ entry.linearRefs.add(r);
499
+ const cardNextSteps = extractLinesMatching(parsed.body, NEXT_STEP_LINE_RE, MAX_NEXT_STEPS);
500
+ if (cardNextSteps.length > 0)
501
+ entry.nextSteps = cardNextSteps.slice(0, MAX_NEXT_STEPS);
502
+ entry.provenance.add(filePath);
503
+ }
504
+ }
505
+ // ---- Score + build briefs ----
506
+ const briefs = [];
507
+ for (const entry of merged.values()) {
508
+ briefs.push({
509
+ slug: entry.slug,
510
+ sid: entry.sid,
511
+ date: entry.date || "unknown",
512
+ title: entry.title || "(untitled session)",
513
+ goalExcerpt: entry.goalExcerpt || "",
514
+ artifacts: [...entry.artifacts].slice(0, MAX_ARTIFACTS),
515
+ linearRefs: [...entry.linearRefs].slice(0, MAX_LINEAR_REFS),
516
+ nextSteps: entry.nextSteps.slice(0, MAX_NEXT_STEPS),
517
+ provenance: [...entry.provenance],
518
+ score: computeScore(entry, queryTerms, now, days),
519
+ });
520
+ }
521
+ briefs.sort((a, b) => b.score - a.score);
522
+ return briefs.slice(0, limit);
523
+ }
524
+ /**
525
+ * Markdown renderer for a list of ContinuityBriefs (CLI command wiring for
526
+ * `ar resurrect` is Wave-2's job — this is just the render function it will
527
+ * call). Never returns an empty string: an empty result set still renders a
528
+ * one-line "nothing found" message so a caller always has something to print.
529
+ */
530
+ export function renderResurrectMarkdown(briefs) {
531
+ if (briefs.length === 0) {
532
+ return "No dead sessions found in the requested window.\n";
533
+ }
534
+ const lines = [];
535
+ for (const brief of briefs) {
536
+ lines.push(`## ${brief.title}`);
537
+ lines.push(`- slug: ${brief.slug}`);
538
+ lines.push(`- sid: ${brief.sid}`);
539
+ lines.push(`- date: ${brief.date}`);
540
+ if (brief.goalExcerpt)
541
+ lines.push(`- goal: ${brief.goalExcerpt}`);
542
+ if (brief.linearRefs.length > 0)
543
+ lines.push(`- linear: ${brief.linearRefs.join(", ")}`);
544
+ if (brief.artifacts.length > 0) {
545
+ lines.push("- artifacts:");
546
+ for (const artifact of brief.artifacts)
547
+ lines.push(` - ${artifact}`);
548
+ }
549
+ if (brief.nextSteps.length > 0) {
550
+ lines.push("- next steps:");
551
+ for (const step of brief.nextSteps)
552
+ lines.push(` - ${step}`);
553
+ }
554
+ lines.push("- provenance:");
555
+ for (const source of brief.provenance)
556
+ lines.push(` - ${source}`);
557
+ lines.push("");
558
+ }
559
+ return lines.join("\n").trimEnd() + "\n";
560
+ }
561
+ //# sourceMappingURL=resurrect.js.map