@remnic/core 10.0.110 → 10.0.111

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 (176) hide show
  1. package/dist/access-admin-ops-surface.js +51 -50
  2. package/dist/access-cli.js +51 -50
  3. package/dist/access-cli.js.map +1 -1
  4. package/dist/access-extraction-force-flush.js +51 -50
  5. package/dist/access-http-briefing.js +51 -50
  6. package/dist/access-http-query.js +51 -50
  7. package/dist/access-http.js +51 -50
  8. package/dist/access-identity-continuity-surface.js +51 -50
  9. package/dist/access-lcm-surface.js +51 -50
  10. package/dist/access-mcp.js +51 -50
  11. package/dist/access-observe-write-surface.js +51 -50
  12. package/dist/access-operations-batch.js +51 -50
  13. package/dist/access-operations.js +51 -50
  14. package/dist/access-recall-concurrency.js +51 -50
  15. package/dist/access-recall-response.js +51 -50
  16. package/dist/access-recall-surface.js +51 -50
  17. package/dist/access-service.js +51 -50
  18. package/dist/active-recall.js +9 -9
  19. package/dist/adapters/index.js +4 -4
  20. package/dist/adapters/registry.js +2 -2
  21. package/dist/briefing.js +10 -10
  22. package/dist/causal-consolidation.js +11 -11
  23. package/dist/{chunk-7HNQR5MV.js → chunk-25JBIXAV.js} +3 -3
  24. package/dist/{chunk-7SW6EBEF.js → chunk-27YNNLRB.js} +2 -2
  25. package/dist/{chunk-E55J2NFL.js → chunk-477SVZUZ.js} +2 -2
  26. package/dist/{chunk-7ZEF43SR.js → chunk-6DUBULUV.js} +3 -3
  27. package/dist/{chunk-63OWJXGW.js → chunk-6YXIL26Y.js} +2 -2
  28. package/dist/{chunk-GT2TH7FZ.js → chunk-AAF7RX22.js} +3 -3
  29. package/dist/{chunk-B3LGXOM5.js → chunk-AJCXPMDA.js} +2 -2
  30. package/dist/{chunk-5VWN3FJS.js → chunk-BFRNDOHO.js} +2 -2
  31. package/dist/{chunk-K32VAS5B.js → chunk-BGM7O5TD.js} +2 -2
  32. package/dist/{chunk-FQACH7MC.js → chunk-BZAI3ETM.js} +2 -2
  33. package/dist/{chunk-UOIVXBNS.js → chunk-E5DYZM56.js} +2 -2
  34. package/dist/{chunk-WQ4XKIOX.js → chunk-F32RH72R.js} +45 -37
  35. package/dist/chunk-F32RH72R.js.map +1 -0
  36. package/dist/{chunk-WCKLRFGF.js → chunk-F6GNH5UY.js} +2 -2
  37. package/dist/{chunk-DLZGSZVC.js → chunk-FYQUUIPI.js} +4 -4
  38. package/dist/{chunk-XTN54NML.js → chunk-G3T6YMBO.js} +4 -4
  39. package/dist/{chunk-AY535ZIM.js → chunk-G7QANNRD.js} +2 -2
  40. package/dist/chunk-GE5J2T67.js +100 -0
  41. package/dist/chunk-GE5J2T67.js.map +1 -0
  42. package/dist/{chunk-H4XPEXWA.js → chunk-GG3QMQEG.js} +2 -2
  43. package/dist/{chunk-FVMEZ57K.js → chunk-HWMIXG3J.js} +10 -10
  44. package/dist/{chunk-LYR57GEF.js → chunk-I5PCMNN5.js} +3 -3
  45. package/dist/{chunk-QIGEWFXE.js → chunk-INXS64LQ.js} +2 -2
  46. package/dist/{chunk-BP7LNNWG.js → chunk-IOTMEQUC.js} +2 -2
  47. package/dist/{chunk-S2HLHAZ4.js → chunk-L76BQSWB.js} +10 -2
  48. package/dist/chunk-L76BQSWB.js.map +1 -0
  49. package/dist/{chunk-7QIRIF3Z.js → chunk-LFPGCYXE.js} +2 -2
  50. package/dist/{chunk-YD4D4EVO.js → chunk-MPIMRX3I.js} +2 -2
  51. package/dist/{chunk-PFUXPTBT.js → chunk-P3AQ2YSX.js} +4 -4
  52. package/dist/{chunk-ZG4GNPRE.js → chunk-PBE7NFB5.js} +5 -5
  53. package/dist/{chunk-FV2B6XE6.js → chunk-R3LYKUZH.js} +2 -2
  54. package/dist/{chunk-OIOKDTZU.js → chunk-SZXDGB32.js} +17 -6
  55. package/dist/chunk-SZXDGB32.js.map +1 -0
  56. package/dist/{chunk-BUOP3DOK.js → chunk-TR4HFZBD.js} +2 -2
  57. package/dist/{chunk-JODSN3V5.js → chunk-UY3JSQ7H.js} +2 -2
  58. package/dist/{chunk-4TYIHHPW.js → chunk-WDAIXMEU.js} +73 -60
  59. package/dist/{chunk-4TYIHHPW.js.map → chunk-WDAIXMEU.js.map} +1 -1
  60. package/dist/{chunk-VLUWWPKO.js → chunk-X3HLHS5E.js} +7 -7
  61. package/dist/{chunk-AOAREXFV.js → chunk-XSFDRM2P.js} +2 -2
  62. package/dist/{chunk-DOJBV6WR.js → chunk-YK6SFDP2.js} +4 -4
  63. package/dist/{chunk-OLJYBMFW.js → chunk-YQ7H7P4Y.js} +7 -7
  64. package/dist/{chunk-IOGYSADY.js → chunk-YTNLLRHQ.js} +2 -2
  65. package/dist/{chunk-EDVVW655.js → chunk-Z4NOA733.js} +2 -2
  66. package/dist/{chunk-AZYUG2HW.js → chunk-Z64ANMII.js} +2 -2
  67. package/dist/{chunk-OEVJH66T.js → chunk-ZAMVB4JK.js} +3 -3
  68. package/dist/cli.js +51 -50
  69. package/dist/coding/export-okf-codegraph.js +9 -9
  70. package/dist/compounding/engine.js +11 -11
  71. package/dist/config.js +9 -9
  72. package/dist/connectors/codex-materialize-runner.js +10 -10
  73. package/dist/connectors/index.js +10 -10
  74. package/dist/convergence-refresh.js +12 -12
  75. package/dist/corpus-watermark.js +12 -12
  76. package/dist/entity-retrieval.js +10 -10
  77. package/dist/explicit-capture.js +51 -50
  78. package/dist/extraction.js +10 -10
  79. package/dist/harmonic-retrieval.js +10 -10
  80. package/dist/index.js +72 -71
  81. package/dist/lcm/engine.js +2 -2
  82. package/dist/lcm/index.js +5 -5
  83. package/dist/location/index.js +11 -11
  84. package/dist/maintenance/memory-governance.js +10 -10
  85. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
  86. package/dist/maintenance/rebuild-memory-projection-runner.js +12 -12
  87. package/dist/maintenance/rebuild-memory-projection.js +11 -11
  88. package/dist/memory-snapshot.d.ts +7 -1
  89. package/dist/memory-snapshot.d.ts.map +1 -1
  90. package/dist/memory-snapshot.js +5 -3
  91. package/dist/namespaces/migrate.js +11 -11
  92. package/dist/namespaces/search.js +7 -7
  93. package/dist/namespaces/storage.js +10 -10
  94. package/dist/operator-doctor-corpus.js +13 -13
  95. package/dist/operator-toolkit.js +16 -16
  96. package/dist/orchestration/backlog-scheduler.js +52 -51
  97. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  98. package/dist/orchestration/buffer-drain-runner.js +52 -51
  99. package/dist/orchestration/maintenance.js +18 -18
  100. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  101. package/dist/orchestration/workspace-ops.d.ts.map +1 -1
  102. package/dist/orchestrator.js +51 -50
  103. package/dist/recall-navigation.js +51 -50
  104. package/dist/resume-bundles.js +12 -11
  105. package/dist/search/factory.js +6 -6
  106. package/dist/search/index.js +11 -11
  107. package/dist/search/lancedb-backend.js +2 -2
  108. package/dist/search/meilisearch-backend.js +2 -2
  109. package/dist/search/orama-backend.js +2 -2
  110. package/dist/semantic-consolidation.js +11 -11
  111. package/dist/semantic-rule-promotion.js +10 -10
  112. package/dist/semantic-rule-verifier.js +10 -10
  113. package/dist/source-agent-qualifier.js +10 -10
  114. package/dist/standup/build.js +10 -10
  115. package/dist/storage.d.ts +3 -0
  116. package/dist/storage.d.ts.map +1 -1
  117. package/dist/storage.js +9 -9
  118. package/dist/transcript-recent.d.ts +22 -0
  119. package/dist/transcript-recent.d.ts.map +1 -0
  120. package/dist/transcript-recent.js +15 -0
  121. package/dist/transcript-recent.js.map +1 -0
  122. package/dist/transcript.d.ts +11 -3
  123. package/dist/transcript.d.ts.map +1 -1
  124. package/dist/transcript.js +2 -1
  125. package/dist/transfer/export-okf.js +10 -10
  126. package/dist/verified-recall.js +10 -10
  127. package/dist/who-knows-cli.js +11 -11
  128. package/dist/who-knows.js +10 -10
  129. package/package.json +2 -2
  130. package/src/memory-snapshot.ts +14 -1
  131. package/src/orchestration/recall-internal.ts +1 -4
  132. package/src/orchestration/workspace-ops.test.ts +113 -0
  133. package/src/orchestration/workspace-ops.ts +38 -12
  134. package/src/storage-contract/lazy-memory-snapshot.test.ts +194 -0
  135. package/src/storage.ts +15 -4
  136. package/src/transcript-recent-tail.test.ts +355 -0
  137. package/src/transcript-recent.ts +129 -0
  138. package/src/transcript.ts +47 -47
  139. package/dist/chunk-OIOKDTZU.js.map +0 -1
  140. package/dist/chunk-S2HLHAZ4.js.map +0 -1
  141. package/dist/chunk-WQ4XKIOX.js.map +0 -1
  142. /package/dist/{chunk-7HNQR5MV.js.map → chunk-25JBIXAV.js.map} +0 -0
  143. /package/dist/{chunk-7SW6EBEF.js.map → chunk-27YNNLRB.js.map} +0 -0
  144. /package/dist/{chunk-E55J2NFL.js.map → chunk-477SVZUZ.js.map} +0 -0
  145. /package/dist/{chunk-7ZEF43SR.js.map → chunk-6DUBULUV.js.map} +0 -0
  146. /package/dist/{chunk-63OWJXGW.js.map → chunk-6YXIL26Y.js.map} +0 -0
  147. /package/dist/{chunk-GT2TH7FZ.js.map → chunk-AAF7RX22.js.map} +0 -0
  148. /package/dist/{chunk-B3LGXOM5.js.map → chunk-AJCXPMDA.js.map} +0 -0
  149. /package/dist/{chunk-5VWN3FJS.js.map → chunk-BFRNDOHO.js.map} +0 -0
  150. /package/dist/{chunk-K32VAS5B.js.map → chunk-BGM7O5TD.js.map} +0 -0
  151. /package/dist/{chunk-FQACH7MC.js.map → chunk-BZAI3ETM.js.map} +0 -0
  152. /package/dist/{chunk-UOIVXBNS.js.map → chunk-E5DYZM56.js.map} +0 -0
  153. /package/dist/{chunk-WCKLRFGF.js.map → chunk-F6GNH5UY.js.map} +0 -0
  154. /package/dist/{chunk-DLZGSZVC.js.map → chunk-FYQUUIPI.js.map} +0 -0
  155. /package/dist/{chunk-XTN54NML.js.map → chunk-G3T6YMBO.js.map} +0 -0
  156. /package/dist/{chunk-AY535ZIM.js.map → chunk-G7QANNRD.js.map} +0 -0
  157. /package/dist/{chunk-H4XPEXWA.js.map → chunk-GG3QMQEG.js.map} +0 -0
  158. /package/dist/{chunk-FVMEZ57K.js.map → chunk-HWMIXG3J.js.map} +0 -0
  159. /package/dist/{chunk-LYR57GEF.js.map → chunk-I5PCMNN5.js.map} +0 -0
  160. /package/dist/{chunk-QIGEWFXE.js.map → chunk-INXS64LQ.js.map} +0 -0
  161. /package/dist/{chunk-BP7LNNWG.js.map → chunk-IOTMEQUC.js.map} +0 -0
  162. /package/dist/{chunk-7QIRIF3Z.js.map → chunk-LFPGCYXE.js.map} +0 -0
  163. /package/dist/{chunk-YD4D4EVO.js.map → chunk-MPIMRX3I.js.map} +0 -0
  164. /package/dist/{chunk-PFUXPTBT.js.map → chunk-P3AQ2YSX.js.map} +0 -0
  165. /package/dist/{chunk-ZG4GNPRE.js.map → chunk-PBE7NFB5.js.map} +0 -0
  166. /package/dist/{chunk-FV2B6XE6.js.map → chunk-R3LYKUZH.js.map} +0 -0
  167. /package/dist/{chunk-BUOP3DOK.js.map → chunk-TR4HFZBD.js.map} +0 -0
  168. /package/dist/{chunk-JODSN3V5.js.map → chunk-UY3JSQ7H.js.map} +0 -0
  169. /package/dist/{chunk-VLUWWPKO.js.map → chunk-X3HLHS5E.js.map} +0 -0
  170. /package/dist/{chunk-AOAREXFV.js.map → chunk-XSFDRM2P.js.map} +0 -0
  171. /package/dist/{chunk-DOJBV6WR.js.map → chunk-YK6SFDP2.js.map} +0 -0
  172. /package/dist/{chunk-OLJYBMFW.js.map → chunk-YQ7H7P4Y.js.map} +0 -0
  173. /package/dist/{chunk-IOGYSADY.js.map → chunk-YTNLLRHQ.js.map} +0 -0
  174. /package/dist/{chunk-EDVVW655.js.map → chunk-Z4NOA733.js.map} +0 -0
  175. /package/dist/{chunk-AZYUG2HW.js.map → chunk-Z64ANMII.js.map} +0 -0
  176. /package/dist/{chunk-OEVJH66T.js.map → chunk-ZAMVB4JK.js.map} +0 -0
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Unscoped `readRecent(hours)` (MCP recalls carry no sessionKey) parsed every
3
+ * line of every daily file in the window plus one day of margin: ~614 MB on the
4
+ * production store, ~7 s of main-thread work per recall (COS-666b). Appended
5
+ * files hold entries in write order, so the recent window is a file's tail and a
6
+ * file not modified since the window began holds nothing in it. These tests pin
7
+ * that the result is unchanged and that the cost is bounded to the window.
8
+ */
9
+
10
+ import assert from "node:assert/strict";
11
+ import { chmod, mkdir, mkdtemp, realpath, rm, symlink, utimes, writeFile } from "node:fs/promises";
12
+ import fsp from "node:fs/promises";
13
+ import { syncBuiltinESMExports } from "node:module";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import test, { mock } from "node:test";
17
+
18
+ import { parseConfig } from "./config.js";
19
+ import { TranscriptManager } from "./transcript.js";
20
+ import type { TranscriptEntry } from "./types.js";
21
+
22
+ const MIN = 60_000;
23
+ const HOUR = 60 * MIN;
24
+ const PAD = "x".repeat(2000);
25
+
26
+ function entry(turnId: string, timestampMs: number, content = `content-${turnId}`): TranscriptEntry {
27
+ return { sessionKey: "agent:a:main", turnId, role: "user", content, timestamp: new Date(timestampMs).toISOString() };
28
+ }
29
+
30
+ async function writeFileOf(file: string, entries: TranscriptEntry[], mtimeMs?: number): Promise<void> {
31
+ await mkdir(path.dirname(file), { recursive: true });
32
+ await writeFile(file, entries.map((e) => JSON.stringify(e)).join("\n") + "\n", "utf-8");
33
+ if (mtimeMs !== undefined) await utimes(file, new Date(mtimeMs), new Date(mtimeMs));
34
+ }
35
+
36
+ async function withStore(run: (ctx: { root: string; manager: TranscriptManager; now: number }) => Promise<void>): Promise<void> {
37
+ const memoryDir = await realpath(await mkdtemp(path.join(os.tmpdir(), "remnic-tx-tail-")));
38
+ try {
39
+ const config = parseConfig({ memoryDir, transcriptSkipChannelTypes: [] });
40
+ await run({ root: path.join(memoryDir, "transcripts"), manager: new TranscriptManager(config), now: Date.now() });
41
+ } finally {
42
+ await rm(memoryDir, { recursive: true, force: true });
43
+ }
44
+ }
45
+
46
+ const today = (now: number): string => new Date(now).toISOString().slice(0, 10);
47
+
48
+ async function countParses<T>(fn: () => Promise<T>): Promise<{ result: T; parses: number }> {
49
+ const spy = mock.method(JSON, "parse");
50
+ try {
51
+ const result = await fn();
52
+ return { result, parses: spy.mock.callCount() };
53
+ } finally {
54
+ spy.mock.restore();
55
+ }
56
+ }
57
+
58
+ test("a file not modified since before the window (less an hour of skew) is not read", async () => {
59
+ await withStore(async ({ root, manager, now }) => {
60
+ const hours = 6;
61
+ const start = now - hours * HOUR;
62
+ const day = today(now);
63
+ // Violates the append invariant on purpose (in-window entry, stale mtime) to pin the bound.
64
+ await writeFileOf(path.join(root, "session/stale", `${day}.jsonl`), [entry("stale", now - 2 * HOUR)], start - 2 * HOUR);
65
+ await writeFileOf(path.join(root, "session/skew", `${day}.jsonl`), [entry("skew", now - 2 * HOUR)], start - 30 * MIN);
66
+ await writeFileOf(path.join(root, "session/live", `${day}.jsonl`), [entry("live", now - 1 * HOUR)], now);
67
+ const ids = (await manager.readRecent(hours)).map((e) => e.turnId).sort();
68
+ assert.deepEqual(ids, ["live", "skew"]);
69
+ const full = (await manager.readRange(new Date(start).toISOString(), new Date(now + 1).toISOString(), undefined)).map((e) => e.turnId);
70
+ assert.ok(full.includes("stale"), "an explicit range still reads every file");
71
+ });
72
+ });
73
+
74
+ test("a large file is read from its tail: same entries as the full scan, a fraction of the parses", async () => {
75
+ await withStore(async ({ root, manager, now }) => {
76
+ const hours = 6;
77
+ const start = now - hours * HOUR;
78
+ // 3000 lines x ~2 KB = ~6 MB across several 1 MiB tail chunks; the last 40 are in the window.
79
+ const lines: TranscriptEntry[] = [];
80
+ for (let i = 0; i < 3000; i++) lines.push(entry(`t${i}`, i < 2960 ? start - 20 * HOUR + i * (19 * HOUR / 2960) : start + 10 * MIN + (i - 2960) * 5 * MIN, PAD));
81
+ await writeFileOf(path.join(root, "session/big", `${today(now)}.jsonl`), lines, now);
82
+ const startIso = new Date(start).toISOString();
83
+ const endIso = new Date(now + 1).toISOString();
84
+ const full = await manager.readRange(startIso, endIso, undefined);
85
+ const { result: recent, parses } = await countParses(() => manager.readRecent(hours));
86
+ assert.deepEqual(recent, full);
87
+ assert.ok(recent.length > 0 && recent.length < 100, `window should hold a handful of turns, got ${recent.length}`);
88
+ assert.ok(parses < 1000, `tail read must not parse the whole file, parsed ${parses}`);
89
+ });
90
+ });
91
+
92
+ test("tail read tolerates out-of-order timestamps within the skew margin", async () => {
93
+ await withStore(async ({ root, manager, now }) => {
94
+ const hours = 6;
95
+ const start = now - hours * HOUR;
96
+ const lines: TranscriptEntry[] = [];
97
+ for (let i = 0; i < 2500; i++) lines.push(entry(`o${i}`, start - 10 * HOUR + i * (9 * HOUR / 2500), PAD));
98
+ // Out-of-order tail: an in-window entry written before an older out-of-window one.
99
+ lines.push(entry("late-in", start + 5 * MIN, PAD), entry("early-out", start - 20 * MIN, PAD), entry("tail", now - 10 * MIN, PAD));
100
+ await writeFileOf(path.join(root, "session/jitter", `${today(now)}.jsonl`), lines, now);
101
+ const full = await manager.readRange(new Date(start).toISOString(), new Date(now + 1).toISOString(), undefined);
102
+ assert.deepEqual(await manager.readRecent(hours), full);
103
+ assert.ok(full.some((e) => e.turnId === "late-in"));
104
+ });
105
+ });
106
+
107
+ test("a file smaller than one chunk, with a line spanning it, and malformed lines still round-trip", async () => {
108
+ await withStore(async ({ root, manager, now }) => {
109
+ const file = path.join(root, "session/small", `${today(now)}.jsonl`);
110
+ await mkdir(path.dirname(file), { recursive: true });
111
+ const a = JSON.stringify(entry("a", now - HOUR));
112
+ const huge = JSON.stringify(entry("huge", now - 30 * MIN, "é".repeat(700_000)));
113
+ await writeFile(file, `${a}\nnot json\n${huge}\n${JSON.stringify(entry("z", now - 5 * MIN))}\n`, "utf-8");
114
+ const ids = (await manager.readRecent(3)).map((e) => e.turnId);
115
+ assert.deepEqual(ids, ["a", "huge", "z"]);
116
+ });
117
+ });
118
+
119
+ async function seedManySessions(root: string, now: number): Promise<void> {
120
+ const day = today(now);
121
+ // 40 sessions x 600 lines x ~2 KB = ~48 MB. Each file's last entry is stamped at its mtime (the append invariant).
122
+ for (let s = 0; s < 40; s++) {
123
+ const mtime = now - (40 - s) * 10 * MIN;
124
+ const lines: TranscriptEntry[] = [];
125
+ for (let i = 0; i < 600; i++) {
126
+ lines.push({ ...entry(`s${s}-${i}`, mtime - 8 * HOUR + (i + 1) * (8 * HOUR / 600) - s * 7, PAD), sessionKey: `agent:${s}:main` });
127
+ }
128
+ await writeFileOf(path.join(root, `session/s${s}`, `${day}.jsonl`), lines, mtime);
129
+ }
130
+ }
131
+
132
+ test("readRecent(hours, undefined, N) equals the last N of the full window, reading a fraction of it", async () => {
133
+ await withStore(async ({ root, manager, now }) => {
134
+ await seedManySessions(root, now);
135
+ const hours = 12;
136
+ const full = await manager.readRange(new Date(now - hours * HOUR).toISOString(), new Date(now + 1).toISOString(), undefined);
137
+ for (const n of [1, 50, 700]) {
138
+ const { result, parses } = await countParses(() => manager.readRecent(hours, undefined, n));
139
+ assert.deepEqual(result.map((e) => e.turnId), full.slice(-n).map((e) => e.turnId), `last ${n}`);
140
+ if (n <= 50) assert.ok(parses < 700, `last ${n} must not parse the window (${full.length} entries), parsed ${parses}`);
141
+ }
142
+ });
143
+ });
144
+
145
+ test("readRecent(hours, undefined, N) with fewer than N entries returns them all", async () => {
146
+ await withStore(async ({ root, manager, now }) => {
147
+ await writeFileOf(path.join(root, "session/one", `${today(now)}.jsonl`), [entry("a", now - 3 * HOUR), entry("b", now - HOUR)], now);
148
+ assert.deepEqual((await manager.readRecent(12, undefined, 50)).map((e) => e.turnId), ["a", "b"]);
149
+ });
150
+ });
151
+
152
+ test("bad lines among a file's newest do not shrink the newest-N result", async () => {
153
+ await withStore(async ({ root, manager, now }) => {
154
+ const file = path.join(root, "session/bad", `${today(now)}.jsonl`);
155
+ await mkdir(path.dirname(file), { recursive: true });
156
+ const lines: string[] = [];
157
+ for (let i = 0; i < 60; i++) lines.push(JSON.stringify(entry(`v${i}`, now - 5 * HOUR + i * MIN)));
158
+ lines.splice(58, 0, "not json");
159
+ lines.push(JSON.stringify({ sessionKey: "k", turnId: "no-ts", role: "user", content: "x" }));
160
+ lines.push(JSON.stringify(entry("future", now + 2 * HOUR)));
161
+ // A torn, unterminated final append.
162
+ await writeFile(file, `${lines.join("\n")}\n{"sessionKey":"agent:a:main","turnId":"torn","ti`, "utf-8");
163
+ for (const n of [1, 50]) {
164
+ const want = (await manager.readRecent(12)).slice(-n).map((e) => e.turnId);
165
+ const got = (await manager.readRecent(12, undefined, n)).map((e) => e.turnId);
166
+ assert.equal(got.length, n, `last ${n}`);
167
+ assert.deepEqual(got, want, `last ${n}`);
168
+ }
169
+ });
170
+ });
171
+
172
+ test("newest-N does not read a file modified too long ago to hold a newer entry", async () => {
173
+ await withStore(async ({ root, manager, now }) => {
174
+ const recent: TranscriptEntry[] = [];
175
+ for (let i = 0; i < 60; i++) recent.push(entry(`r${i}`, now - (61 - i) * MIN));
176
+ await writeFileOf(path.join(root, "session/live", `${today(now)}.jsonl`), recent, now);
177
+ // Violates the append invariant on purpose (newer than its own mtime) to pin the stop rule.
178
+ await writeFileOf(path.join(root, "session/stale", `${today(now)}.jsonl`), [entry("stale-newer", now - 30_000)], now - 5 * HOUR);
179
+ const ids = (await manager.readRecent(12, undefined, 50)).map((e) => e.turnId);
180
+ assert.equal(ids.length, 50);
181
+ assert.ok(!ids.includes("stale-newer"));
182
+ });
183
+ });
184
+
185
+ const ids = (entries: TranscriptEntry[]): string[] => entries.map((e) => e.turnId);
186
+
187
+ test("blank lines among a file's newest do not shrink the newest-N result", async () => {
188
+ await withStore(async ({ root, manager, now }) => {
189
+ // 200 x ~40 KB: each 256 KiB tail chunk holds only a few lines, so the stop rule runs often.
190
+ const lines: string[] = [];
191
+ for (let i = 0; i < 200; i++) {
192
+ lines.push(JSON.stringify(entry(`t${i}`, now - 10 * HOUR + i * 2 * MIN, "y".repeat(40_000))));
193
+ if (i >= 170 && i % 2 === 0) lines.push(""); // 15 blanks among the newest 30
194
+ }
195
+ const file = path.join(root, "session/blank", `${today(now)}.jsonl`);
196
+ await mkdir(path.dirname(file), { recursive: true });
197
+ await writeFile(file, `${lines.join("\n")}\n`, "utf-8");
198
+ const got = await manager.readRecent(12, undefined, 50);
199
+ assert.equal(got.length, 50);
200
+ assert.deepEqual(ids(got), ids(await manager.readRecent(12)).slice(-50));
201
+ });
202
+ });
203
+
204
+ test("a tail chunk holding exactly N lines is not mistaken for the whole window", async () => {
205
+ await withStore(async ({ root, manager, now }) => {
206
+ // Every line is 5300 bytes, so the final 256 KiB chunk holds exactly 50 newlines: the partial first
207
+ // line plus 49 complete lines. Stopping there (`>=` instead of `>`) would return 49.
208
+ const lineBytes = 5300;
209
+ const lines: string[] = [];
210
+ for (let i = 0; i < 100; i++) {
211
+ const id = `f${String(i).padStart(4, "0")}`;
212
+ const pad = lineBytes - 1 - JSON.stringify(entry(id, 0, "")).length;
213
+ lines.push(JSON.stringify(entry(id, now - 8 * HOUR + i * 2 * MIN, "p".repeat(pad))));
214
+ }
215
+ const file = path.join(root, "session/exact", `${today(now)}.jsonl`);
216
+ await mkdir(path.dirname(file), { recursive: true });
217
+ await writeFile(file, `${lines.join("\n")}\n`, "utf-8");
218
+ const got = await manager.readRecent(12, undefined, 50);
219
+ assert.equal(got.length, 50);
220
+ assert.deepEqual(ids(got), ids(await manager.readRecent(12)).slice(-50));
221
+ });
222
+ });
223
+
224
+ test("newest-N leaves out entries stamped before the window even when they sit in a file's tail", async () => {
225
+ await withStore(async ({ root, manager, now }) => {
226
+ const inWindow: TranscriptEntry[] = [];
227
+ for (let i = 0; i < 20; i++) inWindow.push(entry(`in${i}`, now - HOUR + i * MIN));
228
+ const old: TranscriptEntry[] = [];
229
+ for (let i = 0; i < 30; i++) old.push(entry(`old${i}`, now - 20 * HOUR + i * MIN));
230
+ await writeFileOf(path.join(root, "session/mixed", `${today(now)}.jsonl`), [...inWindow, ...old], now);
231
+ assert.deepEqual(ids(await manager.readRecent(6, undefined, 50)), ids(inWindow));
232
+ });
233
+ });
234
+
235
+ test("maxEntries that is not a positive integer falls back to the full window", async () => {
236
+ await withStore(async ({ root, manager, now }) => {
237
+ const all: TranscriptEntry[] = [];
238
+ for (let i = 0; i < 8; i++) all.push(entry(`e${i}`, now - HOUR + i * MIN));
239
+ await writeFileOf(path.join(root, "session/guard", `${today(now)}.jsonl`), all, now);
240
+ for (const bad of [0, -3, 2.5, Number.NaN]) {
241
+ assert.deepEqual(ids(await manager.readRecent(6, undefined, bad)), ids(all), `maxEntries ${bad}`);
242
+ }
243
+ assert.deepEqual(ids(await manager.readRecent(6, undefined, 3)), ["e5", "e6", "e7"]);
244
+ });
245
+ });
246
+
247
+ test("a short read skips that file rather than returning a gap", async (t) => {
248
+ await withStore(async ({ root, manager, now }) => {
249
+ await writeFileOf(path.join(root, "session/short", `${today(now)}.jsonl`), [entry("s1", now - 2 * HOUR), entry("s2", now - HOUR)], now);
250
+ await writeFileOf(path.join(root, "session/whole", `${today(now)}.jsonl`), [entry("w1", now - 90 * MIN)], now);
251
+ const realOpen = fsp.open;
252
+ t.mock.method(fsp, "open", async (...args: Parameters<typeof fsp.open>) => {
253
+ const fh = await realOpen(...args);
254
+ if (!String(args[0]).includes("/short/")) return fh;
255
+ // Report one byte fewer than were read: the data is intact, only the count is short.
256
+ const realRead = fh.read.bind(fh);
257
+ Object.defineProperty(fh, "read", {
258
+ value: async (buffer: Buffer, offset: number, length: number, position: number) => {
259
+ const r = await realRead(buffer, offset, length, position);
260
+ return { buffer: r.buffer, bytesRead: r.bytesRead - 1 };
261
+ },
262
+ });
263
+ return fh;
264
+ });
265
+ syncBuiltinESMExports();
266
+ try {
267
+ assert.deepEqual(ids(await manager.readRecent(6, undefined, 50)), ["w1"]);
268
+ assert.deepEqual(ids(await manager.readRecent(6)), ["w1"]);
269
+ } finally {
270
+ t.mock.restoreAll();
271
+ syncBuiltinESMExports();
272
+ }
273
+ });
274
+ });
275
+
276
+ test("a missing transcripts directory reads as empty", async () => {
277
+ await withStore(async ({ manager }) => {
278
+ assert.deepEqual(await manager.readRecent(6, undefined, 50), []);
279
+ assert.deepEqual(await manager.readRecent(6), []);
280
+ });
281
+ });
282
+
283
+ test("unreadable and unstatable files do not hide the readable ones", async () => {
284
+ await withStore(async ({ root, manager, now }) => {
285
+ const day = today(now);
286
+ await writeFileOf(path.join(root, "session/good", `${day}.jsonl`), [entry("g1", now - HOUR)], now);
287
+ // A directory named like a daily file: stat works, reading it fails.
288
+ await mkdir(path.join(root, "session/isdir", `${day}.jsonl`), { recursive: true });
289
+ // A dangling symlink: listed by name, stat fails.
290
+ await mkdir(path.join(root, "session/dangling"), { recursive: true });
291
+ await symlink(path.join(root, "nowhere"), path.join(root, "session/dangling", `${day}.jsonl`));
292
+ assert.deepEqual(ids(await manager.readRecent(6, undefined, 50)), ["g1"]);
293
+ assert.deepEqual(ids(await manager.readRecent(6)), ["g1"]);
294
+ });
295
+ });
296
+
297
+ test("an unreadable channel or channel-type directory is skipped", { skip: process.getuid?.() === 0 && "root ignores directory modes" }, async () => {
298
+ await withStore(async ({ root, manager, now }) => {
299
+ const day = today(now);
300
+ await writeFileOf(path.join(root, "session/good", `${day}.jsonl`), [entry("g1", now - HOUR)], now);
301
+ await writeFileOf(path.join(root, "session/locked", `${day}.jsonl`), [entry("hidden1", now - HOUR)], now);
302
+ await writeFileOf(path.join(root, "lockedtype/chan", `${day}.jsonl`), [entry("hidden2", now - HOUR)], now);
303
+ await chmod(path.join(root, "session/locked"), 0o000);
304
+ await chmod(path.join(root, "lockedtype"), 0o000);
305
+ try {
306
+ assert.deepEqual(ids(await manager.readRecent(6, undefined, 50)), ["g1"]);
307
+ assert.deepEqual(ids(await manager.readRecent(6)), ["g1"]);
308
+ } finally {
309
+ await chmod(path.join(root, "session/locked"), 0o755);
310
+ await chmod(path.join(root, "lockedtype"), 0o755);
311
+ }
312
+ });
313
+ });
314
+
315
+ test("blank lines at the end of a file do not shrink the newest-N result", async () => {
316
+ await withStore(async ({ root, manager, now }) => {
317
+ // 100 lines of exactly 5300 bytes, then four blank lines: the last 256 KiB chunk holds 50 entry
318
+ // terminators plus the blanks, so the stop rule counts blanks that trim() would later drop.
319
+ const lines: string[] = [];
320
+ for (let i = 0; i < 100; i++) {
321
+ const id = `f${String(i).padStart(4, "0")}`;
322
+ const pad = 5300 - 1 - JSON.stringify(entry(id, 0, "")).length;
323
+ lines.push(JSON.stringify(entry(id, now - 8 * HOUR + i * 2 * MIN, "p".repeat(pad))));
324
+ }
325
+ const file = path.join(root, "session/trailing", `${today(now)}.jsonl`);
326
+ await mkdir(path.dirname(file), { recursive: true });
327
+ await writeFile(file, `${lines.join("\n")}\n\n\n\n\n`, "utf-8");
328
+ const got = await manager.readRecent(12, undefined, 50);
329
+ assert.equal(got.length, 50);
330
+ assert.deepEqual(ids(got), ids(await manager.readRecent(12)).slice(-50));
331
+ });
332
+ });
333
+
334
+ test("a row with a null timestamp at a chunk boundary does not stop the tail scan early", async () => {
335
+ await withStore(async ({ root, manager, now }) => {
336
+ // 100 lines of exactly 5300 bytes: line 51 is the first complete line of the last 256 KiB chunk. new Date(null)
337
+ // is the epoch, so treating it as a cutoff sentinel would stop before the earlier valid entries.
338
+ const lines: string[] = [];
339
+ for (let i = 0; i < 100; i++) {
340
+ const id = `f${String(i).padStart(4, "0")}`;
341
+ const stamped = (content: string) => {
342
+ const e = entry(id, now - 8 * HOUR + i * 2 * MIN, content);
343
+ return i === 51 ? { ...e, timestamp: null } : e;
344
+ };
345
+ const pad = 5300 - 1 - JSON.stringify(stamped("")).length;
346
+ lines.push(JSON.stringify(stamped("p".repeat(pad))));
347
+ }
348
+ const file = path.join(root, "session/nulls", `${today(now)}.jsonl`);
349
+ await mkdir(path.dirname(file), { recursive: true });
350
+ await writeFile(file, `${lines.join("\n")}\n`, "utf-8");
351
+ const got = await manager.readRecent(12, undefined, 50);
352
+ assert.equal(got.length, 50);
353
+ assert.deepEqual(ids(got), ids(await manager.readRecent(12)).slice(-50));
354
+ });
355
+ });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Tail reads of daily transcript files for the unscoped `readRecent` (COS-666c). Split out of
3
+ * transcript.ts to keep that file under its size cap.
4
+ */
5
+
6
+ import { open, stat } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { log } from "./logger.js";
9
+ import type { TranscriptEntry } from "./types.js";
10
+
11
+ const RECENT_TAIL_CHUNK_BYTES = 1 << 18;
12
+ export const RECENT_SKEW_MS = 3_600_000;
13
+
14
+ const ISO_STAMP = /^\d{4}-\d\d-\d\dT/;
15
+
16
+ /** True when the first complete line in `chunk` (which starts mid-line) is stamped before `cutoffMs`. */
17
+ function firstLineBefore(chunk: Buffer, cutoffMs: number): boolean {
18
+ const from = chunk.indexOf(0x0a) + 1;
19
+ const to = chunk.indexOf(0x0a, from);
20
+ if (from === 0 || to < 0) return false;
21
+ try {
22
+ // SAFETY: only `.timestamp` is read, and it is used only if it is an ISO string (the test coerces null, numbers
23
+ // and other shapes to text that fails); new Date(null) is the epoch and would stop the scan early.
24
+ const stamp = (JSON.parse(chunk.toString("utf-8", from, to)) as TranscriptEntry).timestamp;
25
+ return ISO_STAMP.test(stamp) && new Date(stamp).getTime() < cutoffMs;
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+
31
+ function countNewlines(chunk: Buffer): number {
32
+ let n = 0;
33
+ for (let i = chunk.indexOf(0x0a); i >= 0; i = chunk.indexOf(0x0a, i + 1)) n++;
34
+ return n;
35
+ }
36
+
37
+ const FS_CONCURRENCY = 48;
38
+
39
+ /** `items.map(fn)` with at most FS_CONCURRENCY in flight (the libuv pool is shared); results keep input order. */
40
+ export async function mapLimited<T, R>(items: T[], fn: (item: T) => Promise<R>): Promise<R[]> {
41
+ const out = new Array<R>(items.length);
42
+ let next = 0;
43
+ await Promise.all(Array.from({ length: Math.min(FS_CONCURRENCY, items.length) }, async () => {
44
+ while (next < items.length) {
45
+ const i = next++;
46
+ out[i] = await fn(items[i]);
47
+ }
48
+ }));
49
+ return out;
50
+ }
51
+
52
+ /**
53
+ * Lines of a daily transcript file that can be stamped at or after `cutoffMs`.
54
+ * Files are appended in write order, so the recent window is the file's tail:
55
+ * read 256 KiB chunks from the end and stop once the first complete line in hand is
56
+ * older than the cutoff, or (with `maxLines`) once `maxLines` complete lines are in hand,
57
+ * returning at most the last `maxLines`. A file not modified since the cutoff holds nothing in the window.
58
+ * shortcut: assumes a file's timestamps never run backwards by more than the
59
+ * RECENT_SKEW_MS the caller subtracts, and that its last `maxLines` lines hold its newest
60
+ * `maxLines` entries (the newest-N path has no skew margin: a writer stamping entries late can change which N are returned); widen the margin if writers can lag further.
61
+ */
62
+ export async function readLinesSince(filePath: string, cutoffMs: number, maxLines = Infinity): Promise<string[]> {
63
+ const { size, mtimeMs } = await stat(filePath);
64
+ if (mtimeMs < cutoffMs) return [];
65
+ const fh = await open(filePath, "r");
66
+ try {
67
+ const chunks: Buffer[] = [];
68
+ let pos = size;
69
+ let newlines = 0;
70
+ while (pos > 0) {
71
+ const buf = Buffer.allocUnsafe(Math.min(RECENT_TAIL_CHUNK_BYTES, pos));
72
+ pos -= buf.length;
73
+ const { bytesRead } = await fh.read(buf, 0, buf.length, pos);
74
+ if (bytesRead !== buf.length) throw new Error(`short read on ${filePath}`); // a gap would silently drop lines
75
+ chunks.unshift(buf);
76
+ newlines += countNewlines(chunks[0]);
77
+ // One newline ends the partial first line; each further one ends a complete line.
78
+ if (pos > 0 && (newlines > maxLines || firstLineBefore(chunks[0], cutoffMs))) break;
79
+ }
80
+ let text = Buffer.concat(chunks).toString("utf-8");
81
+ if (pos > 0) text = text.slice(text.indexOf("\n") + 1); // drop the partial first line
82
+ // Blank lines stay (only the final terminator goes): they count toward `maxLines` like the chunk stop counts them, and a blank fails to parse like any bad line.
83
+ return (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n").slice(-maxLines);
84
+ } finally {
85
+ await fh.close();
86
+ }
87
+ }
88
+
89
+ /** The newest `limit` entries in `[start, end)` from the given daily files (paths relative to `transcriptsDir`). */
90
+ export async function readNewestFromFiles(
91
+ transcriptsDir: string,
92
+ files: string[],
93
+ start: Date,
94
+ end: Date,
95
+ limit: number,
96
+ ): Promise<TranscriptEntry[]> {
97
+ const startMs = start.getTime();
98
+ const stamped = await mapLimited(files, async (f) => {
99
+ const filePath = path.join(transcriptsDir, f);
100
+ return { filePath, mtimeMs: await stat(filePath).then((s) => s.mtimeMs, () => -Infinity) };
101
+ });
102
+ stamped.sort((a, b) => b.mtimeMs - a.mtimeMs);
103
+ let newest: TranscriptEntry[] = []; // ascending by timestamp, at most `limit`
104
+ for (const { filePath, mtimeMs } of stamped) {
105
+ // The Nth-newest timestamp so far; a file modified more than the skew before it holds nothing newer.
106
+ const floorMs = newest.length >= limit ? new Date(newest[0].timestamp).getTime() : startMs;
107
+ if (mtimeMs + RECENT_SKEW_MS < floorMs) break;
108
+ let found: TranscriptEntry[] = [];
109
+ // A bad line (torn append, no timestamp, future-dated) takes a slot without yielding an entry:
110
+ // widen the tail until `limit` entries are found or the file's window is exhausted.
111
+ for (let cap = limit; ; cap *= 2) {
112
+ const lines = await readLinesSince(filePath, floorMs - RECENT_SKEW_MS, cap).catch(() => []);
113
+ found = [];
114
+ for (const line of lines) {
115
+ try {
116
+ // SAFETY: the same cast the full-window read made here; `timestamp` is validated on the next line.
117
+ const entry = JSON.parse(line) as TranscriptEntry;
118
+ const entryTime = new Date(entry.timestamp);
119
+ if (entryTime >= start && entryTime < end) found.push(entry);
120
+ } catch {
121
+ log.debug(`skipped malformed transcript line in ${filePath}`);
122
+ }
123
+ }
124
+ if (found.length >= limit || lines.length < cap) break;
125
+ }
126
+ newest = [...newest, ...found].sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()).slice(-limit);
127
+ }
128
+ return newest;
129
+ }
package/src/transcript.ts CHANGED
@@ -8,6 +8,7 @@ import { sessionStoragePaths } from "./session-identity.js";
8
8
  import { estimateTokenCount } from "./token-estimate.js";
9
9
  import { isMacOsReplicationJunkBasename } from "./utils/macos-replication-junk.js";
10
10
  import { JsonlOwnershipDigestCache } from "./transcript-ownership-digest.js";
11
+ import { RECENT_SKEW_MS, mapLimited, readLinesSince, readNewestFromFiles } from "./transcript-recent.js";
11
12
 
12
13
  type DirectorySessionStatus = "missing" | "empty" | "matches" | "occupied";
13
14
 
@@ -559,52 +560,31 @@ export class TranscriptManager {
559
560
  /**
560
561
  * Get all transcript files from the hierarchical directory structure.
561
562
  * Recursively finds all .jsonl files in transcripts/{channelType}/{channelId}/ subdirectories.
563
+ * Directories are listed concurrently: a large store has ~17k channel directories and a
564
+ * sequential walk spent ~1.5 s on round trips alone. Results keep readdir order.
562
565
  */
563
566
  private async getAllTranscriptFiles(): Promise<string[]> {
564
- const files: string[] = [];
565
-
566
- try {
567
- const entries = await readdir(this.transcriptsDir, { withFileTypes: true });
568
-
569
- for (const entry of entries) {
570
- if (entry.isDirectory()) {
571
- // This is a channel type directory (discord, slack, cron, main, etc.)
572
- const channelTypeDir = path.join(this.transcriptsDir, entry.name);
573
- try {
574
- const channelTypeEntries = await readdir(channelTypeDir, { withFileTypes: true });
575
-
576
- for (const channelTypeEntry of channelTypeEntries) {
577
- if (channelTypeEntry.isDirectory()) {
578
- // This is a channel ID directory - contains daily transcript files
579
- const channelDir = path.join(channelTypeDir, channelTypeEntry.name);
580
- try {
581
- const channelFiles = await readdir(channelDir);
582
- for (const file of channelFiles) {
583
- if (file.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(file)) {
584
- files.push(path.join(entry.name, channelTypeEntry.name, file));
585
- }
586
- }
587
- } catch {
588
- // Skip unreadable directories
589
- }
590
- } else if (channelTypeEntry.isFile() && channelTypeEntry.name.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(channelTypeEntry.name)) {
591
- // Legacy: channel type dir contains .jsonl files directly
592
- files.push(path.join(entry.name, channelTypeEntry.name));
593
- }
594
- }
595
- } catch {
596
- // Skip unreadable directories
597
- }
598
- } else if (entry.isFile() && entry.name.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(entry.name)) {
599
- // Legacy flat file - still include for backward compatibility
600
- files.push(entry.name);
567
+ const isJsonl = (name: string): boolean => name.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(name);
568
+ // Directory doesn't exist or is unreadable: skip it.
569
+ const top = await readdir(this.transcriptsDir, { withFileTypes: true }).catch(() => []);
570
+ const perTop = await Promise.all(top.map(async (entry): Promise<string[]> => {
571
+ // Legacy flat file - still include for backward compatibility
572
+ if (!entry.isDirectory()) return entry.isFile() && isJsonl(entry.name) ? [entry.name] : [];
573
+ // A channel type directory (discord, slack, cron, main, etc.)
574
+ const channelTypeDir = path.join(this.transcriptsDir, entry.name);
575
+ const children = await readdir(channelTypeDir, { withFileTypes: true }).catch(() => []);
576
+ const perChild = await mapLimited(children, async (child): Promise<string[]> => {
577
+ if (child.isDirectory()) {
578
+ // A channel ID directory - contains daily transcript files
579
+ const channelFiles = await readdir(path.join(channelTypeDir, child.name)).catch(() => []);
580
+ return channelFiles.filter(isJsonl).map((file) => path.join(entry.name, child.name, file));
601
581
  }
602
- }
603
- } catch {
604
- // Directory doesn't exist or is unreadable
605
- }
606
-
607
- return files;
582
+ // Legacy: channel type dir contains .jsonl files directly
583
+ return child.isFile() && isJsonl(child.name) ? [path.join(entry.name, child.name)] : [];
584
+ });
585
+ return perChild.flat();
586
+ }));
587
+ return perTop.flat();
608
588
  }
609
589
 
610
590
  /**
@@ -641,8 +621,9 @@ export class TranscriptManager {
641
621
  for (const relativePath of transcriptFiles) {
642
622
  const filePath = path.join(this.transcriptsDir, relativePath);
643
623
  try {
644
- const content = await readFile(filePath, "utf-8");
645
- const lines = content.trim().split("\n").filter(Boolean);
624
+ const lines = skipFilesDatedBefore !== undefined
625
+ ? await readLinesSince(filePath, start.getTime() - RECENT_SKEW_MS)
626
+ : (await readFile(filePath, "utf-8")).trim().split("\n").filter(Boolean);
646
627
 
647
628
  for (const line of lines) {
648
629
  try {
@@ -682,9 +663,13 @@ export class TranscriptManager {
682
663
  * Read the last N hours of transcript.
683
664
  *
684
665
  * Fast path: when sessionKey is given, reads only the 1-2 daily files for that channel. Without one,
685
- * every channel is scanned but daily files older than the window (less a day of clock skew) are skipped.
666
+ * every channel is scanned but daily files older than the window (less a day of clock skew) are skipped,
667
+ * and each file is read from its tail. With `maxEntries` and no sessionKey, only the newest `maxEntries`
668
+ * entries are returned (what a caller that keeps `slice(-maxEntries)` would see) and files are visited
669
+ * newest-modified first, stopping once no remaining file can hold a newer entry. The per-file read cap of
670
+ * 48 applies per channel-type directory, not globally.
686
671
  */
687
- async readRecent(hours: number, sessionKey?: string): Promise<TranscriptEntry[]> {
672
+ async readRecent(hours: number, sessionKey?: string, maxEntries?: number): Promise<TranscriptEntry[]> {
688
673
  const now = new Date();
689
674
  // The recent-read window is inclusive of "now": a turn that is buffered and
690
675
  // then immediately read back can carry the same millisecond timestamp as
@@ -700,9 +685,24 @@ export class TranscriptManager {
700
685
  if (sessionKey) {
701
686
  return this.readRecentForSession(start, end, sessionKey);
702
687
  }
688
+ if (maxEntries !== undefined && Number.isInteger(maxEntries) && maxEntries >= 1) {
689
+ return this.readNewestEntries(start, end, maxEntries);
690
+ }
703
691
  return this.readRange(start.toISOString(), end.toISOString(), undefined, new Date(start.getTime() - 86_400_000).toISOString().slice(0, 10));
704
692
  }
705
693
 
694
+ /** Newest `limit` entries in `[start, end)` across every channel; see {@link readRecent}. */
695
+ private async readNewestEntries(start: Date, end: Date, limit: number): Promise<TranscriptEntry[]> {
696
+ const minDate = new Date(start.getTime() - 86_400_000).toISOString().slice(0, 10);
697
+ try {
698
+ const files = (await this.getAllTranscriptFiles()).filter((f) => !isDailyFileDatedBefore(f, minDate));
699
+ return await readNewestFromFiles(this.transcriptsDir, files, start, end, limit);
700
+ } catch (err) {
701
+ log.error("failed to read newest transcript entries:", err);
702
+ return [];
703
+ }
704
+ }
705
+
706
706
  /**
707
707
  * Optimized read for a specific session: only looks in that session's channel
708
708
  * directory and only reads files whose date falls within the lookback window.