@remnic/core 10.0.111 → 10.0.113
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 +58 -57
- package/dist/access-cli.js +58 -57
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush.js +58 -57
- package/dist/access-http-briefing.js +58 -57
- package/dist/access-http-query.js +58 -57
- package/dist/access-http.js +58 -57
- package/dist/access-identity-continuity-surface.js +58 -57
- package/dist/access-lcm-surface.js +58 -57
- package/dist/access-mcp.js +58 -57
- package/dist/access-observe-write-category.js +5 -5
- package/dist/access-observe-write-surface.js +58 -57
- package/dist/access-operations-batch.js +58 -57
- package/dist/access-operations.js +58 -57
- package/dist/access-recall-concurrency.js +58 -57
- package/dist/access-recall-response.js +58 -57
- package/dist/access-recall-surface.js +58 -57
- package/dist/access-schema.js +4 -4
- package/dist/access-service.js +58 -57
- package/dist/active-recall.js +7 -7
- package/dist/briefing.js +8 -8
- package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
- package/dist/causal-consolidation.js +9 -9
- package/dist/{chunk-WDAIXMEU.js → chunk-4N7L2N54.js} +70 -70
- package/dist/{chunk-F32RH72R.js → chunk-5RONA5FF.js} +26 -16
- package/dist/chunk-5RONA5FF.js.map +1 -0
- package/dist/{chunk-PBE7NFB5.js → chunk-BNQJKWWZ.js} +4 -4
- package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
- package/dist/{chunk-LFPGCYXE.js → chunk-C2KBLOKE.js} +2 -2
- package/dist/{chunk-Z64ANMII.js → chunk-C6WVKVHZ.js} +2 -2
- package/dist/{chunk-UY3JSQ7H.js → chunk-CTQ2XD4R.js} +2 -2
- package/dist/{chunk-XNI3URDR.js → chunk-D5F3D7DA.js} +2 -2
- package/dist/{chunk-FYQUUIPI.js → chunk-DLZGSZVC.js} +4 -4
- package/dist/{chunk-YK6SFDP2.js → chunk-DOJBV6WR.js} +4 -4
- package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
- package/dist/{chunk-I5PCMNN5.js → chunk-EKWS6NCF.js} +3 -3
- package/dist/{chunk-XSFDRM2P.js → chunk-G6TDGYVC.js} +2 -2
- package/dist/{chunk-TR4HFZBD.js → chunk-GRS34Y7V.js} +2 -2
- package/dist/{chunk-BZAI3ETM.js → chunk-HM62567O.js} +2 -2
- package/dist/{chunk-AJCXPMDA.js → chunk-IOLFR3JJ.js} +2 -2
- package/dist/{chunk-F6GNH5UY.js → chunk-J5MBTYDO.js} +2 -2
- package/dist/{chunk-HRMOKGQM.js → chunk-JCKN3E6Y.js} +2 -2
- package/dist/{chunk-E5DYZM56.js → chunk-JTO63AXR.js} +2 -2
- package/dist/{chunk-G7QANNRD.js → chunk-KPFOFT4I.js} +2 -2
- package/dist/{chunk-R3LYKUZH.js → chunk-NRZJKDGO.js} +2 -2
- package/dist/{chunk-X3HLHS5E.js → chunk-O5DO5LXA.js} +13 -13
- package/dist/{chunk-BFRNDOHO.js → chunk-OSYHJCLK.js} +2 -2
- package/dist/{chunk-P3AQ2YSX.js → chunk-PFUXPTBT.js} +4 -4
- package/dist/chunk-PQVLF42S.js +87 -0
- package/dist/chunk-PQVLF42S.js.map +1 -0
- package/dist/{chunk-YQ7H7P4Y.js → chunk-Q7UY2CSW.js} +7 -7
- package/dist/{chunk-R2DOFBG4.js → chunk-QNTBJKTN.js} +2 -2
- package/dist/{chunk-27YNNLRB.js → chunk-QYN6I3CG.js} +2 -2
- package/dist/{chunk-KQAFEZQX.js → chunk-R45L4TV6.js} +6 -6
- package/dist/{chunk-25JBIXAV.js → chunk-R76L66OW.js} +3 -3
- package/dist/{chunk-INXS64LQ.js → chunk-RJTHGVO3.js} +2 -2
- package/dist/{chunk-HWMIXG3J.js → chunk-RLXD2L3G.js} +4 -4
- package/dist/{chunk-25BUV3TU.js → chunk-S4G7WX7Q.js} +2 -2
- package/dist/{chunk-IOTMEQUC.js → chunk-SMAPUZYV.js} +2 -2
- package/dist/{chunk-AAF7RX22.js → chunk-T4FW43AG.js} +3 -3
- package/dist/{chunk-SZXDGB32.js → chunk-T5DX6A7T.js} +2 -2
- package/dist/{chunk-Z4NOA733.js → chunk-T6H5HNA6.js} +2 -2
- package/dist/{chunk-MPIMRX3I.js → chunk-TA6IK76H.js} +2 -2
- package/dist/{chunk-6DUBULUV.js → chunk-TPAIKAT5.js} +3 -3
- package/dist/{chunk-YTNLLRHQ.js → chunk-TS34Y2T5.js} +2 -2
- package/dist/{chunk-ZAMVB4JK.js → chunk-VHWQGBXY.js} +3 -3
- package/dist/{chunk-6YXIL26Y.js → chunk-VMEFUPOM.js} +2 -2
- package/dist/{chunk-477SVZUZ.js → chunk-WP25PXBB.js} +2 -2
- package/dist/{chunk-GG3QMQEG.js → chunk-XOCAG2LF.js} +2 -2
- package/dist/{chunk-BGM7O5TD.js → chunk-YPDUSAPH.js} +2 -2
- package/dist/cli.js +58 -57
- package/dist/coding/export-okf-codegraph.js +7 -7
- package/dist/compounding/engine.js +9 -9
- package/dist/config.js +7 -7
- package/dist/connectors/codex-materialize-runner.js +8 -8
- package/dist/connectors/index.js +8 -8
- package/dist/convergence-refresh.js +10 -10
- package/dist/corpus-watermark.js +10 -10
- package/dist/deep-recall-http-glue.js +5 -5
- package/dist/entity-retrieval.js +8 -8
- package/dist/explicit-capture.js +58 -57
- package/dist/extraction.js +8 -8
- package/dist/harmonic-retrieval.js +8 -8
- package/dist/index.js +70 -69
- package/dist/lcm/engine.js +2 -2
- package/dist/lcm/index.js +5 -5
- package/dist/location/index.js +9 -9
- package/dist/maintenance/memory-governance.js +8 -8
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +8 -8
- package/dist/maintenance/rebuild-memory-projection-runner.js +10 -10
- package/dist/maintenance/rebuild-memory-projection.js +9 -9
- package/dist/namespaces/migrate.js +9 -9
- package/dist/namespaces/search.js +6 -6
- package/dist/namespaces/storage.js +8 -8
- package/dist/operator-doctor-corpus.js +11 -11
- package/dist/operator-toolkit.js +14 -14
- package/dist/orchestration/backlog-scheduler.js +59 -58
- package/dist/orchestration/backlog-scheduler.js.map +1 -1
- package/dist/orchestration/buffer-drain-runner.js +59 -58
- package/dist/orchestration/maintenance.js +16 -16
- package/dist/orchestrator.js +58 -57
- package/dist/recall-navigation.js +58 -57
- package/dist/resume-bundles.js +10 -9
- package/dist/search/factory.js +5 -5
- package/dist/search/index.js +5 -5
- package/dist/search/lancedb-backend.js +2 -2
- package/dist/search/meilisearch-backend.js +2 -2
- package/dist/search/orama-backend.js +2 -2
- package/dist/semantic-consolidation.js +9 -9
- package/dist/semantic-rule-promotion.js +8 -8
- package/dist/semantic-rule-verifier.js +8 -8
- package/dist/source-agent-qualifier.js +8 -8
- package/dist/standup/build.js +8 -8
- package/dist/storage.js +7 -7
- 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 +4 -0
- package/dist/transcript.d.ts.map +1 -1
- package/dist/transcript.js +2 -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 +8 -8
- package/dist/verified-recall.js +8 -8
- package/dist/who-knows-cli.js +9 -9
- package/dist/who-knows.js +8 -8
- package/package.json +2 -2
- package/src/transcript-ownership-digest.test.ts +8 -0
- package/src/transcript-write-dir-memo.test.ts +340 -0
- package/src/transcript-write-dir-memo.ts +104 -0
- package/src/transcript.ts +23 -16
- package/dist/chunk-F32RH72R.js.map +0 -1
- /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
- /package/dist/{chunk-WDAIXMEU.js.map → chunk-4N7L2N54.js.map} +0 -0
- /package/dist/{chunk-PBE7NFB5.js.map → chunk-BNQJKWWZ.js.map} +0 -0
- /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
- /package/dist/{chunk-LFPGCYXE.js.map → chunk-C2KBLOKE.js.map} +0 -0
- /package/dist/{chunk-Z64ANMII.js.map → chunk-C6WVKVHZ.js.map} +0 -0
- /package/dist/{chunk-UY3JSQ7H.js.map → chunk-CTQ2XD4R.js.map} +0 -0
- /package/dist/{chunk-XNI3URDR.js.map → chunk-D5F3D7DA.js.map} +0 -0
- /package/dist/{chunk-FYQUUIPI.js.map → chunk-DLZGSZVC.js.map} +0 -0
- /package/dist/{chunk-YK6SFDP2.js.map → chunk-DOJBV6WR.js.map} +0 -0
- /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
- /package/dist/{chunk-I5PCMNN5.js.map → chunk-EKWS6NCF.js.map} +0 -0
- /package/dist/{chunk-XSFDRM2P.js.map → chunk-G6TDGYVC.js.map} +0 -0
- /package/dist/{chunk-TR4HFZBD.js.map → chunk-GRS34Y7V.js.map} +0 -0
- /package/dist/{chunk-BZAI3ETM.js.map → chunk-HM62567O.js.map} +0 -0
- /package/dist/{chunk-AJCXPMDA.js.map → chunk-IOLFR3JJ.js.map} +0 -0
- /package/dist/{chunk-F6GNH5UY.js.map → chunk-J5MBTYDO.js.map} +0 -0
- /package/dist/{chunk-HRMOKGQM.js.map → chunk-JCKN3E6Y.js.map} +0 -0
- /package/dist/{chunk-E5DYZM56.js.map → chunk-JTO63AXR.js.map} +0 -0
- /package/dist/{chunk-G7QANNRD.js.map → chunk-KPFOFT4I.js.map} +0 -0
- /package/dist/{chunk-R3LYKUZH.js.map → chunk-NRZJKDGO.js.map} +0 -0
- /package/dist/{chunk-X3HLHS5E.js.map → chunk-O5DO5LXA.js.map} +0 -0
- /package/dist/{chunk-BFRNDOHO.js.map → chunk-OSYHJCLK.js.map} +0 -0
- /package/dist/{chunk-P3AQ2YSX.js.map → chunk-PFUXPTBT.js.map} +0 -0
- /package/dist/{chunk-YQ7H7P4Y.js.map → chunk-Q7UY2CSW.js.map} +0 -0
- /package/dist/{chunk-R2DOFBG4.js.map → chunk-QNTBJKTN.js.map} +0 -0
- /package/dist/{chunk-27YNNLRB.js.map → chunk-QYN6I3CG.js.map} +0 -0
- /package/dist/{chunk-KQAFEZQX.js.map → chunk-R45L4TV6.js.map} +0 -0
- /package/dist/{chunk-25JBIXAV.js.map → chunk-R76L66OW.js.map} +0 -0
- /package/dist/{chunk-INXS64LQ.js.map → chunk-RJTHGVO3.js.map} +0 -0
- /package/dist/{chunk-HWMIXG3J.js.map → chunk-RLXD2L3G.js.map} +0 -0
- /package/dist/{chunk-25BUV3TU.js.map → chunk-S4G7WX7Q.js.map} +0 -0
- /package/dist/{chunk-IOTMEQUC.js.map → chunk-SMAPUZYV.js.map} +0 -0
- /package/dist/{chunk-AAF7RX22.js.map → chunk-T4FW43AG.js.map} +0 -0
- /package/dist/{chunk-SZXDGB32.js.map → chunk-T5DX6A7T.js.map} +0 -0
- /package/dist/{chunk-Z4NOA733.js.map → chunk-T6H5HNA6.js.map} +0 -0
- /package/dist/{chunk-MPIMRX3I.js.map → chunk-TA6IK76H.js.map} +0 -0
- /package/dist/{chunk-6DUBULUV.js.map → chunk-TPAIKAT5.js.map} +0 -0
- /package/dist/{chunk-YTNLLRHQ.js.map → chunk-TS34Y2T5.js.map} +0 -0
- /package/dist/{chunk-ZAMVB4JK.js.map → chunk-VHWQGBXY.js.map} +0 -0
- /package/dist/{chunk-6YXIL26Y.js.map → chunk-VMEFUPOM.js.map} +0 -0
- /package/dist/{chunk-477SVZUZ.js.map → chunk-WP25PXBB.js.map} +0 -0
- /package/dist/{chunk-GG3QMQEG.js.map → chunk-XOCAG2LF.js.map} +0 -0
- /package/dist/{chunk-BGM7O5TD.js.map → chunk-YPDUSAPH.js.map} +0 -0
|
@@ -0,0 +1,340 @@
|
|
|
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
|
+
});
|
|
309
|
+
|
|
310
|
+
test("run() keeps serving a primary directory's queue after one first append fails", async () => {
|
|
311
|
+
const memo = new WriteDirMemo();
|
|
312
|
+
const failed = memo.run("root", "s1", "primary", async () => {
|
|
313
|
+
throw new Error("boom");
|
|
314
|
+
});
|
|
315
|
+
const queued = memo.run("root", "s2", "primary", async () => "ran");
|
|
316
|
+
await assert.rejects(failed, /boom/);
|
|
317
|
+
assert.equal(await queued, "ran", "a failed first append must not fail the next one in the lane");
|
|
318
|
+
assert.equal(memo.pendingLanes, 0);
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
test("cleanup drops the remembered directories when it deletes a file whose rows are all expired", async () => {
|
|
322
|
+
await withManager(async ({ manager, root }) => {
|
|
323
|
+
const owner = "pi-geek:memo-emptied-file";
|
|
324
|
+
const channelDir = path.join(root, manager.getTranscriptPath(owner).dir);
|
|
325
|
+
await mkdir(channelDir, { recursive: true });
|
|
326
|
+
// Not a YYYY-MM-DD.jsonl name, so cleanup() takes the cleanupTranscriptFile path and deletes it once nothing is left.
|
|
327
|
+
const old = { ...entry(owner, "old"), timestamp: "2026-01-01T00:00:00.000Z" };
|
|
328
|
+
await writeFile(path.join(channelDir, "notes.jsonl"), `${JSON.stringify(old)}\n`, "utf-8");
|
|
329
|
+
await manager.append(entry(owner, "h1"));
|
|
330
|
+
assert.equal(await manager.cleanup(30), 1);
|
|
331
|
+
assert.equal((await readdir(channelDir)).includes("notes.jsonl"), false);
|
|
332
|
+
const verify = mock.method(JsonlOwnershipDigestCache.prototype, "verify");
|
|
333
|
+
try {
|
|
334
|
+
await manager.append(entry(owner, "h2"));
|
|
335
|
+
assert.ok(verify.mock.callCount() >= 1, "the directory was not verified again after the file was deleted");
|
|
336
|
+
} finally {
|
|
337
|
+
verify.mock.restore();
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
});
|
|
@@ -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,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 { WriteDirMemo } from "./transcript-write-dir-memo.js";
|
|
11
12
|
import { RECENT_SKEW_MS, mapLimited, readLinesSince, readNewestFromFiles } from "./transcript-recent.js";
|
|
12
13
|
|
|
13
14
|
type DirectorySessionStatus = "missing" | "empty" | "matches" | "occupied";
|
|
@@ -85,6 +86,8 @@ export class TranscriptManager {
|
|
|
85
86
|
}
|
|
86
87
|
>();
|
|
87
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();
|
|
88
91
|
|
|
89
92
|
/** Default checkpoint TTL in hours */
|
|
90
93
|
private static readonly DEFAULT_CHECKPOINT_TTL_HOURS = 24;
|
|
@@ -521,6 +524,11 @@ export class TranscriptManager {
|
|
|
521
524
|
return /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(filename);
|
|
522
525
|
}
|
|
523
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
|
+
|
|
524
532
|
/**
|
|
525
533
|
* Append a turn to the appropriate transcript file.
|
|
526
534
|
* Files are stored hierarchically: transcripts/{channelType}/{channelId}.jsonl
|
|
@@ -536,23 +544,22 @@ export class TranscriptManager {
|
|
|
536
544
|
return;
|
|
537
545
|
}
|
|
538
546
|
|
|
539
|
-
|
|
540
|
-
this.transcriptsDir,
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
alternateDir,
|
|
545
|
-
);
|
|
546
|
-
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);
|
|
547
552
|
|
|
548
|
-
|
|
549
|
-
|
|
553
|
+
// Ensure channel directory exists
|
|
554
|
+
await mkdir(channelDir, { recursive: true });
|
|
550
555
|
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
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
|
+
});
|
|
554
560
|
} catch (err) {
|
|
555
561
|
log.error("failed to append transcript entry:", err);
|
|
562
|
+
this.writeDirs.forget(this.transcriptsDir, entry.sessionKey);
|
|
556
563
|
throw err;
|
|
557
564
|
}
|
|
558
565
|
}
|
|
@@ -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) {
|