agent-recall-core 3.5.2 → 3.5.3

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 (114) hide show
  1. package/README.md +254 -143
  2. package/dist/digest/match.d.ts +2 -0
  3. package/dist/digest/match.d.ts.map +1 -1
  4. package/dist/digest/match.js +5 -0
  5. package/dist/digest/match.js.map +1 -1
  6. package/dist/digest/store.d.ts.map +1 -1
  7. package/dist/digest/store.js +2 -3
  8. package/dist/digest/store.js.map +1 -1
  9. package/dist/index.d.ts +17 -4
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +10 -3
  12. package/dist/index.js.map +1 -1
  13. package/dist/palace/rooms.d.ts +7 -0
  14. package/dist/palace/rooms.d.ts.map +1 -1
  15. package/dist/palace/rooms.js +13 -0
  16. package/dist/palace/rooms.js.map +1 -1
  17. package/dist/retrieval/lexical-index.d.ts.map +1 -1
  18. package/dist/retrieval/lexical-index.js +3 -1
  19. package/dist/retrieval/lexical-index.js.map +1 -1
  20. package/dist/retrieval/query-memory.d.ts.map +1 -1
  21. package/dist/retrieval/query-memory.js +5 -3
  22. package/dist/retrieval/query-memory.js.map +1 -1
  23. package/dist/storage/classification.d.ts.map +1 -1
  24. package/dist/storage/classification.js +2 -0
  25. package/dist/storage/classification.js.map +1 -1
  26. package/dist/storage/content-guard.d.ts +6 -0
  27. package/dist/storage/content-guard.d.ts.map +1 -1
  28. package/dist/storage/content-guard.js +17 -0
  29. package/dist/storage/content-guard.js.map +1 -1
  30. package/dist/storage/corrections.d.ts +3 -1
  31. package/dist/storage/corrections.d.ts.map +1 -1
  32. package/dist/storage/corrections.js +5 -1
  33. package/dist/storage/corrections.js.map +1 -1
  34. package/dist/storage/cwd-allowlist.d.ts +2 -0
  35. package/dist/storage/cwd-allowlist.d.ts.map +1 -1
  36. package/dist/storage/cwd-allowlist.js +49 -14
  37. package/dist/storage/cwd-allowlist.js.map +1 -1
  38. package/dist/storage/deferred-bookkeeping.d.ts +34 -0
  39. package/dist/storage/deferred-bookkeeping.d.ts.map +1 -0
  40. package/dist/storage/deferred-bookkeeping.js +201 -0
  41. package/dist/storage/deferred-bookkeeping.js.map +1 -0
  42. package/dist/storage/frontmatter.d.ts +14 -0
  43. package/dist/storage/frontmatter.d.ts.map +1 -0
  44. package/dist/storage/frontmatter.js +22 -0
  45. package/dist/storage/frontmatter.js.map +1 -0
  46. package/dist/storage/fs-utils.d.ts +2 -0
  47. package/dist/storage/fs-utils.d.ts.map +1 -1
  48. package/dist/storage/fs-utils.js +17 -0
  49. package/dist/storage/fs-utils.js.map +1 -1
  50. package/dist/storage/hook-session.d.ts +9 -0
  51. package/dist/storage/hook-session.d.ts.map +1 -0
  52. package/dist/storage/hook-session.js +49 -0
  53. package/dist/storage/hook-session.js.map +1 -0
  54. package/dist/storage/identity-card.d.ts +27 -0
  55. package/dist/storage/identity-card.d.ts.map +1 -0
  56. package/dist/storage/identity-card.js +86 -0
  57. package/dist/storage/identity-card.js.map +1 -0
  58. package/dist/storage/lifecycle-telemetry.d.ts +1 -1
  59. package/dist/storage/lifecycle-telemetry.d.ts.map +1 -1
  60. package/dist/storage/lifecycle-telemetry.js +2 -2
  61. package/dist/storage/lifecycle-telemetry.js.map +1 -1
  62. package/dist/storage/pending.d.ts +39 -3
  63. package/dist/storage/pending.d.ts.map +1 -1
  64. package/dist/storage/pending.js +126 -20
  65. package/dist/storage/pending.js.map +1 -1
  66. package/dist/storage/project.d.ts.map +1 -1
  67. package/dist/storage/project.js +25 -7
  68. package/dist/storage/project.js.map +1 -1
  69. package/dist/storage/session.d.ts.map +1 -1
  70. package/dist/storage/session.js +43 -16
  71. package/dist/storage/session.js.map +1 -1
  72. package/dist/storage/state-card.d.ts +59 -0
  73. package/dist/storage/state-card.d.ts.map +1 -0
  74. package/dist/storage/state-card.js +162 -0
  75. package/dist/storage/state-card.js.map +1 -0
  76. package/dist/storage/unclaimed.js +2 -2
  77. package/dist/storage/unclaimed.js.map +1 -1
  78. package/dist/supabase/config.d.ts.map +1 -1
  79. package/dist/supabase/config.js +7 -1
  80. package/dist/supabase/config.js.map +1 -1
  81. package/dist/tools-logic/check.d.ts +62 -2
  82. package/dist/tools-logic/check.d.ts.map +1 -1
  83. package/dist/tools-logic/check.js +226 -13
  84. package/dist/tools-logic/check.js.map +1 -1
  85. package/dist/tools-logic/recall-backend.d.ts.map +1 -1
  86. package/dist/tools-logic/recall-backend.js +8 -0
  87. package/dist/tools-logic/recall-backend.js.map +1 -1
  88. package/dist/tools-logic/session-end.d.ts +18 -1
  89. package/dist/tools-logic/session-end.d.ts.map +1 -1
  90. package/dist/tools-logic/session-end.js +36 -5
  91. package/dist/tools-logic/session-end.js.map +1 -1
  92. package/dist/tools-logic/session-start-render.d.ts +35 -0
  93. package/dist/tools-logic/session-start-render.d.ts.map +1 -0
  94. package/dist/tools-logic/session-start-render.js +240 -0
  95. package/dist/tools-logic/session-start-render.js.map +1 -0
  96. package/dist/tools-logic/session-start.d.ts +21 -0
  97. package/dist/tools-logic/session-start.d.ts.map +1 -1
  98. package/dist/tools-logic/session-start.js +279 -225
  99. package/dist/tools-logic/session-start.js.map +1 -1
  100. package/dist/tools-logic/smart-recall.d.ts +8 -0
  101. package/dist/tools-logic/smart-recall.d.ts.map +1 -1
  102. package/dist/tools-logic/smart-recall.js +24 -5
  103. package/dist/tools-logic/smart-recall.js.map +1 -1
  104. package/dist/tools-logic/smart-remember.d.ts.map +1 -1
  105. package/dist/tools-logic/smart-remember.js +2 -3
  106. package/dist/tools-logic/smart-remember.js.map +1 -1
  107. package/dist/types.d.ts +82 -1
  108. package/dist/types.d.ts.map +1 -1
  109. package/dist/types.js +134 -1
  110. package/dist/types.js.map +1 -1
  111. package/dist/vector/embedding.d.ts.map +1 -1
  112. package/dist/vector/embedding.js +3 -0
  113. package/dist/vector/embedding.js.map +1 -1
  114. package/package.json +2 -2
