@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
package/src/storage.ts
CHANGED
|
@@ -22,7 +22,7 @@ import { selectArtifactMatches, type ArtifactSearchOptions } from "./artifact-se
|
|
|
22
22
|
import path from "node:path";
|
|
23
23
|
import { resolveSafeStoragePath } from "./storage-paths.js";
|
|
24
24
|
import { log } from "./logger.js";
|
|
25
|
-
import { createMemorySnapshot } from "./memory-snapshot.js";
|
|
25
|
+
import { createMemorySnapshot, loadTimeStamps } from "./memory-snapshot.js";
|
|
26
26
|
import { assertMemoryFrontmatterId, warnProjectionFallback } from "./storage-guards.js";
|
|
27
27
|
import { createTombstoneMigrationSourceContents } from "./storage/tombstone-migration-sources.js";
|
|
28
28
|
import { MemoryReadStore, readWindowedMemories, type WindowedMemoryReadOptions, type WindowedMemoryReadResult } from "./storage/memory-read-store.js";
|
|
@@ -62,7 +62,7 @@ import {
|
|
|
62
62
|
type EntityCanonicalIdMigrationHost,
|
|
63
63
|
} from "./storage/entity-canonical-id-migration-adapter.js";
|
|
64
64
|
import { EntityCanonicalIdMigrationRunner } from "./storage/entity-canonical-id-migration-runner.js";
|
|
65
|
-
import { rememberRawFrontmatter } from "./storage/memory-frontmatter-metadata.js";
|
|
65
|
+
import { readRawMemoryDocument, rememberRawFrontmatter } from "./storage/memory-frontmatter-metadata.js";
|
|
66
66
|
import { createMemoryEntityRefSerializer } from "./storage/memory-migration-serialization.js";
|
|
67
67
|
import { readEntityAliasConfigSync } from "./storage/entity-alias-config.js";
|
|
68
68
|
import { assertSafeEntityId } from "./storage/entity-id-safety.js";
|
|
@@ -4343,13 +4343,24 @@ export class StorageManager extends TombstoneBlockedCaptureIndexHost {
|
|
|
4343
4343
|
return lineCount > threshold;
|
|
4344
4344
|
}
|
|
4345
4345
|
|
|
4346
|
+
/** Loaded memories keep their file text, so the load-time snapshot is derived from it when a tier move needs it, not built per memory on every corpus read (COS-666d). */
|
|
4346
4347
|
private rememberMemorySnapshot<T extends MemoryFile | null>(memory: T): T {
|
|
4347
|
-
if (memory !== null && !StorageManager.loadedMemorySnapshots.has(memory)) {
|
|
4348
|
+
if (memory !== null && readRawMemoryDocument(memory) === undefined && !StorageManager.loadedMemorySnapshots.has(memory)) {
|
|
4348
4349
|
StorageManager.loadedMemorySnapshots.set(memory, createMemorySnapshot(memory));
|
|
4349
4350
|
}
|
|
4350
4351
|
return memory;
|
|
4351
4352
|
}
|
|
4352
4353
|
|
|
4354
|
+
/** The snapshot of `memory` as loaded, rebuilt from its retained file text; undefined when none was retained. */
|
|
4355
|
+
private snapshotFromLoadedDocument(memory: MemoryFile): string | undefined {
|
|
4356
|
+
const raw = readRawMemoryDocument(memory);
|
|
4357
|
+
const parsed = raw === undefined ? null : parseFrontmatter(raw);
|
|
4358
|
+
if (raw === undefined || !parsed) return undefined;
|
|
4359
|
+
const frontmatter = { ...parsed.frontmatter, ...loadTimeStamps(raw, parsed.frontmatter, memory.frontmatter) };
|
|
4360
|
+
const normalized = normalizeFrontmatterForPath(frontmatter, toMemoryPathRel(this.baseDir, memory.path), parsed.content);
|
|
4361
|
+
return createMemorySnapshot({ path: memory.path, frontmatter: normalized, content: parsed.content });
|
|
4362
|
+
}
|
|
4363
|
+
|
|
4353
4364
|
private rememberMemorySnapshots(memories: MemoryFile[]): MemoryFile[] {
|
|
4354
4365
|
for (const memory of memories) this.rememberMemorySnapshot(memory);
|
|
4355
4366
|
return memories;
|
|
@@ -5015,7 +5026,7 @@ export class StorageManager extends TombstoneBlockedCaptureIndexHost {
|
|
|
5015
5026
|
if (current === null && destination?.frontmatter.id === memory.frontmatter.id) return false;
|
|
5016
5027
|
throw new Error(`memory ${memory.frontmatter.id} changed before its tier move`);
|
|
5017
5028
|
}
|
|
5018
|
-
const callerSnapshot = StorageManager.loadedMemorySnapshots.get(memory);
|
|
5029
|
+
const callerSnapshot = StorageManager.loadedMemorySnapshots.get(memory) ?? this.snapshotFromLoadedDocument(memory);
|
|
5019
5030
|
const currentSnapshot = createMemorySnapshot(current);
|
|
5020
5031
|
if (
|
|
5021
5032
|
callerSnapshot === undefined
|
|
@@ -64,6 +64,7 @@ test("same-size foreign rewrite with restored mtime is never served a cached own
|
|
|
64
64
|
const primary = path.join(root, dir, file);
|
|
65
65
|
await rewriteSameSize(primary, (text) => text.replaceAll(owner, intruder));
|
|
66
66
|
|
|
67
|
+
manager.resetWriteDirs();
|
|
67
68
|
await manager.append(entry(owner, "3"));
|
|
68
69
|
|
|
69
70
|
const primaryText = await jsonlContents(path.join(root, dir));
|
|
@@ -83,6 +84,7 @@ test("same-size malformed rewrite with restored mtime is never served a cached o
|
|
|
83
84
|
const primary = path.join(root, dir, file);
|
|
84
85
|
await rewriteSameSize(primary, (text) => text.replace('{"timestamp"', '{"timestamp:'));
|
|
85
86
|
|
|
87
|
+
manager.resetWriteDirs();
|
|
86
88
|
await manager.append(entry(owner, "3"));
|
|
87
89
|
|
|
88
90
|
assert.equal((await jsonlContents(path.join(root, dir))).includes('"turnId":"3"'), false);
|
|
@@ -102,6 +104,7 @@ test("a read error after a cached owner verdict makes the directory occupied", a
|
|
|
102
104
|
await manager.append(entry(owner, "2"));
|
|
103
105
|
const primary = path.join(root, dir, file);
|
|
104
106
|
await chmod(primary, 0o000);
|
|
107
|
+
manager.resetWriteDirs();
|
|
105
108
|
try {
|
|
106
109
|
await manager.append(entry(owner, "3"));
|
|
107
110
|
} finally {
|
|
@@ -126,6 +129,7 @@ test("editing a cached prefix while the file grows is detected by content, not s
|
|
|
126
129
|
const grown = (await readFile(primary, "utf-8")) + JSON.stringify(entry(owner, "x")) + "\n";
|
|
127
130
|
await writeFile(primary, grown, "utf-8");
|
|
128
131
|
|
|
132
|
+
manager.resetWriteDirs();
|
|
129
133
|
await manager.append(entry(owner, "4"));
|
|
130
134
|
|
|
131
135
|
assert.equal((await jsonlContents(path.join(root, dir))).includes('"turnId":"4"'), false);
|
|
@@ -172,6 +176,7 @@ test("steady-state appends parse only new lines, not the accumulated history", a
|
|
|
172
176
|
assert.ok(parseSpy.mock.callCount() >= 20 * linesPerDay, "first append must verify the full history");
|
|
173
177
|
for (const id of ["a2", "a3", "a4"]) {
|
|
174
178
|
parseSpy.mock.resetCalls();
|
|
179
|
+
manager.resetWriteDirs(); // keep the directory check, and so the incremental digest path, in play
|
|
175
180
|
await manager.append(entry(owner, id));
|
|
176
181
|
const parses = parseSpy.mock.callCount();
|
|
177
182
|
assert.ok(parses <= 2, `append ${id} re-parsed ${parses} lines`);
|
|
@@ -375,12 +380,14 @@ test("warm multi-file directory: equal-size restored-mtime foreign rewrite of an
|
|
|
375
380
|
const original = await readFile(target, "utf-8");
|
|
376
381
|
await rewriteSameSize(target, (text) => text.replaceAll(owner, intruder));
|
|
377
382
|
|
|
383
|
+
manager.resetWriteDirs();
|
|
378
384
|
await manager.append(entry(owner, "after-foreign"));
|
|
379
385
|
|
|
380
386
|
assert.equal((await jsonlContents(path.join(root, dir))).includes('"turnId":"after-foreign"'), false);
|
|
381
387
|
assert.equal((await jsonlContents(path.join(root, alternateDir))).includes('"turnId":"after-foreign"'), true);
|
|
382
388
|
|
|
383
389
|
await writeFile(target, original, "utf-8");
|
|
390
|
+
manager.resetWriteDirs();
|
|
384
391
|
await manager.append(entry(owner, "after-restore"));
|
|
385
392
|
|
|
386
393
|
assert.equal((await jsonlContents(path.join(root, dir))).includes('"turnId":"after-restore"'), true);
|
|
@@ -395,6 +402,7 @@ test("warm multi-file directory: equal-size restored-mtime malformed rewrite of
|
|
|
395
402
|
const target = await warmedHistory(manager, root, owner);
|
|
396
403
|
await rewriteSameSize(target, (text) => text.replace('{"timestamp"', '{"timestamp:'));
|
|
397
404
|
|
|
405
|
+
manager.resetWriteDirs();
|
|
398
406
|
await manager.append(entry(owner, "after-malformed"));
|
|
399
407
|
|
|
400
408
|
assert.equal((await jsonlContents(path.join(root, dir))).includes('"turnId":"after-malformed"'), false);
|
|
@@ -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
|
+
}
|