@remnic/core 10.0.110 → 10.0.112
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.
- package/dist/access-admin-ops-surface.js +69 -67
- package/dist/access-cli.js +69 -67
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush.js +69 -67
- package/dist/access-http-briefing.js +69 -67
- package/dist/access-http-query.js +69 -67
- package/dist/access-http.js +69 -67
- package/dist/access-identity-continuity-surface.js +69 -67
- package/dist/access-lcm-surface.js +69 -67
- package/dist/access-mcp.js +69 -67
- package/dist/access-observe-write-category.js +5 -5
- package/dist/access-observe-write-surface.js +69 -67
- package/dist/access-operations-batch.js +69 -67
- package/dist/access-operations.js +69 -67
- package/dist/access-recall-concurrency.js +69 -67
- package/dist/access-recall-response.js +69 -67
- package/dist/access-recall-surface.js +69 -67
- package/dist/access-schema.js +4 -4
- package/dist/access-service.js +69 -67
- package/dist/active-recall.js +6 -6
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/briefing.js +7 -7
- package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
- package/dist/causal-consolidation.js +8 -8
- package/dist/{chunk-4TYIHHPW.js → chunk-4N7L2N54.js} +111 -98
- package/dist/{chunk-4TYIHHPW.js.map → chunk-4N7L2N54.js.map} +1 -1
- package/dist/{chunk-WQ4XKIOX.js → chunk-5RONA5FF.js} +70 -52
- package/dist/chunk-5RONA5FF.js.map +1 -0
- package/dist/{chunk-ZG4GNPRE.js → chunk-BNQJKWWZ.js} +8 -8
- package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
- package/dist/{chunk-7QIRIF3Z.js → chunk-C2KBLOKE.js} +2 -2
- package/dist/{chunk-AZYUG2HW.js → chunk-C6WVKVHZ.js} +2 -2
- package/dist/{chunk-JODSN3V5.js → chunk-CTQ2XD4R.js} +2 -2
- package/dist/{chunk-XNI3URDR.js → chunk-D5F3D7DA.js} +2 -2
- package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
- package/dist/{chunk-LYR57GEF.js → chunk-EKWS6NCF.js} +3 -3
- package/dist/{chunk-XTN54NML.js → chunk-G3T6YMBO.js} +4 -4
- package/dist/{chunk-AOAREXFV.js → chunk-G6TDGYVC.js} +2 -2
- package/dist/chunk-GE5J2T67.js +100 -0
- package/dist/chunk-GE5J2T67.js.map +1 -0
- package/dist/{chunk-BUOP3DOK.js → chunk-GRS34Y7V.js} +2 -2
- package/dist/{chunk-FQACH7MC.js → chunk-HM62567O.js} +2 -2
- package/dist/{chunk-B3LGXOM5.js → chunk-IOLFR3JJ.js} +2 -2
- package/dist/{chunk-WCKLRFGF.js → chunk-J5MBTYDO.js} +2 -2
- package/dist/{chunk-HRMOKGQM.js → chunk-JCKN3E6Y.js} +2 -2
- package/dist/{chunk-UOIVXBNS.js → chunk-JTO63AXR.js} +2 -2
- package/dist/{chunk-AY535ZIM.js → chunk-KPFOFT4I.js} +2 -2
- package/dist/{chunk-S2HLHAZ4.js → chunk-L76BQSWB.js} +10 -2
- package/dist/chunk-L76BQSWB.js.map +1 -0
- package/dist/{chunk-FV2B6XE6.js → chunk-NRZJKDGO.js} +2 -2
- package/dist/{chunk-VLUWWPKO.js → chunk-O5DO5LXA.js} +13 -13
- package/dist/{chunk-5VWN3FJS.js → chunk-OSYHJCLK.js} +2 -2
- package/dist/chunk-PQVLF42S.js +87 -0
- package/dist/chunk-PQVLF42S.js.map +1 -0
- package/dist/{chunk-OLJYBMFW.js → chunk-Q7UY2CSW.js} +7 -7
- package/dist/{chunk-R2DOFBG4.js → chunk-QNTBJKTN.js} +2 -2
- package/dist/{chunk-7SW6EBEF.js → chunk-QYN6I3CG.js} +2 -2
- package/dist/{chunk-KQAFEZQX.js → chunk-R45L4TV6.js} +6 -6
- package/dist/{chunk-7HNQR5MV.js → chunk-R76L66OW.js} +3 -3
- package/dist/{chunk-QIGEWFXE.js → chunk-RJTHGVO3.js} +2 -2
- package/dist/{chunk-FVMEZ57K.js → chunk-RLXD2L3G.js} +7 -7
- package/dist/{chunk-25BUV3TU.js → chunk-S4G7WX7Q.js} +2 -2
- package/dist/{chunk-BP7LNNWG.js → chunk-SMAPUZYV.js} +2 -2
- package/dist/{chunk-GT2TH7FZ.js → chunk-T4FW43AG.js} +3 -3
- package/dist/{chunk-OIOKDTZU.js → chunk-T5DX6A7T.js} +17 -6
- package/dist/chunk-T5DX6A7T.js.map +1 -0
- package/dist/{chunk-EDVVW655.js → chunk-T6H5HNA6.js} +2 -2
- package/dist/{chunk-YD4D4EVO.js → chunk-TA6IK76H.js} +2 -2
- package/dist/{chunk-7ZEF43SR.js → chunk-TPAIKAT5.js} +3 -3
- package/dist/{chunk-IOGYSADY.js → chunk-TS34Y2T5.js} +2 -2
- package/dist/{chunk-OEVJH66T.js → chunk-VHWQGBXY.js} +3 -3
- package/dist/{chunk-63OWJXGW.js → chunk-VMEFUPOM.js} +2 -2
- package/dist/{chunk-E55J2NFL.js → chunk-WP25PXBB.js} +2 -2
- package/dist/{chunk-H4XPEXWA.js → chunk-XOCAG2LF.js} +2 -2
- package/dist/{chunk-K32VAS5B.js → chunk-YPDUSAPH.js} +2 -2
- package/dist/cli.js +69 -67
- package/dist/coding/export-okf-codegraph.js +6 -6
- package/dist/compounding/engine.js +8 -8
- package/dist/config.js +6 -6
- package/dist/connectors/codex-materialize-runner.js +7 -7
- package/dist/connectors/index.js +7 -7
- package/dist/convergence-refresh.js +9 -9
- package/dist/corpus-watermark.js +9 -9
- package/dist/deep-recall-http-glue.js +5 -5
- package/dist/entity-retrieval.js +7 -7
- package/dist/explicit-capture.js +69 -67
- package/dist/extraction.js +7 -7
- package/dist/harmonic-retrieval.js +7 -7
- package/dist/index.js +86 -84
- package/dist/lcm/engine.js +3 -3
- package/dist/lcm/index.js +9 -9
- package/dist/location/index.js +8 -8
- package/dist/maintenance/memory-governance.js +7 -7
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -7
- package/dist/maintenance/rebuild-memory-projection-runner.js +9 -9
- package/dist/maintenance/rebuild-memory-projection.js +8 -8
- package/dist/memory-snapshot.d.ts +7 -1
- package/dist/memory-snapshot.d.ts.map +1 -1
- package/dist/memory-snapshot.js +5 -3
- package/dist/namespaces/migrate.js +8 -8
- package/dist/namespaces/search.js +4 -4
- package/dist/namespaces/storage.js +7 -7
- package/dist/operator-doctor-corpus.js +10 -10
- package/dist/operator-toolkit.js +13 -13
- package/dist/orchestration/backlog-scheduler.js +70 -68
- package/dist/orchestration/backlog-scheduler.js.map +1 -1
- package/dist/orchestration/buffer-drain-runner.js +70 -68
- package/dist/orchestration/maintenance.js +15 -15
- package/dist/orchestration/recall-internal.d.ts.map +1 -1
- package/dist/orchestration/workspace-ops.d.ts.map +1 -1
- package/dist/orchestrator.js +69 -67
- package/dist/recall-navigation.js +69 -67
- package/dist/resume-bundles.js +10 -8
- package/dist/search/factory.js +3 -3
- package/dist/search/index.js +7 -7
- package/dist/semantic-consolidation.js +8 -8
- package/dist/semantic-rule-promotion.js +7 -7
- package/dist/semantic-rule-verifier.js +7 -7
- package/dist/source-agent-qualifier.js +7 -7
- package/dist/standup/build.js +7 -7
- package/dist/storage.d.ts +3 -0
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +6 -6
- package/dist/transcript-recent.d.ts +22 -0
- package/dist/transcript-recent.d.ts.map +1 -0
- package/dist/transcript-recent.js +15 -0
- package/dist/transcript-recent.js.map +1 -0
- package/dist/transcript-write-dir-memo.d.ts +43 -0
- package/dist/transcript-write-dir-memo.d.ts.map +1 -0
- package/dist/transcript-write-dir-memo.js +10 -0
- package/dist/transcript-write-dir-memo.js.map +1 -0
- package/dist/transcript.d.ts +15 -3
- package/dist/transcript.d.ts.map +1 -1
- package/dist/transcript.js +3 -1
- package/dist/transfer/autodetect.js +1 -1
- package/dist/transfer/backup.js +2 -2
- package/dist/transfer/capsule-export.js +3 -3
- package/dist/transfer/capsule-import.js +2 -2
- package/dist/transfer/export-okf.js +7 -7
- package/dist/verified-recall.js +7 -7
- package/dist/who-knows-cli.js +8 -8
- package/dist/who-knows.js +7 -7
- package/package.json +2 -2
- package/src/memory-snapshot.ts +14 -1
- package/src/orchestration/recall-internal.ts +1 -4
- package/src/orchestration/workspace-ops.test.ts +113 -0
- package/src/orchestration/workspace-ops.ts +38 -12
- package/src/storage-contract/lazy-memory-snapshot.test.ts +194 -0
- package/src/storage.ts +15 -4
- package/src/transcript-ownership-digest.test.ts +8 -0
- package/src/transcript-recent-tail.test.ts +355 -0
- package/src/transcript-recent.ts +129 -0
- package/src/transcript-write-dir-memo.test.ts +308 -0
- package/src/transcript-write-dir-memo.ts +104 -0
- package/src/transcript.ts +70 -63
- package/dist/chunk-OIOKDTZU.js.map +0 -1
- package/dist/chunk-S2HLHAZ4.js.map +0 -1
- package/dist/chunk-WQ4XKIOX.js.map +0 -1
- /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
- /package/dist/{chunk-ZG4GNPRE.js.map → chunk-BNQJKWWZ.js.map} +0 -0
- /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
- /package/dist/{chunk-7QIRIF3Z.js.map → chunk-C2KBLOKE.js.map} +0 -0
- /package/dist/{chunk-AZYUG2HW.js.map → chunk-C6WVKVHZ.js.map} +0 -0
- /package/dist/{chunk-JODSN3V5.js.map → chunk-CTQ2XD4R.js.map} +0 -0
- /package/dist/{chunk-XNI3URDR.js.map → chunk-D5F3D7DA.js.map} +0 -0
- /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
- /package/dist/{chunk-LYR57GEF.js.map → chunk-EKWS6NCF.js.map} +0 -0
- /package/dist/{chunk-XTN54NML.js.map → chunk-G3T6YMBO.js.map} +0 -0
- /package/dist/{chunk-AOAREXFV.js.map → chunk-G6TDGYVC.js.map} +0 -0
- /package/dist/{chunk-BUOP3DOK.js.map → chunk-GRS34Y7V.js.map} +0 -0
- /package/dist/{chunk-FQACH7MC.js.map → chunk-HM62567O.js.map} +0 -0
- /package/dist/{chunk-B3LGXOM5.js.map → chunk-IOLFR3JJ.js.map} +0 -0
- /package/dist/{chunk-WCKLRFGF.js.map → chunk-J5MBTYDO.js.map} +0 -0
- /package/dist/{chunk-HRMOKGQM.js.map → chunk-JCKN3E6Y.js.map} +0 -0
- /package/dist/{chunk-UOIVXBNS.js.map → chunk-JTO63AXR.js.map} +0 -0
- /package/dist/{chunk-AY535ZIM.js.map → chunk-KPFOFT4I.js.map} +0 -0
- /package/dist/{chunk-FV2B6XE6.js.map → chunk-NRZJKDGO.js.map} +0 -0
- /package/dist/{chunk-VLUWWPKO.js.map → chunk-O5DO5LXA.js.map} +0 -0
- /package/dist/{chunk-5VWN3FJS.js.map → chunk-OSYHJCLK.js.map} +0 -0
- /package/dist/{chunk-OLJYBMFW.js.map → chunk-Q7UY2CSW.js.map} +0 -0
- /package/dist/{chunk-R2DOFBG4.js.map → chunk-QNTBJKTN.js.map} +0 -0
- /package/dist/{chunk-7SW6EBEF.js.map → chunk-QYN6I3CG.js.map} +0 -0
- /package/dist/{chunk-KQAFEZQX.js.map → chunk-R45L4TV6.js.map} +0 -0
- /package/dist/{chunk-7HNQR5MV.js.map → chunk-R76L66OW.js.map} +0 -0
- /package/dist/{chunk-QIGEWFXE.js.map → chunk-RJTHGVO3.js.map} +0 -0
- /package/dist/{chunk-FVMEZ57K.js.map → chunk-RLXD2L3G.js.map} +0 -0
- /package/dist/{chunk-25BUV3TU.js.map → chunk-S4G7WX7Q.js.map} +0 -0
- /package/dist/{chunk-BP7LNNWG.js.map → chunk-SMAPUZYV.js.map} +0 -0
- /package/dist/{chunk-GT2TH7FZ.js.map → chunk-T4FW43AG.js.map} +0 -0
- /package/dist/{chunk-EDVVW655.js.map → chunk-T6H5HNA6.js.map} +0 -0
- /package/dist/{chunk-YD4D4EVO.js.map → chunk-TA6IK76H.js.map} +0 -0
- /package/dist/{chunk-7ZEF43SR.js.map → chunk-TPAIKAT5.js.map} +0 -0
- /package/dist/{chunk-IOGYSADY.js.map → chunk-TS34Y2T5.js.map} +0 -0
- /package/dist/{chunk-OEVJH66T.js.map → chunk-VHWQGBXY.js.map} +0 -0
- /package/dist/{chunk-63OWJXGW.js.map → chunk-VMEFUPOM.js.map} +0 -0
- /package/dist/{chunk-E55J2NFL.js.map → chunk-WP25PXBB.js.map} +0 -0
- /package/dist/{chunk-H4XPEXWA.js.map → chunk-XOCAG2LF.js.map} +0 -0
- /package/dist/{chunk-K32VAS5B.js.map → chunk-YPDUSAPH.js.map} +0 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test, { mock } from "node:test";
|
|
6
|
+
import { parseConfig } from "./config.js";
|
|
7
|
+
import { JsonlOwnershipDigestCache } from "./transcript-ownership-digest.js";
|
|
8
|
+
import { WriteDirMemo } from "./transcript-write-dir-memo.js";
|
|
9
|
+
import { TranscriptManager } from "./transcript.js";
|
|
10
|
+
import type { TranscriptEntry } from "./types.js";
|
|
11
|
+
|
|
12
|
+
async function withManager(
|
|
13
|
+
fn: (ctx: { manager: TranscriptManager; root: string }) => Promise<void>,
|
|
14
|
+
): Promise<void> {
|
|
15
|
+
const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-transcript-memo-"));
|
|
16
|
+
try {
|
|
17
|
+
const manager = new TranscriptManager(parseConfig({ memoryDir }));
|
|
18
|
+
await manager.initialize();
|
|
19
|
+
await fn({ manager, root: path.join(memoryDir, "transcripts") });
|
|
20
|
+
} finally {
|
|
21
|
+
await rm(memoryDir, { recursive: true, force: true });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function entry(sessionKey: string, turnId: string): TranscriptEntry {
|
|
26
|
+
return { timestamp: new Date().toISOString(), role: "user", content: `turn ${turnId}`, sessionKey, turnId };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Write `days` old daily files, each holding one row owned by `sessionKey`. */
|
|
30
|
+
async function writeOldDays(channelDir: string, sessionKey: string, days: number): Promise<void> {
|
|
31
|
+
await mkdir(channelDir, { recursive: true });
|
|
32
|
+
for (let day = 1; day <= days; day++) {
|
|
33
|
+
const date = new Date(Date.UTC(2026, 0, day)).toISOString().slice(0, 10);
|
|
34
|
+
await writeFile(path.join(channelDir, `${date}.jsonl`), `${JSON.stringify(entry(sessionKey, `old${day}`))}\n`, "utf-8");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function jsonlContents(dir: string): Promise<string> {
|
|
39
|
+
const names = (await readdir(dir).catch(() => [])).filter((n) => n.endsWith(".jsonl")).sort();
|
|
40
|
+
return (await Promise.all(names.map((n) => readFile(path.join(dir, n), "utf-8")))).join("");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
test("a session's later appends do not re-read its old daily files", async () => {
|
|
44
|
+
await withManager(async ({ manager, root }) => {
|
|
45
|
+
const owner = "pi-geek:memo-steady";
|
|
46
|
+
const channelDir = path.join(root, manager.getTranscriptPath(owner).dir);
|
|
47
|
+
await writeOldDays(channelDir, owner, 5);
|
|
48
|
+
const verify = mock.method(JsonlOwnershipDigestCache.prototype, "verify");
|
|
49
|
+
try {
|
|
50
|
+
await manager.append(entry(owner, "a1"));
|
|
51
|
+
assert.equal(verify.mock.callCount(), 5, "the first append verifies the directory once");
|
|
52
|
+
verify.mock.resetCalls();
|
|
53
|
+
await manager.append(entry(owner, "a2"));
|
|
54
|
+
await manager.append(entry(owner, "a3"));
|
|
55
|
+
assert.equal(verify.mock.callCount(), 0, "later appends re-verified the directory");
|
|
56
|
+
} finally {
|
|
57
|
+
verify.mock.restore();
|
|
58
|
+
}
|
|
59
|
+
const text = await jsonlContents(channelDir);
|
|
60
|
+
for (const id of ["a1", "a2", "a3"]) assert.ok(text.includes(`"turnId":"${id}"`), `${id} was not written`);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("a directory holding another session's rows is still refused on the first append", async () => {
|
|
65
|
+
await withManager(async ({ manager, root }) => {
|
|
66
|
+
const owner = "pi-geek:memo-owner";
|
|
67
|
+
const intruder = "pi-geek:memo-intrude";
|
|
68
|
+
const { dir, alternateDir } = manager.getTranscriptPath(owner);
|
|
69
|
+
await writeOldDays(path.join(root, dir), intruder, 2);
|
|
70
|
+
await manager.append(entry(owner, "b1"));
|
|
71
|
+
await manager.append(entry(owner, "b2"));
|
|
72
|
+
assert.equal((await jsonlContents(path.join(root, dir))).includes('"turnId":"b1"'), false, "wrote into a foreign directory");
|
|
73
|
+
const alternate = await jsonlContents(path.join(root, alternateDir));
|
|
74
|
+
assert.ok(alternate.includes('"turnId":"b1"') && alternate.includes('"turnId":"b2"'));
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("an append error drops the remembered directory so the next append verifies it again", async (t) => {
|
|
79
|
+
if (process.getuid?.() === 0) {
|
|
80
|
+
t.skip("root bypasses file permissions");
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
await withManager(async ({ manager, root }) => {
|
|
84
|
+
const owner = "pi-geek:memo-error";
|
|
85
|
+
const { dir, file } = manager.getTranscriptPath(owner);
|
|
86
|
+
const channelDir = path.join(root, dir);
|
|
87
|
+
await writeOldDays(channelDir, owner, 3);
|
|
88
|
+
await manager.append(entry(owner, "c1"));
|
|
89
|
+
// A read-only daily file lets the directory check pass and makes appendFile fail.
|
|
90
|
+
const today = path.join(channelDir, file);
|
|
91
|
+
await chmod(today, 0o444);
|
|
92
|
+
await assert.rejects(manager.append(entry(owner, "c2")));
|
|
93
|
+
await chmod(today, 0o644);
|
|
94
|
+
const verify = mock.method(JsonlOwnershipDigestCache.prototype, "verify");
|
|
95
|
+
try {
|
|
96
|
+
await manager.append(entry(owner, "c3"));
|
|
97
|
+
assert.ok(verify.mock.callCount() >= 3, "the directory was not verified again after the error");
|
|
98
|
+
} finally {
|
|
99
|
+
verify.mock.restore();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("each session keeps its own remembered directory", async () => {
|
|
105
|
+
await withManager(async ({ manager, root }) => {
|
|
106
|
+
const a = "pi-geek:memo-a";
|
|
107
|
+
const b = "pi-geek:memo-b";
|
|
108
|
+
await writeOldDays(path.join(root, manager.getTranscriptPath(a).dir), a, 2);
|
|
109
|
+
await writeOldDays(path.join(root, manager.getTranscriptPath(b).dir), b, 2);
|
|
110
|
+
await manager.append(entry(a, "d1"));
|
|
111
|
+
const verify = mock.method(JsonlOwnershipDigestCache.prototype, "verify");
|
|
112
|
+
try {
|
|
113
|
+
await manager.append(entry(b, "d2"));
|
|
114
|
+
assert.equal(verify.mock.callCount(), 2, "a's memo must not skip b's first verification");
|
|
115
|
+
} finally {
|
|
116
|
+
verify.mock.restore();
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("a file edited behind the process is noticed only after the remembered directory is dropped", async () => {
|
|
122
|
+
await withManager(async ({ manager, root }) => {
|
|
123
|
+
const owner = "pi-geek:memo-edit-a";
|
|
124
|
+
const intruder = "pi-geek:memo-edit-b";
|
|
125
|
+
const { dir, alternateDir, file } = manager.getTranscriptPath(owner);
|
|
126
|
+
await manager.append(entry(owner, "e1"));
|
|
127
|
+
const primary = path.join(root, dir, file);
|
|
128
|
+
await writeFile(primary, (await readFile(primary, "utf-8")).replaceAll(owner, intruder), "utf-8");
|
|
129
|
+
|
|
130
|
+
await manager.append(entry(owner, "e2"));
|
|
131
|
+
assert.ok((await jsonlContents(path.join(root, dir))).includes('"turnId":"e2"'), "the remembered directory is trusted");
|
|
132
|
+
|
|
133
|
+
manager.resetWriteDirs();
|
|
134
|
+
await manager.append(entry(owner, "e3"));
|
|
135
|
+
assert.equal((await jsonlContents(path.join(root, dir))).includes('"turnId":"e3"'), false);
|
|
136
|
+
assert.ok((await jsonlContents(path.join(root, alternateDir))).includes('"turnId":"e3"'));
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("a cleanup that deletes files drops the remembered directories", async () => {
|
|
141
|
+
await withManager(async ({ manager, root }) => {
|
|
142
|
+
const owner = "pi-geek:memo-cleanup";
|
|
143
|
+
const channelDir = path.join(root, manager.getTranscriptPath(owner).dir);
|
|
144
|
+
await writeOldDays(channelDir, owner, 2); // 2026-01-01 and 2026-01-02, past any retention window
|
|
145
|
+
await manager.append(entry(owner, "f1"));
|
|
146
|
+
assert.equal(await manager.cleanup(30), 2);
|
|
147
|
+
const verify = mock.method(JsonlOwnershipDigestCache.prototype, "verify");
|
|
148
|
+
try {
|
|
149
|
+
await manager.append(entry(owner, "f2"));
|
|
150
|
+
assert.ok(verify.mock.callCount() >= 1, "the directory was not verified again after the cleanup");
|
|
151
|
+
} finally {
|
|
152
|
+
verify.mock.restore();
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test("a choice that was pending when the memo was cleared or forgotten is not remembered", async () => {
|
|
158
|
+
for (const invalidate of ["clear", "forget"] as const) {
|
|
159
|
+
const memo = new WriteDirMemo();
|
|
160
|
+
let release: () => void = () => {};
|
|
161
|
+
const gate = new Promise<void>((resolve) => {
|
|
162
|
+
release = resolve;
|
|
163
|
+
});
|
|
164
|
+
let calls = 0;
|
|
165
|
+
const choose = async () => {
|
|
166
|
+
calls++;
|
|
167
|
+
if (calls === 1) await gate;
|
|
168
|
+
return { dir: `d${calls}`, channelDir: `c${calls}` };
|
|
169
|
+
};
|
|
170
|
+
const pending = memo.resolve("root", "session", choose);
|
|
171
|
+
if (invalidate === "clear") memo.clear();
|
|
172
|
+
else memo.forget("root", "session");
|
|
173
|
+
release();
|
|
174
|
+
assert.deepEqual(await pending, { dir: "d1", channelDir: "c1" });
|
|
175
|
+
assert.deepEqual(await memo.resolve("root", "session", choose), { dir: "d2", channelDir: "c2" }, `${invalidate}: stale choice was remembered`);
|
|
176
|
+
assert.equal(calls, 2);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test("the memo is a bounded LRU", async () => {
|
|
181
|
+
const memo = new WriteDirMemo(2);
|
|
182
|
+
const chooser = (name: string) => async () => ({ dir: name, channelDir: name });
|
|
183
|
+
await memo.resolve("r", "a", chooser("a1"));
|
|
184
|
+
await memo.resolve("r", "b", chooser("b1"));
|
|
185
|
+
await memo.resolve("r", "a", chooser("unused")); // touch a so b is the oldest
|
|
186
|
+
await memo.resolve("r", "c", chooser("c1")); // evicts b
|
|
187
|
+
assert.equal((await memo.resolve("r", "a", chooser("a2"))).dir, "a1");
|
|
188
|
+
assert.equal((await memo.resolve("r", "b", chooser("b2"))).dir, "b2");
|
|
189
|
+
assert.throws(() => new WriteDirMemo(0), RangeError);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
const ALICE = "agent:alice:discord:channel:123";
|
|
193
|
+
const BOB = "agent:bob:discord:channel:123";
|
|
194
|
+
|
|
195
|
+
async function sessionsIn(dir: string): Promise<string[]> {
|
|
196
|
+
const text = await jsonlContents(dir);
|
|
197
|
+
return [ALICE, BOB].filter((key) => text.includes(`"sessionKey":"${key}"`));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
test("two sessions that share a primary directory never share a directory, even when their first appends overlap", async () => {
|
|
201
|
+
await withManager(async ({ manager, root }) => {
|
|
202
|
+
const alice = manager.getTranscriptPath(ALICE);
|
|
203
|
+
const bob = manager.getTranscriptPath(BOB);
|
|
204
|
+
assert.equal(alice.dir, bob.dir, "the keys must map to one primary directory for this test");
|
|
205
|
+
await Promise.allSettled([manager.append(entry(ALICE, "a1")), manager.append(entry(BOB, "b1"))]);
|
|
206
|
+
for (const n of [2, 3, 4]) {
|
|
207
|
+
await manager.append(entry(ALICE, `a${n}`));
|
|
208
|
+
await manager.append(entry(BOB, `b${n}`));
|
|
209
|
+
}
|
|
210
|
+
let rows = 0;
|
|
211
|
+
for (const dir of [alice.dir, alice.alternateDir, bob.alternateDir]) {
|
|
212
|
+
const owners = await sessionsIn(path.join(root, dir));
|
|
213
|
+
assert.ok(owners.length <= 1, `${dir} holds rows of ${owners.length} sessions`);
|
|
214
|
+
rows += (await jsonlContents(path.join(root, dir))).split("\n").filter(Boolean).length;
|
|
215
|
+
}
|
|
216
|
+
assert.equal(rows, 8, "every row must be written once");
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
test("a directory emptied by cleanup and claimed by another session is re-checked by the first session", async () => {
|
|
221
|
+
await withManager(async ({ manager, root }) => {
|
|
222
|
+
const alice = manager.getTranscriptPath(ALICE);
|
|
223
|
+
// Alice's only file is from a past day, so cleanup() will delete it and empty the directory.
|
|
224
|
+
mock.timers.enable({ apis: ["Date"], now: Date.UTC(2026, 0, 1, 12) });
|
|
225
|
+
try {
|
|
226
|
+
await manager.append(entry(ALICE, "a1"));
|
|
227
|
+
} finally {
|
|
228
|
+
mock.timers.reset();
|
|
229
|
+
}
|
|
230
|
+
assert.equal(await manager.cleanup(30), 1);
|
|
231
|
+
await manager.append(entry(BOB, "b1")); // claims the emptied directory
|
|
232
|
+
await manager.append(entry(ALICE, "a2"));
|
|
233
|
+
assert.deepEqual(await sessionsIn(path.join(root, alice.dir)), [BOB]);
|
|
234
|
+
assert.ok((await jsonlContents(path.join(root, alice.alternateDir))).includes('"turnId":"a2"'));
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("cleanup drops the remembered directories after deleting a single file", async () => {
|
|
239
|
+
await withManager(async ({ manager, root }) => {
|
|
240
|
+
const owner = "pi-geek:memo-one-file";
|
|
241
|
+
const channelDir = path.join(root, manager.getTranscriptPath(owner).dir);
|
|
242
|
+
await writeOldDays(channelDir, owner, 1);
|
|
243
|
+
await manager.append(entry(owner, "g1"));
|
|
244
|
+
assert.equal(await manager.cleanup(30), 1);
|
|
245
|
+
const verify = mock.method(JsonlOwnershipDigestCache.prototype, "verify");
|
|
246
|
+
try {
|
|
247
|
+
await manager.append(entry(owner, "g2"));
|
|
248
|
+
assert.ok(verify.mock.callCount() >= 1, "the directory was not verified again after a one-file cleanup");
|
|
249
|
+
} finally {
|
|
250
|
+
verify.mock.restore();
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test("removing() drops every remembered directory once the removal has run", async () => {
|
|
256
|
+
const memo = new WriteDirMemo();
|
|
257
|
+
let calls = 0;
|
|
258
|
+
const choose = async () => ({ dir: `d${++calls}`, channelDir: "c" });
|
|
259
|
+
await memo.resolve("root", "session", choose);
|
|
260
|
+
let removed = false;
|
|
261
|
+
await memo.removing(async () => {
|
|
262
|
+
assert.equal((await memo.resolve("root", "session", choose)).dir, "d1", "still remembered while the removal runs");
|
|
263
|
+
removed = true;
|
|
264
|
+
});
|
|
265
|
+
assert.ok(removed);
|
|
266
|
+
assert.equal((await memo.resolve("root", "session", choose)).dir, "d2");
|
|
267
|
+
await assert.rejects(memo.removing(async () => { throw new Error("unlink failed"); }), /unlink failed/);
|
|
268
|
+
assert.equal((await memo.resolve("root", "session", choose)).dir, "d3", "a failed removal may still have emptied a directory");
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
test("run() queues a session's first append behind earlier ones for the same primary directory, and lets remembered sessions through", async () => {
|
|
272
|
+
const memo = new WriteDirMemo();
|
|
273
|
+
const order: string[] = [];
|
|
274
|
+
let releaseFirst: () => void = () => {};
|
|
275
|
+
const gate = new Promise<void>((resolve) => {
|
|
276
|
+
releaseFirst = resolve;
|
|
277
|
+
});
|
|
278
|
+
const first = memo.run("root", "s1", "primary", async () => {
|
|
279
|
+
order.push("first start");
|
|
280
|
+
await gate;
|
|
281
|
+
order.push("first end");
|
|
282
|
+
await memo.resolve("root", "s1", async () => ({ dir: "p", channelDir: "p" }));
|
|
283
|
+
});
|
|
284
|
+
const second = memo.run("root", "s2", "primary", async () => {
|
|
285
|
+
order.push("second start");
|
|
286
|
+
});
|
|
287
|
+
const otherDir = memo.run("root", "s3", "elsewhere", async () => {
|
|
288
|
+
order.push("other dir");
|
|
289
|
+
});
|
|
290
|
+
await otherDir;
|
|
291
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
292
|
+
assert.deepEqual(order, ["first start", "other dir"], "second must wait for first");
|
|
293
|
+
releaseFirst();
|
|
294
|
+
await Promise.all([first, second]);
|
|
295
|
+
assert.deepEqual(order, ["first start", "other dir", "first end", "second start"]);
|
|
296
|
+
assert.equal(memo.pendingLanes, 0, "idle lanes must be pruned");
|
|
297
|
+
// s1 is remembered now, so it runs immediately even while another run holds the lane
|
|
298
|
+
const holder = memo.run("root", "s4", "primary", () => new Promise<void>(() => {}));
|
|
299
|
+
void holder;
|
|
300
|
+
const outcome = await Promise.race([
|
|
301
|
+
memo.run("root", "s1", "primary", async () => {
|
|
302
|
+
order.push("remembered");
|
|
303
|
+
}).then(() => "ran"),
|
|
304
|
+
new Promise((resolve) => setTimeout(() => resolve("blocked"), 200)),
|
|
305
|
+
]);
|
|
306
|
+
assert.equal(outcome, "ran");
|
|
307
|
+
assert.equal(order.at(-1), "remembered");
|
|
308
|
+
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/** One entry per session, ~200 B each. */
|
|
4
|
+
export const DEFAULT_WRITE_DIR_MEMO_ENTRIES = 4096;
|
|
5
|
+
|
|
6
|
+
export interface WriteDirChoice {
|
|
7
|
+
dir: string;
|
|
8
|
+
channelDir: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Remembers which storage directory a session's appends were verified to own,
|
|
13
|
+
* so only a session's first append in a process pays the directory ownership
|
|
14
|
+
* check (a full read of every daily file). The key holds the session key as a
|
|
15
|
+
* digest so caller-chosen keys cannot inflate memory; the map is an LRU.
|
|
16
|
+
*
|
|
17
|
+
* The remembered choice is not re-derived from the bytes. A file edited on
|
|
18
|
+
* disk behind the process is noticed on the session's first append after a
|
|
19
|
+
* restart or after an append error ({@link forget}), not on every append.
|
|
20
|
+
*/
|
|
21
|
+
export class WriteDirMemo {
|
|
22
|
+
private readonly entries = new Map<string, WriteDirChoice>();
|
|
23
|
+
/** Bumped by every invalidation; a choice that was pending across one is not remembered. */
|
|
24
|
+
private generation = 0;
|
|
25
|
+
/** Tail of the queue of memo-miss runs, per primary directory. */
|
|
26
|
+
private readonly lanes = new Map<string, Promise<void>>();
|
|
27
|
+
|
|
28
|
+
constructor(private readonly maxEntries: number = DEFAULT_WRITE_DIR_MEMO_ENTRIES) {
|
|
29
|
+
if (!Number.isInteger(maxEntries) || maxEntries < 1) {
|
|
30
|
+
throw new RangeError("maxEntries must be a positive integer");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Primary directories with a first append queued or running; empty when idle. */
|
|
35
|
+
get pendingLanes(): number {
|
|
36
|
+
return this.lanes.size;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The remembered choice for the session, else the result of `choose` (remembered when it resolves). */
|
|
40
|
+
async resolve(root: string, sessionKey: string, choose: () => Promise<WriteDirChoice>): Promise<WriteDirChoice> {
|
|
41
|
+
const key = this.keyFor(root, sessionKey);
|
|
42
|
+
const hit = this.entries.get(key);
|
|
43
|
+
if (hit) {
|
|
44
|
+
this.entries.delete(key);
|
|
45
|
+
this.entries.set(key, hit);
|
|
46
|
+
return hit;
|
|
47
|
+
}
|
|
48
|
+
const generation = this.generation;
|
|
49
|
+
const chosen = await choose();
|
|
50
|
+
if (generation !== this.generation) return chosen;
|
|
51
|
+
this.entries.set(key, chosen);
|
|
52
|
+
if (this.entries.size > this.maxEntries) {
|
|
53
|
+
const oldest = this.entries.keys().next();
|
|
54
|
+
if (!oldest.done) this.entries.delete(oldest.value);
|
|
55
|
+
}
|
|
56
|
+
return chosen;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Run a session's append. A session whose directory is already remembered
|
|
61
|
+
* runs at once. Any other session's first append runs after the earlier
|
|
62
|
+
* first appends that share its primary directory: two sessions that map to
|
|
63
|
+
* one directory (two agents in one channel) must not both find it empty and
|
|
64
|
+
* both claim it, so the second check has to see the first session's row.
|
|
65
|
+
*/
|
|
66
|
+
async run<T>(root: string, sessionKey: string, primaryDir: string, fn: () => Promise<T>): Promise<T> {
|
|
67
|
+
if (this.entries.has(this.keyFor(root, sessionKey))) return fn();
|
|
68
|
+
const lane = `${root}\0${primaryDir}`;
|
|
69
|
+
const result = (this.lanes.get(lane) ?? Promise.resolve()).then(fn);
|
|
70
|
+
const tail = result.then(
|
|
71
|
+
() => undefined,
|
|
72
|
+
() => undefined,
|
|
73
|
+
);
|
|
74
|
+
this.lanes.set(lane, tail);
|
|
75
|
+
try {
|
|
76
|
+
return await result;
|
|
77
|
+
} finally {
|
|
78
|
+
if (this.lanes.get(lane) === tail) this.lanes.delete(lane);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Run a file removal, then drop every remembered directory: the removal may have emptied one that another session can now claim. */
|
|
83
|
+
async removing<T>(remove: () => Promise<T>): Promise<T> {
|
|
84
|
+
try {
|
|
85
|
+
return await remove();
|
|
86
|
+
} finally {
|
|
87
|
+
this.clear();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
clear(): void {
|
|
92
|
+
this.generation++;
|
|
93
|
+
this.entries.clear();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
forget(root: string, sessionKey: string): void {
|
|
97
|
+
this.generation++;
|
|
98
|
+
this.entries.delete(this.keyFor(root, sessionKey));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private keyFor(root: string, sessionKey: string): string {
|
|
102
|
+
return `${root}\0${createHash("sha256").update(sessionKey).digest("hex")}`;
|
|
103
|
+
}
|
|
104
|
+
}
|
package/src/transcript.ts
CHANGED
|
@@ -8,6 +8,8 @@ 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 { WriteDirMemo } from "./transcript-write-dir-memo.js";
|
|
12
|
+
import { RECENT_SKEW_MS, mapLimited, readLinesSince, readNewestFromFiles } from "./transcript-recent.js";
|
|
11
13
|
|
|
12
14
|
type DirectorySessionStatus = "missing" | "empty" | "matches" | "occupied";
|
|
13
15
|
|
|
@@ -84,6 +86,8 @@ export class TranscriptManager {
|
|
|
84
86
|
}
|
|
85
87
|
>();
|
|
86
88
|
private ownershipDigests = new JsonlOwnershipDigestCache();
|
|
89
|
+
/** Per-session verified write dir: only a session's first append pays the directory ownership read. */
|
|
90
|
+
private writeDirs = new WriteDirMemo();
|
|
87
91
|
|
|
88
92
|
/** Default checkpoint TTL in hours */
|
|
89
93
|
private static readonly DEFAULT_CHECKPOINT_TTL_HOURS = 24;
|
|
@@ -520,6 +524,11 @@ export class TranscriptManager {
|
|
|
520
524
|
return /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(filename);
|
|
521
525
|
}
|
|
522
526
|
|
|
527
|
+
/** Drop the remembered write dirs so every session's next append re-verifies directory ownership. */
|
|
528
|
+
resetWriteDirs(): void {
|
|
529
|
+
this.writeDirs.clear();
|
|
530
|
+
}
|
|
531
|
+
|
|
523
532
|
/**
|
|
524
533
|
* Append a turn to the appropriate transcript file.
|
|
525
534
|
* Files are stored hierarchically: transcripts/{channelType}/{channelId}.jsonl
|
|
@@ -535,23 +544,22 @@ export class TranscriptManager {
|
|
|
535
544
|
return;
|
|
536
545
|
}
|
|
537
546
|
|
|
538
|
-
|
|
539
|
-
this.transcriptsDir,
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
alternateDir,
|
|
544
|
-
);
|
|
545
|
-
const filePath = await resolveSafeStoragePath(this.transcriptsDir, writeDir, file);
|
|
547
|
+
await this.writeDirs.run(this.transcriptsDir, entry.sessionKey, dir, async () => {
|
|
548
|
+
const { dir: writeDir, channelDir } = await this.writeDirs.resolve(this.transcriptsDir, entry.sessionKey, () =>
|
|
549
|
+
this.selectStorageDirForWrite(this.transcriptsDir, dir, legacyDir, entry.sessionKey, alternateDir),
|
|
550
|
+
);
|
|
551
|
+
const filePath = await resolveSafeStoragePath(this.transcriptsDir, writeDir, file);
|
|
546
552
|
|
|
547
|
-
|
|
548
|
-
|
|
553
|
+
// Ensure channel directory exists
|
|
554
|
+
await mkdir(channelDir, { recursive: true });
|
|
549
555
|
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
556
|
+
const line = JSON.stringify(entry) + "\n";
|
|
557
|
+
await appendFile(filePath, line, "utf-8");
|
|
558
|
+
log.debug(`appended transcript entry for ${entry.sessionKey}: ${entry.turnId}`);
|
|
559
|
+
});
|
|
553
560
|
} catch (err) {
|
|
554
561
|
log.error("failed to append transcript entry:", err);
|
|
562
|
+
this.writeDirs.forget(this.transcriptsDir, entry.sessionKey);
|
|
555
563
|
throw err;
|
|
556
564
|
}
|
|
557
565
|
}
|
|
@@ -559,52 +567,31 @@ export class TranscriptManager {
|
|
|
559
567
|
/**
|
|
560
568
|
* Get all transcript files from the hierarchical directory structure.
|
|
561
569
|
* Recursively finds all .jsonl files in transcripts/{channelType}/{channelId}/ subdirectories.
|
|
570
|
+
* Directories are listed concurrently: a large store has ~17k channel directories and a
|
|
571
|
+
* sequential walk spent ~1.5 s on round trips alone. Results keep readdir order.
|
|
562
572
|
*/
|
|
563
573
|
private async getAllTranscriptFiles(): Promise<string[]> {
|
|
564
|
-
const
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
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);
|
|
574
|
+
const isJsonl = (name: string): boolean => name.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(name);
|
|
575
|
+
// Directory doesn't exist or is unreadable: skip it.
|
|
576
|
+
const top = await readdir(this.transcriptsDir, { withFileTypes: true }).catch(() => []);
|
|
577
|
+
const perTop = await Promise.all(top.map(async (entry): Promise<string[]> => {
|
|
578
|
+
// Legacy flat file - still include for backward compatibility
|
|
579
|
+
if (!entry.isDirectory()) return entry.isFile() && isJsonl(entry.name) ? [entry.name] : [];
|
|
580
|
+
// A channel type directory (discord, slack, cron, main, etc.)
|
|
581
|
+
const channelTypeDir = path.join(this.transcriptsDir, entry.name);
|
|
582
|
+
const children = await readdir(channelTypeDir, { withFileTypes: true }).catch(() => []);
|
|
583
|
+
const perChild = await mapLimited(children, async (child): Promise<string[]> => {
|
|
584
|
+
if (child.isDirectory()) {
|
|
585
|
+
// A channel ID directory - contains daily transcript files
|
|
586
|
+
const channelFiles = await readdir(path.join(channelTypeDir, child.name)).catch(() => []);
|
|
587
|
+
return channelFiles.filter(isJsonl).map((file) => path.join(entry.name, child.name, file));
|
|
601
588
|
}
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
return
|
|
589
|
+
// Legacy: channel type dir contains .jsonl files directly
|
|
590
|
+
return child.isFile() && isJsonl(child.name) ? [path.join(entry.name, child.name)] : [];
|
|
591
|
+
});
|
|
592
|
+
return perChild.flat();
|
|
593
|
+
}));
|
|
594
|
+
return perTop.flat();
|
|
608
595
|
}
|
|
609
596
|
|
|
610
597
|
/**
|
|
@@ -641,8 +628,9 @@ export class TranscriptManager {
|
|
|
641
628
|
for (const relativePath of transcriptFiles) {
|
|
642
629
|
const filePath = path.join(this.transcriptsDir, relativePath);
|
|
643
630
|
try {
|
|
644
|
-
const
|
|
645
|
-
|
|
631
|
+
const lines = skipFilesDatedBefore !== undefined
|
|
632
|
+
? await readLinesSince(filePath, start.getTime() - RECENT_SKEW_MS)
|
|
633
|
+
: (await readFile(filePath, "utf-8")).trim().split("\n").filter(Boolean);
|
|
646
634
|
|
|
647
635
|
for (const line of lines) {
|
|
648
636
|
try {
|
|
@@ -682,9 +670,13 @@ export class TranscriptManager {
|
|
|
682
670
|
* Read the last N hours of transcript.
|
|
683
671
|
*
|
|
684
672
|
* 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
|
|
673
|
+
* every channel is scanned but daily files older than the window (less a day of clock skew) are skipped,
|
|
674
|
+
* and each file is read from its tail. With `maxEntries` and no sessionKey, only the newest `maxEntries`
|
|
675
|
+
* entries are returned (what a caller that keeps `slice(-maxEntries)` would see) and files are visited
|
|
676
|
+
* newest-modified first, stopping once no remaining file can hold a newer entry. The per-file read cap of
|
|
677
|
+
* 48 applies per channel-type directory, not globally.
|
|
686
678
|
*/
|
|
687
|
-
async readRecent(hours: number, sessionKey?: string): Promise<TranscriptEntry[]> {
|
|
679
|
+
async readRecent(hours: number, sessionKey?: string, maxEntries?: number): Promise<TranscriptEntry[]> {
|
|
688
680
|
const now = new Date();
|
|
689
681
|
// The recent-read window is inclusive of "now": a turn that is buffered and
|
|
690
682
|
// then immediately read back can carry the same millisecond timestamp as
|
|
@@ -700,9 +692,24 @@ export class TranscriptManager {
|
|
|
700
692
|
if (sessionKey) {
|
|
701
693
|
return this.readRecentForSession(start, end, sessionKey);
|
|
702
694
|
}
|
|
695
|
+
if (maxEntries !== undefined && Number.isInteger(maxEntries) && maxEntries >= 1) {
|
|
696
|
+
return this.readNewestEntries(start, end, maxEntries);
|
|
697
|
+
}
|
|
703
698
|
return this.readRange(start.toISOString(), end.toISOString(), undefined, new Date(start.getTime() - 86_400_000).toISOString().slice(0, 10));
|
|
704
699
|
}
|
|
705
700
|
|
|
701
|
+
/** Newest `limit` entries in `[start, end)` across every channel; see {@link readRecent}. */
|
|
702
|
+
private async readNewestEntries(start: Date, end: Date, limit: number): Promise<TranscriptEntry[]> {
|
|
703
|
+
const minDate = new Date(start.getTime() - 86_400_000).toISOString().slice(0, 10);
|
|
704
|
+
try {
|
|
705
|
+
const files = (await this.getAllTranscriptFiles()).filter((f) => !isDailyFileDatedBefore(f, minDate));
|
|
706
|
+
return await readNewestFromFiles(this.transcriptsDir, files, start, end, limit);
|
|
707
|
+
} catch (err) {
|
|
708
|
+
log.error("failed to read newest transcript entries:", err);
|
|
709
|
+
return [];
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
706
713
|
/**
|
|
707
714
|
* Optimized read for a specific session: only looks in that session's channel
|
|
708
715
|
* directory and only reads files whose date falls within the lookback window.
|
|
@@ -815,7 +822,7 @@ export class TranscriptManager {
|
|
|
815
822
|
|
|
816
823
|
if (!isNaN(fileDate.getTime()) && fileDate < cutoff) {
|
|
817
824
|
try {
|
|
818
|
-
await unlink(filePath);
|
|
825
|
+
await this.writeDirs.removing(() => unlink(filePath));
|
|
819
826
|
processed++;
|
|
820
827
|
log.debug(`deleted old daily transcript file: ${entry.name}/${channelTypeEntry.name}/${file}`);
|
|
821
828
|
} catch (err) {
|
|
@@ -854,7 +861,7 @@ export class TranscriptManager {
|
|
|
854
861
|
if (!isNaN(fileDate.getTime()) && fileDate < cutoff) {
|
|
855
862
|
const filePath = path.join(this.transcriptsDir, entry.name);
|
|
856
863
|
try {
|
|
857
|
-
await unlink(filePath);
|
|
864
|
+
await this.writeDirs.removing(() => unlink(filePath));
|
|
858
865
|
processed++;
|
|
859
866
|
log.debug(`deleted old legacy transcript file: ${entry.name}`);
|
|
860
867
|
} catch (err) {
|
|
@@ -908,7 +915,7 @@ export class TranscriptManager {
|
|
|
908
915
|
if (validLines.length === 0) {
|
|
909
916
|
// No valid entries left, delete the file
|
|
910
917
|
try {
|
|
911
|
-
await unlink(filePath);
|
|
918
|
+
await this.writeDirs.removing(() => unlink(filePath));
|
|
912
919
|
log.debug(`deleted empty transcript file: ${filePath}`);
|
|
913
920
|
return true;
|
|
914
921
|
} catch (err) {
|