@@ -3,13 +3,21 @@
3
3
  *
4
4
  * Replaces: journal_cold_start + palace_walk + recall_insight
5
5
  * Target: <400 tokens output. No awareness duplication.
6
+ *
7
+ * Cards v2 (G6): `mode: "cards"` (the agent-facing default at the MCP tool, hook-start and the SDK) loads
8
+ * Owner → HARD RULES (P0 corrections and behaviour policies) → State, plus the one-line pending-review
9
+ * count, and nothing else; `mode: "full"` (this function's own default) is the complete
10
+ * payload. Side effects run in both modes — see the `full` guards below.
6
11
  */
7
12
  import { resolveProject, isValidProjectSlug } from "../storage/project.js";
8
13
  import { resetOwnedFiles, getSessionId, claimSessionStartOnce } from "../storage/session.js";
9
14
  import { recordLifecycleEvent } from "../storage/lifecycle-telemetry.js";
10
- import { ensurePalaceInitialized, listRooms, isRoomStale, countRoomEntries } from "../palace/rooms.js";
11
- import { DEFAULT_PALACE_ROOMS, getRoot } from "../types.js";
15
+ import { bookkeep } from "../storage/deferred-bookkeeping.js";
16
+ import { ensurePalaceInitializedForRead, listRooms, isRoomStale, countRoomEntries } from "../palace/rooms.js";
17
+ import { DEFAULT_PALACE_ROOMS, getRoot, isTenantScoped } from "../types.js";
12
18
  import { readIdentity } from "../palace/identity.js";
19
+ import { readIdentityCard } from "../storage/identity-card.js";
20
+ import { readStateCard, stateCardHasContent } from "../storage/state-card.js";
13
21
  import { readAwarenessState, fetchDashboardArchivedTitles } from "../palace/awareness.js";
14
22
  import { recallInsights, readInsightsIndex } from "../palace/insights-index.js";
15
23
  import { journalDirs, projectSubPath } from "../storage/paths.js";
@@ -246,12 +254,15 @@ export async function sessionStart(input) {
246
254
  // Reset owned-files state from any previous session in the same process
247
255
  resetOwnedFiles();
248
256
  const slug = await resolveProject(input.project);
257
+ // Cards v2 (G6): "cards" skips every read below that is not Owner / HARD RULES / State; side effects run in both modes.
258
+ const mode = input.mode ?? "full";
259
+ const full = mode === "full";
249
260
  // fix5 (2026-09-11): ensurePalaceInitialized no-ops for the `_unclaimed`
250
261
  // staging sentinel internally (palace/rooms.ts) — a failed resolution must
251
262
  // not scaffold a palace anywhere, and everything below degrades to empty
252
263
  // reads for the sentinel. Call left unconditional so the gate lives in ONE
253
264
  // place (the function itself), not per-caller.
254
- ensurePalaceInitialized(slug);
265
+ ensurePalaceInitializedForRead(slug); // a read of a project with no palace yet does not create one
255
266
  // C2 (2026-07-26) — idempotency: getSessionId() is process-scoped, a
256
267
  // workable identity for one MCP-server lifetime. claimSessionStartOnce
257
268
  // returns true only on the FIRST session_start call for (this session,
@@ -282,91 +293,112 @@ export async function sessionStart(input) {
282
293
  warnForcedWithoutEnabled();
283
294
  }
284
295
  const abArm = abAssignment?.arm ?? null;
285
- // 1. Identity — first meaningful lines, skipping YAML frontmatter keys and empty template stubs
286
- const rawIdentity = readIdentity(slug);
287
- const identityLines = rawIdentity.split("\n").filter((l) => {
288
- const t = l.trim();
289
- if (!t)
290
- return false;
291
- if (t.startsWith("---"))
292
- return false;
293
- if (t.startsWith(">"))
294
- return false;
295
- // Skip raw YAML frontmatter key-value lines like "project: foo" or "created: ..."
296
- if (/^[a-z_]+:\s/.test(t))
297
- return false;
298
- // Skip unfilled template stubs
299
- if (t.startsWith("_(fill in"))
300
- return false;
301
- return true;
302
- });
303
- const identity = identityLines.slice(0, 2).map((l) => l.trim().replace(/^#+\s*/, "")).join(" ").trim() || slug;
304
- // 2. Top insights from awareness state — sort by confirmations DESC, recency DESC
305
- const state = readAwarenessState();
306
- let sortedInsights = (state?.topInsights ?? []).slice().sort((a, b) => {
307
- if (b.confirmations !== a.confirmations)
308
- return b.confirmations - a.confirmations;
309
- // Tiebreak: most recently confirmed first
310
- return (b.lastConfirmed ?? "").localeCompare(a.lastConfirmed ?? "");
311
- });
312
- // Filter out insights archived via the dashboard (Supabase sync-back).
313
- // Case-insensitive match — dedup elsewhere normalizes to lowercase, so the
314
- // archive filter must too (else "Bug Fix" fails to suppress "bug fix").
315
- const archivedLower = new Set((await fetchDashboardArchivedTitles()).map((t) => t.toLowerCase()));
316
- if (archivedLower.size > 0) {
317
- sortedInsights = sortedInsights.filter(i => !archivedLower.has(i.title.toLowerCase()));
318
- }
319
- // Cap startup noise: top 3 awareness insights (was 8). Anything below the
320
- // top 3 by salience pollutes more than it informs at session-start. Agents
321
- // can pull deeper via recall() on demand.
322
- const insights = sortedInsights.slice(0, 3).map((i) => ({
323
- title: sliceAtWord(i.title, 200),
324
- confirmed: i.confirmations ?? 1,
325
- severity: i.severity ?? "important",
326
- trend: i.trend,
327
- }));
328
- // 2b. P0-3 — guarantee a session-1 insight is visible at session-2.
329
- // Confirmation count must control ORDER/verbosity, never EXISTENCE. The
330
- // global awareness `topInsights` only receives an index insight once
331
- // `promoteConfirmedInsights` fires (confirmed_count >= 3), so a brand-new
332
- // single-confirmation insight stored by session_end can be absent from
333
- // `topInsights` while living in the project-scoped insights-index. Surface
334
- // those directly so they appear from confirmation count 1.
335
- const index = readInsightsIndex();
336
- const projectIndexInsights = index.insights
337
- .filter((i) => (i.projects ?? []).includes(slug))
338
- .filter((i) => !archivedLower.has(i.title.toLowerCase()))
339
- .sort((a, b) => b.confirmed_count - a.confirmed_count || (b.last_confirmed ?? "").localeCompare(a.last_confirmed ?? ""));
340
- // RESERVED SLOTS: project-scoped index insights get their own budget (up to 2)
341
- // ON TOP of the awareness top-3. If we shared one cap, an established project
342
- // whose global awareness already has 3+ insights would never surface a fresh
343
- // session-1 insight — the cap would be full before this loop ran. P0-3 requires
344
- // existence, not just ordering, so the budget must be independent.
345
- const seenTitles = new Set(insights.map((i) => i.title.toLowerCase()));
346
- const PROJECT_INSIGHT_BUDGET = 2;
347
- let projectAdded = 0;
348
- for (const idx of projectIndexInsights) {
349
- if (projectAdded >= PROJECT_INSIGHT_BUDGET)
350
- break;
351
- if (seenTitles.has(idx.title.toLowerCase()))
352
- continue;
353
- insights.push({
354
- title: sliceAtWord(idx.title, 200),
355
- confirmed: idx.confirmed_count ?? 1,
356
- severity: idx.severity ?? "important",
357
- trend: undefined,
296
+ // 1. Identity — first meaningful lines, skipping YAML frontmatter keys and empty template stubs.
297
+ // Cards v2: cards mode renders no Intention line, so identity.md is not read and `identity` is the slug.
298
+ let identity = slug;
299
+ if (full) {
300
+ const rawIdentity = readIdentity(slug);
301
+ const identityLines = rawIdentity.split("\n").filter((l) => {
302
+ const t = l.trim();
303
+ if (!t)
304
+ return false;
305
+ if (t.startsWith("---"))
306
+ return false;
307
+ if (t.startsWith(">"))
308
+ return false;
309
+ // Skip raw YAML frontmatter key-value lines like "project: foo" or "created: ..."
310
+ if (/^[a-z_]+:\s/.test(t))
311
+ return false;
312
+ // Skip unfilled template stubs
313
+ if (t.startsWith("_(fill in"))
314
+ return false;
315
+ return true;
358
316
  });
359
- seenTitles.add(idx.title.toLowerCase());
360
- projectAdded++;
317
+ identity = identityLines.slice(0, 2).map((l) => l.trim().replace(/^#+\s*/, "")).join(" ").trim() || slug;
361
318
  }
362
- // Keep highest-confirmed first (order, not existence, is the threshold's job).
363
- // Total visible = up to 3 awareness + up to 2 project-scoped = max 5.
364
- insights.sort((a, b) => b.confirmed - a.confirmed);
319
+ // Cards v1 — readers never throw (stderr line + null); try is belt-and-braces.
320
+ let ownerCard;
321
+ let stateCard;
322
+ try {
323
+ const ic = readIdentityCard();
324
+ if (ic?.body.trim())
325
+ ownerCard = { version: ic.version, body: ic.body };
326
+ }
327
+ catch { /* omit */ }
328
+ try {
329
+ stateCard = readStateCard(slug) ?? undefined;
330
+ }
331
+ catch { /* omit */ }
332
+ // 2. Top insights from awareness state — sort by confirmations DESC, recency DESC.
333
+ // Cards v2: the whole insights block (awareness state, dashboard archive, insights index) is full-mode only.
334
+ const insights = [];
335
+ if (full) {
336
+ const state = readAwarenessState();
337
+ let sortedInsights = (state?.topInsights ?? []).slice().sort((a, b) => {
338
+ if (b.confirmations !== a.confirmations)
339
+ return b.confirmations - a.confirmations;
340
+ // Tiebreak: most recently confirmed first
341
+ return (b.lastConfirmed ?? "").localeCompare(a.lastConfirmed ?? "");
342
+ });
343
+ // Filter out insights archived via the dashboard (Supabase sync-back).
344
+ // Case-insensitive match — dedup elsewhere normalizes to lowercase, so the
345
+ // archive filter must too (else "Bug Fix" fails to suppress "bug fix").
346
+ const archivedLower = new Set((await fetchDashboardArchivedTitles()).map((t) => t.toLowerCase()));
347
+ if (archivedLower.size > 0) {
348
+ sortedInsights = sortedInsights.filter(i => !archivedLower.has(i.title.toLowerCase()));
349
+ }
350
+ // Cap startup noise: top 3 awareness insights (was 8). Anything below the
351
+ // top 3 by salience pollutes more than it informs at session-start. Agents
352
+ // can pull deeper via recall() on demand.
353
+ insights.push(...sortedInsights.slice(0, 3).map((i) => ({
354
+ title: sliceAtWord(i.title, 200),
355
+ confirmed: i.confirmations ?? 1,
356
+ severity: i.severity ?? "important",
357
+ trend: i.trend,
358
+ })));
359
+ // 2b. P0-3 — guarantee a session-1 insight is visible at session-2.
360
+ // Confirmation count must control ORDER/verbosity, never EXISTENCE. The
361
+ // global awareness `topInsights` only receives an index insight once
362
+ // `promoteConfirmedInsights` fires (confirmed_count >= 3), so a brand-new
363
+ // single-confirmation insight stored by session_end can be absent from
364
+ // `topInsights` while living in the project-scoped insights-index. Surface
365
+ // those directly so they appear from confirmation count 1.
366
+ const index = readInsightsIndex();
367
+ const projectIndexInsights = index.insights
368
+ .filter((i) => (i.projects ?? []).includes(slug))
369
+ .filter((i) => !archivedLower.has(i.title.toLowerCase()))
370
+ .sort((a, b) => b.confirmed_count - a.confirmed_count || (b.last_confirmed ?? "").localeCompare(a.last_confirmed ?? ""));
371
+ // RESERVED SLOTS: project-scoped index insights get their own budget (up to 2)
372
+ // ON TOP of the awareness top-3. If we shared one cap, an established project
373
+ // whose global awareness already has 3+ insights would never surface a fresh
374
+ // session-1 insight — the cap would be full before this loop ran. P0-3 requires
375
+ // existence, not just ordering, so the budget must be independent.
376
+ const seenTitles = new Set(insights.map((i) => i.title.toLowerCase()));
377
+ const PROJECT_INSIGHT_BUDGET = 2;
378
+ let projectAdded = 0;
379
+ for (const idx of projectIndexInsights) {
380
+ if (projectAdded >= PROJECT_INSIGHT_BUDGET)
381
+ break;
382
+ if (seenTitles.has(idx.title.toLowerCase()))
383
+ continue;
384
+ insights.push({
385
+ title: sliceAtWord(idx.title, 200),
386
+ confirmed: idx.confirmed_count ?? 1,
387
+ severity: idx.severity ?? "important",
388
+ trend: undefined,
389
+ });
390
+ seenTitles.add(idx.title.toLowerCase());
391
+ projectAdded++;
392
+ }
393
+ // Keep highest-confirmed first (order, not existence, is the threshold's job).
394
+ // Total visible = up to 3 awareness + up to 2 project-scoped = max 5.
395
+ insights.sort((a, b) => b.confirmed - a.confirmed);
396
+ } // end full-mode insights block
365
397
  // 3. Active rooms — top 3 by salience (was 5). Same noise-cap rationale.
366
398
  // Call listRooms ONCE — it internally scans every room via countRoomEntries
367
399
  // to enforce the empty-last sort. Reuse the result for both active_rooms and
368
400
  // the hasPalaceContent check below (avoids a 2nd full sort + 3rd scan pass).
369
- const allRooms = listRooms(slug);
401
+ const allRooms = full ? listRooms(slug) : []; // Cards v2: no palace scan in cards mode
370
402
  const rooms = allRooms.slice(0, 3);
371
403
  const active_rooms = rooms.map((r) => ({
372
404
  name: r.name,
@@ -433,7 +465,7 @@ export async function sessionStart(input) {
433
465
  // uses, so a future caller-supplied scope option is a one-line change
434
466
  // here instead of a fresh migration.
435
467
  const context = input.context ?? slug;
436
- const matched = applyScope(recallInsights(context, 1, slug), slug, "all");
468
+ const matched = full ? applyScope(recallInsights(context, 1, slug), slug, "all") : []; // Cards v2: full mode only
437
469
  const cross_project = matched.map((i) => ({
438
470
  title: sliceAtWord(i.title, 100),
439
471
  from_project: (i.projects?.[0] ?? (i.source ?? "unknown").replace(/\s+\d{4}-\d{2}-\d{2}.*$/, "")).slice(0, 30),
@@ -466,8 +498,10 @@ export async function sessionStart(input) {
466
498
  // accepted as an acceptable synchronous cost at session_start/hook-start
467
499
  // frequency (not the ambient-capture hot path) — only its POSITION within
468
500
  // sessionStart() changed, not its cost or its failure semantics.
501
+ // Deferred inside a read (it writes journal entries and the recency ledger): a crashed session is recovered by
502
+ // the next flush, so only the same call's full-mode continuity no longer shows it.
469
503
  try {
470
- rescueOrphanedWorkingMemory();
504
+ void bookkeep({ key: "wm-rescue", apply: () => { rescueOrphanedWorkingMemory(); } });
471
505
  }
472
506
  catch {
473
507
  // rescueOrphanedWorkingMemory never throws — guard kept so a future
@@ -482,8 +516,8 @@ export async function sessionStart(input) {
482
516
  // the guard mirrors the rescue call's.
483
517
  let unclaimedCount = 0;
484
518
  try {
485
- archiveExpiredUnclaimed();
486
- unclaimedCount = countUnclaimedSessions();
519
+ void bookkeep({ key: "unclaimed-ttl", apply: () => { archiveExpiredUnclaimed(); } }); // both modes: the TTL sweep is maintenance, not payload
520
+ unclaimedCount = full ? countUnclaimedSessions() : 0;
487
521
  }
488
522
  catch {
489
523
  unclaimedCount = 0;
@@ -494,70 +528,71 @@ export async function sessionStart(input) {
494
528
  // stays visible even when THIS project has no journal entries of its own
495
529
  // yet. Best-effort: a missing/corrupt index must never break orientation.
496
530
  let continuity;
497
- try {
498
- // Identity-trust (CRITICAL-1 followup, 2026-08-20): a working-memory-
499
- // rescue ledger entry (recency-index.ts's `source` tag, set by
500
- // storage/working-memory.ts's `distillOneSession`) is filed under an
501
- // unauthenticated cwd-guess — the red-team CRITICAL-2 fixture showed
502
- // this exact field surfacing a hijacked title verbatim in `continuity`,
503
- // printed automatically into every session's context via the CLI's
504
- // hook-start "📓 Today:"/continuity render, with zero agent action
505
- // required.
506
- //
507
- // UNLIKE journalSearch/session-start's own recent-briefs/resume readers
508
- // (which exclude rescue-sourced content outright — see
509
- // journal-filter.ts's isRescueSourcedContent), `continuity` cannot use
510
- // blanket exclusion: a genuinely crashed session's OWN rescue is a
511
- // shipped, tested product feature (session-start-wm-rescue-ordering.
512
- // test.mjs's M2 acceptance criterion, working-memory-wave.test.mjs's
513
- // "e2e crash-rescue round trip" — both require a just-rescued session to
514
- // appear in continuity). Excluding it outright would silence a real
515
- // crash-recovery signal the owner explicitly wanted ("like a human
516
- // brain — you need to know what happened 10 minutes before").
517
- //
518
- // Fix: mirror resurrect()'s own two-tier approach instead of excluding —
519
- // trusted entries always sort ahead of untrusted ones (a rescue entry
520
- // can never DISPLACE a genuine entry out of the top-3 by recency alone,
521
- // regardless of how fresh its self-claimed mtime is), and every
522
- // untrusted entry is tagged (`untrusted: true`) so both renderers (CLI
523
- // hook-start, MCP formatTerse) can visibly label it rather than
524
- // presenting it as verified memory. Over-fetch past the eventual
525
- // `.slice(0, 3)` cap so an untrusted entry occupying one of the naive
526
- // top-3-by-recency ledger rows doesn't silently shrink the visible
527
- // TRUSTED continuity list below 3 entries.
528
- const recentSessions = readRecentSessions(20);
529
- const tiered = [...recentSessions].sort((a, b) => {
530
- const aUntrusted = isRescueSourceTag(a.source);
531
- const bUntrusted = isRescueSourceTag(b.source);
532
- if (aUntrusted !== bUntrusted)
533
- return aUntrusted ? 1 : -1;
534
- return 0; // stable — readRecentSessions is already newest-first within each tier
535
- }).slice(0, 3);
536
- if (tiered.length > 0) {
537
- continuity = tiered.map((s) => ({
538
- ago: formatAgo(s.ts),
539
- slug: s.slug,
540
- // M7 fix: BYTE-based truncation (truncateUtf8Bytes), not sliceAtWord's
541
- // char-based truncation — see continuity_title/continuity_next_step's
542
- // doc comment above.
543
- title: truncateUtf8Bytes(s.title, SECTION_CHAR_LIMITS.continuity_title),
544
- next_step: s.next_step ? truncateUtf8Bytes(s.next_step, SECTION_CHAR_LIMITS.continuity_next_step) : undefined,
545
- // Identity-trust (2026-08-20): present ONLY when true (never `false`)
546
- // — matches recency-index.ts's own `source` field convention so
547
- // pre-existing/legacy entries with no signal at all are correctly
548
- // treated as trusted.
549
- untrusted: isRescueSourceTag(s.source) ? true : undefined,
550
- // Fable option 2 (label-not-scope, 2026-08-30): label, don't filter —
551
- // see isCurrentProjectContinuityEntry's doc comment. Compares
552
- // against the RESOLVED `slug` (post resolveProject, in scope from
553
- // this function's top), never raw input.
554
- is_current_project: isCurrentProjectContinuityEntry({ slug: s.slug }, slug),
555
- }));
531
+ if (full)
532
+ try { // Cards v2: cards mode reads no recency index
533
+ // Identity-trust (CRITICAL-1 followup, 2026-08-20): a working-memory-
534
+ // rescue ledger entry (recency-index.ts's `source` tag, set by
535
+ // storage/working-memory.ts's `distillOneSession`) is filed under an
536
+ // unauthenticated cwd-guess — the red-team CRITICAL-2 fixture showed
537
+ // this exact field surfacing a hijacked title verbatim in `continuity`,
538
+ // printed automatically into every session's context via the CLI's
539
+ // hook-start "📓 Today:"/continuity render, with zero agent action
540
+ // required.
541
+ //
542
+ // UNLIKE journalSearch/session-start's own recent-briefs/resume readers
543
+ // (which exclude rescue-sourced content outright — see
544
+ // journal-filter.ts's isRescueSourcedContent), `continuity` cannot use
545
+ // blanket exclusion: a genuinely crashed session's OWN rescue is a
546
+ // shipped, tested product feature (session-start-wm-rescue-ordering.
547
+ // test.mjs's M2 acceptance criterion, working-memory-wave.test.mjs's
548
+ // "e2e crash-rescue round trip" — both require a just-rescued session to
549
+ // appear in continuity). Excluding it outright would silence a real
550
+ // crash-recovery signal the owner explicitly wanted ("like a human
551
+ // brain — you need to know what happened 10 minutes before").
552
+ //
553
+ // Fix: mirror resurrect()'s own two-tier approach instead of excluding —
554
+ // trusted entries always sort ahead of untrusted ones (a rescue entry
555
+ // can never DISPLACE a genuine entry out of the top-3 by recency alone,
556
+ // regardless of how fresh its self-claimed mtime is), and every
557
+ // untrusted entry is tagged (`untrusted: true`) so both renderers (CLI
558
+ // hook-start, MCP formatTerse) can visibly label it rather than
559
+ // presenting it as verified memory. Over-fetch past the eventual
560
+ // `.slice(0, 3)` cap so an untrusted entry occupying one of the naive
561
+ // top-3-by-recency ledger rows doesn't silently shrink the visible
562
+ // TRUSTED continuity list below 3 entries.
563
+ const recentSessions = readRecentSessions(20);
564
+ const tiered = [...recentSessions].sort((a, b) => {
565
+ const aUntrusted = isRescueSourceTag(a.source);
566
+ const bUntrusted = isRescueSourceTag(b.source);
567
+ if (aUntrusted !== bUntrusted)
568
+ return aUntrusted ? 1 : -1;
569
+ return 0; // stable — readRecentSessions is already newest-first within each tier
570
+ }).slice(0, 3);
571
+ if (tiered.length > 0) {
572
+ continuity = tiered.map((s) => ({
573
+ ago: formatAgo(s.ts),
574
+ slug: s.slug,
575
+ // M7 fix: BYTE-based truncation (truncateUtf8Bytes), not sliceAtWord's
576
+ // char-based truncation — see continuity_title/continuity_next_step's
577
+ // doc comment above.
578
+ title: truncateUtf8Bytes(s.title, SECTION_CHAR_LIMITS.continuity_title),
579
+ next_step: s.next_step ? truncateUtf8Bytes(s.next_step, SECTION_CHAR_LIMITS.continuity_next_step) : undefined,
580
+ // Identity-trust (2026-08-20): present ONLY when true (never `false`)
581
+ // — matches recency-index.ts's own `source` field convention so
582
+ // pre-existing/legacy entries with no signal at all are correctly
583
+ // treated as trusted.
584
+ untrusted: isRescueSourceTag(s.source) ? true : undefined,
585
+ // Fable option 2 (label-not-scope, 2026-08-30): label, don't filter —
586
+ // see isCurrentProjectContinuityEntry's doc comment. Compares
587
+ // against the RESOLVED `slug` (post resolveProject, in scope from
588
+ // this function's top), never raw input.
589
+ is_current_project: isCurrentProjectContinuityEntry({ slug: s.slug }, slug),
590
+ }));
591
+ }
592
+ }
593
+ catch {
594
+ continuity = undefined;
556
595
  }
557
- }
558
- catch {
559
- continuity = undefined;
560
- }
561
596
  // 4c. Working-memory "live" line (v3.4.42 working-memory wave, design doc
562
597
  // §Consume 1) — a cross-window signal that ANOTHER Claude Code session is
563
598
  // (or was, within WM_LIVE_WINDOW_MS) actively running elsewhere RIGHT NOW,
@@ -569,42 +604,43 @@ export async function sessionStart(input) {
569
604
  // keep in sync. Max one entry, newest non-self WM file only; omitted
570
605
  // entirely when none qualify. Best-effort: any WM read failure must never
571
606
  // break orientation.
572
- try {
573
- const now = Date.now();
574
- const candidates = wmList().filter((f) => now - f.mtimeMs < WM_LIVE_WINDOW_MS && (!input.sid || f.sid !== input.sid));
575
- if (candidates.length > 0) {
576
- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
577
- const newest = candidates[0];
578
- const wmLines = wmRead(newest.sid);
579
- if (wmLines.length > 0) {
580
- const lastLine = wmLines[wmLines.length - 1];
581
- // M2 fix (review, post-build): the raw `path.basename(cwd)` fallback
582
- // bypassed `isValidProjectSlug` entirely — unlike `guessSlugFromWmLines`
583
- // itself (which gates every candidate through that same check) and
584
- // unlike F1's own claim-not-generate policy. A cwd basename can be a
585
- // deny-listed word ("build", "test", …), a UUID-shaped segment, or a
586
- // dotfile-style name, any of which would otherwise surface directly
587
- // as a "project" in the live continuity line. Validate before using
588
- // it; fall back to the documented "auto" sentinel otherwise.
589
- const cwdBase = lastLine.cwd ? path.basename(lastLine.cwd) : null;
590
- const validCwdBase = cwdBase && isValidProjectSlug(cwdBase) ? cwdBase : null;
591
- const liveSlug = guessSlugFromWmLines(wmLines) ?? validCwdBase ?? "auto";
592
- const liveEntry = {
593
- ago: formatAgo(new Date(newest.mtimeMs).toISOString()),
594
- slug: liveSlug,
595
- title: truncateUtf8Bytes(`🔴 live — ${lastLine.prompt}`, SECTION_CHAR_LIMITS.continuity_title),
596
- // Fable option 2 (label-not-scope, 2026-08-30) — same labeling as
597
- // the ledger-sourced entries above; the "live" line is prepended
598
- // to the SAME `continuity` array and must carry the same label.
599
- is_current_project: isCurrentProjectContinuityEntry({ slug: liveSlug }, slug),
600
- };
601
- continuity = continuity ? [liveEntry, ...continuity] : [liveEntry];
607
+ if (full)
608
+ try { // Cards v2: cards mode shows no live line
609
+ const now = Date.now();
610
+ const candidates = wmList().filter((f) => now - f.mtimeMs < WM_LIVE_WINDOW_MS && (!input.sid || f.sid !== input.sid));
611
+ if (candidates.length > 0) {
612
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
613
+ const newest = candidates[0];
614
+ const wmLines = wmRead(newest.sid);
615
+ if (wmLines.length > 0) {
616
+ const lastLine = wmLines[wmLines.length - 1];
617
+ // M2 fix (review, post-build): the raw `path.basename(cwd)` fallback
618
+ // bypassed `isValidProjectSlug` entirely — unlike `guessSlugFromWmLines`
619
+ // itself (which gates every candidate through that same check) and
620
+ // unlike F1's own claim-not-generate policy. A cwd basename can be a
621
+ // deny-listed word ("build", "test", …), a UUID-shaped segment, or a
622
+ // dotfile-style name, any of which would otherwise surface directly
623
+ // as a "project" in the live continuity line. Validate before using
624
+ // it; fall back to the documented "auto" sentinel otherwise.
625
+ const cwdBase = lastLine.cwd ? path.basename(lastLine.cwd) : null;
626
+ const validCwdBase = cwdBase && isValidProjectSlug(cwdBase) ? cwdBase : null;
627
+ const liveSlug = guessSlugFromWmLines(wmLines) ?? validCwdBase ?? "auto";
628
+ const liveEntry = {
629
+ ago: formatAgo(new Date(newest.mtimeMs).toISOString()),
630
+ slug: liveSlug,
631
+ title: truncateUtf8Bytes(`🔴 live — ${lastLine.prompt}`, SECTION_CHAR_LIMITS.continuity_title),
632
+ // Fable option 2 (label-not-scope, 2026-08-30) — same labeling as
633
+ // the ledger-sourced entries above; the "live" line is prepended
634
+ // to the SAME `continuity` array and must carry the same label.
635
+ is_current_project: isCurrentProjectContinuityEntry({ slug: liveSlug }, slug),
636
+ };
637
+ continuity = continuity ? [liveEntry, ...continuity] : [liveEntry];
638
+ }
602
639
  }
603
640
  }
604
- }
605
- catch {
606
- // never break orientation over a best-effort live signal
607
- }
641
+ catch {
642
+ // never break orientation over a best-effort live signal
643
+ }
608
644
  // 5. Recent journal briefs — today + yesterday only.
609
645
  //
610
646
  // Identity-trust (W4, 2026-08-30, wave/pipe-w4-session): both this block
@@ -650,7 +686,9 @@ export async function sessionStart(input) {
650
686
  // capture/log files (`*-log.md`, `*--capture--*`) that isJournalFile
651
687
  // excludes — filtering here reconstructs the identical candidate set the
652
688
  // old `fs.readdirSync(dir).filter(isJournalFile)` scan produced.
653
- const allJournalCandidates = readTierCandidates("journal", slug).filter((c) => isJournalFile(c.file));
689
+ const allJournalCandidates = full
690
+ ? readTierCandidates("journal", slug).filter((c) => isJournalFile(c.file))
691
+ : []; // Cards v2: no journal scan in cards mode (recent briefs and resume stay empty)
654
692
  // Reconstruct the EXACT pre-migration traversal order for THIS block: dirs
655
693
  // in journalDirs() order (primary, then legacy), WITHIN each dir sorted by
656
694
  // filename DESCENDING — the old `.sort().reverse()` per-dir behavior.
@@ -698,7 +736,7 @@ export async function sessionStart(input) {
698
736
  // 6. Watch for — predictive warnings from past corrections.
699
737
  // A/B OFF arm: suppressed entirely (correction-derived; ruling 2026-07-03).
700
738
  const watch_for = [];
701
- if (abArm !== "off") {
739
+ if (full && abArm !== "off") {
702
740
  const alignLog = readAlignmentLog(slug);
703
741
  watch_for.push(...extractWatchPatterns(alignLog, 2));
704
742
  // 8b. Decision calibration warnings
@@ -772,14 +810,15 @@ export async function sessionStart(input) {
772
810
  if (c.last_retrieved && new Date(c.last_retrieved).toLocaleDateString("sv") === todayStr)
773
811
  continue; // already counted today
774
812
  try {
775
- await recordOutcome({
776
- correction_id: c.id,
777
- project: slug,
778
- kind: "retrieved",
779
- at: nowISO,
780
- evidence: "surfaced at session_start",
781
- session_id: sessionId,
782
- });
813
+ // Ranking input (retrieved_count, last_retrieved, the alignment KPI): queued inside a read.
814
+ await bookkeep({ key: `retrieved:${slug}:${c.id}`, apply: () => recordOutcome({
815
+ correction_id: c.id,
816
+ project: slug,
817
+ kind: "retrieved",
818
+ at: nowISO,
819
+ evidence: "surfaced at session_start",
820
+ session_id: sessionId,
821
+ }) });
783
822
  }
784
823
  catch {
785
824
  // Outcome tracking must NEVER break orientation — swallow all errors
@@ -804,7 +843,7 @@ export async function sessionStart(input) {
804
843
  if (abArm !== "off") {
805
844
  try {
806
845
  const staged = await listPendingCorrections(slug);
807
- if (staged.length > 0) {
846
+ if (staged.length > 0) { // Cards v2: surfaced in both modes — session_start is the only place an agent learns that staged items await check() before the TTL expires them
808
847
  pendingCorrections = { count: staged.length, ids: staged.slice(0, 3).map((p) => p.id) };
809
848
  }
810
849
  }
@@ -866,7 +905,7 @@ export async function sessionStart(input) {
866
905
  // 8c. Recent captures — journal_capture writes that pre-date any session_end.
867
906
  // These live in `*-log.md` / `--capture--` files the orientation path skips,
868
907
  // so without this an agent that captured 4 things sees "No memory found".
869
- const recentCaptures = readRecentCaptures(slug, 5);
908
+ const recentCaptures = full ? readRecentCaptures(slug, 5) : []; // Cards v2: full mode only
870
909
  // 9. Empty state detection — guide first-time agents on THIS project.
871
910
  // The filesystem is the single source of truth: ANY committed store
872
911
  // (resume/journal/corrections) OR uncommitted store (captures) OR real
@@ -881,22 +920,20 @@ export async function sessionStart(input) {
881
920
  // public helper) tells a real room from scaffold without touching palace
882
921
  // internals, so "non-empty" is precise rather than `active_rooms.length > 0`.
883
922
  const hasPalaceContent = allRooms.some((r) => countRoomEntries(slug, r.slug) > 0);
884
- const hasCaptures = recentCaptures.length > 0 || hasCaptureLogs(slug);
923
+ const hasCaptures = full && (recentCaptures.length > 0 || hasCaptureLogs(slug));
885
924
  // A/B: use correctionsSlim (pre-suppression), NOT the arm-gated `corrections`,
886
925
  // so empty-state detection is arm-independent — an OFF-arm session on a
887
926
  // corrections-only project must not flash the "No memory found" banner.
888
- const isEmpty = !resume &&
889
- correctionsSlim.length === 0 &&
890
- !todayBrief && !yesterdayBrief &&
891
- olderCount === 0 &&
892
- !hasCaptures &&
893
- !hasPalaceContent;
927
+ // Cards v1: a state card with any field filled is project memory; a frontmatter-only file is not.
928
+ const hasStateContent = Boolean(stateCard && stateCardHasContent(stateCard));
929
+ const isEmpty = full
930
+ ? !resume && correctionsSlim.length === 0 && !todayBrief && !yesterdayBrief && olderCount === 0 && !hasCaptures && !hasPalaceContent && !hasStateContent
931
+ : !ownerCard && correctionsSlim.length === 0 && !hasStateContent && readBehaviorPolicies(slug).rules.length === 0; // Cards v2: empty when it would render no card and no rule (P0 or behaviour policy)
894
932
  // Trigger backfill if Supabase is configured (non-blocking)
895
933
  const sbConfig = readSupabaseConfig();
896
934
  if (sbConfig) {
897
- setImmediate(() => {
898
- void autoBackfill(slug);
899
- });
935
+ // Owner opt-in sync to the owner's own Supabase; never on the hosted server. Queued so a read pushes nothing.
936
+ void bookkeep({ key: `backfill:${slug}`, apply: () => { setImmediate(() => { void autoBackfill(slug); }); } });
900
937
  }
901
938
  // Behavior policies — always-loaded high-salience rules. Bump hit counter
902
939
  // FIRST so the returned objects reflect post-bump state (the on-disk store
@@ -904,8 +941,10 @@ export async function sessionStart(input) {
904
941
  // C2: gated on isFirstCallThisSession — the hits counter has no per-day
905
942
  // guard of its own, so without this a repeat session_start call in the
906
943
  // same session would double (or triple, ...) count every rule's hits.
944
+ // Cards v2: behaviour policies are always-follow rules the owner registered, so they render in BOTH modes (right
945
+ // before the HARD RULES, as before) and the load is counted in both — nothing registered as a rule goes silent by default.
907
946
  if (isFirstCallThisSession && readBehaviorPolicies(slug).rules.length > 0)
908
- recordPolicyLoad(slug);
947
+ void bookkeep({ key: `policy-load:${slug}`, apply: () => recordPolicyLoad(slug) });
909
948
  const behaviorRules = readBehaviorPolicies(slug).rules;
910
949
  // North-star alignment metric — correction precision (heeded/retrieved).
911
950
  // Wrapped in try/catch so a corrupt or unreadable corrections dir never
@@ -913,7 +952,7 @@ export async function sessionStart(input) {
913
952
  // (retrieved === 0) — no fake claims.
914
953
  // A/B OFF arm: suppressed (correction-derived KPI; ruling 2026-07-03).
915
954
  let alignment = null;
916
- if (abArm !== "off") {
955
+ if (full && abArm !== "off") {
917
956
  try {
918
957
  // Deliberately NOT fed the `allCorrectionsOnce` snapshot: the P0-B loop
919
958
  // above WROTE retrieved_count/last_retrieved to disk after that snapshot
@@ -954,7 +993,7 @@ export async function sessionStart(input) {
954
993
  storeDoctorLine = null;
955
994
  }
956
995
  // Pipeline narrative spine summary — null if no pipeline files exist for project
957
- const pipelineMilestones = listMilestones(slug);
996
+ const pipelineMilestones = full ? listMilestones(slug) : []; // Cards v2: full mode only
958
997
  let pipeline = null;
959
998
  if (pipelineMilestones.length > 0) {
960
999
  const active = pipelineMilestones.find((m) => m.meta.status === "active") ?? null;
@@ -983,7 +1022,7 @@ export async function sessionStart(input) {
983
1022
  let blindSpots = [];
984
1023
  // predicted_risks is optional — undefined when empty (absent from JSON, saves ~20 bytes/project).
985
1024
  let predictedRisks;
986
- if (abArm !== "off") {
1025
+ if (full && abArm !== "off") {
987
1026
  try {
988
1027
  const profile = readBlindSpots(slug);
989
1028
  if (profile) {
@@ -1027,7 +1066,7 @@ export async function sessionStart(input) {
1027
1066
  // derived). With corrections=[] and blindSpots=[] it would self-suppress
1028
1067
  // anyway, but the explicit gate keeps the contract robust to future edits.
1029
1068
  let mirrorAvailable;
1030
- if (abArm !== "off") {
1069
+ if (full && abArm !== "off") {
1031
1070
  try {
1032
1071
  const hasProfile = blindSpots.length > 0;
1033
1072
  // corrections is now SlimCorrection[] (no `active` field) — count length directly.
@@ -1046,19 +1085,23 @@ export async function sessionStart(input) {
1046
1085
  // Loop 4 — real-time recognition snapshot. Pure-local assembler over the
1047
1086
  // already-resolved slug (no re-detection ⇒ no git shell-out on the hot path).
1048
1087
  // Best-effort: a degraded recognition must never break orientation.
1049
- let recognition;
1050
- try {
1051
- // PERF: reuse the corrections array read once above instead of letting
1052
- // buildRecognition -> readCapabilities re-scan corrections/*.json.
1053
- recognition = buildRecognition(slug, { preloadedCorrections: activeCorrectionsOnce });
1054
- }
1055
- catch {
1056
- recognition = {
1057
- who: { name: "unknown", role: null, owner: null, unknown: true },
1058
- can_do: { skills: [], permissions: [] },
1059
- project: { slug, last_journal_date: null, status: "empty", trajectory: null, rooms: [] },
1060
- person: { tendencies: [], caveat: "" },
1061
- };
1088
+ const degradedRecognition = () => ({
1089
+ who: { name: "unknown", role: null, owner: null, unknown: true },
1090
+ can_do: { skills: [], permissions: [] },
1091
+ project: { slug, last_journal_date: null, status: "empty", trajectory: null, rooms: [] },
1092
+ person: { tendencies: [], caveat: "" },
1093
+ });
1094
+ // Cards v2: cards mode skips the assembler (skills/capabilities scans) and returns the degraded shape.
1095
+ let recognition = degradedRecognition();
1096
+ if (full) {
1097
+ try {
1098
+ // PERF: reuse the corrections array read once above instead of letting
1099
+ // buildRecognition -> readCapabilities re-scan corrections/*.json.
1100
+ recognition = buildRecognition(slug, { preloadedCorrections: activeCorrectionsOnce });
1101
+ }
1102
+ catch {
1103
+ recognition = degradedRecognition();
1104
+ }
1062
1105
  }
1063
1106
  // A/B OFF arm: recognition.person tendencies derive from the blind-spots
1064
1107
  // profile (corrections lineage) — strip the person block regardless of
@@ -1149,6 +1192,9 @@ export async function sessionStart(input) {
1149
1192
  }));
1150
1193
  const result = {
1151
1194
  project: slug,
1195
+ mode,
1196
+ ...(ownerCard ? { owner: ownerCard } : {}),
1197
+ ...(stateCard ? { state: stateCard } : {}),
1152
1198
  identity,
1153
1199
  insights: insightsBudgeted,
1154
1200
  active_rooms: roomsBudgeted,
@@ -1178,7 +1224,12 @@ export async function sessionStart(input) {
1178
1224
  mirror_available: mirrorAvailable,
1179
1225
  // fix5: absent-when-zero — see the field's doc comment above.
1180
1226
  unclaimed_cards: unclaimedCount > 0 ? unclaimedCount : undefined,
1181
- empty_state: isEmpty ? "No memory found for this project. Try: bootstrap_scan() to import existing projects, or start working and use remember() to save decisions." : undefined,
1227
+ // Hosted: a new user has no CLI, so the text names only tools the agent can call here.
1228
+ empty_state: !isEmpty ? undefined : isTenantScoped()
1229
+ ? `No memory yet for ${slug}: this is a new AgentRecall memory. Ask the user which rules every agent should follow and save each with remember; session_end before you stop writes the first state card.`
1230
+ : full
1231
+ ? "No memory found for this project. Try `ar bootstrap` in a terminal to import existing projects, or start working and use remember() to save decisions."
1232
+ : `No cards yet for ${slug} — session_end writes the state card; ar identity init creates the owner card.`,
1182
1233
  // C4: ab_arm is included only when the experiment is running (saves bytes otherwise).
1183
1234
  ab_arm: abArm ?? undefined,
1184
1235
  };
@@ -1192,7 +1243,10 @@ export async function sessionStart(input) {
1192
1243
  // C2 — lifecycle telemetry: counters only, never transcript content.
1193
1244
  // dup=true means this call's write-phase was idempotent-suppressed (a
1194
1245
  // repeat session_start for this process's session + project).
1195
- recordLifecycleEvent("session_start", sessionId, slug, !isFirstCallThisSession);
1246
+ // Pure telemetry, never read back by behaviour; queued so the call itself writes nothing (stamped now, not at flush).
1247
+ const calledAt = new Date().toISOString();
1248
+ const wasDup = !isFirstCallThisSession;
1249
+ void bookkeep({ apply: () => recordLifecycleEvent("session_start", sessionId, slug, wasDup, calledAt) });
1196
1250
  return result;
1197
1251
  }
1198
1252
  async function autoBackfill(project) {