agent-blackboard 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +33 -2
  2. package/dist/cli/snapshot-partition-options.d.mts +9 -0
  3. package/dist/cli/snapshot-partition-options.mjs +22 -0
  4. package/dist/cli/snapshot.mjs +93 -6
  5. package/dist/cli/usage.d.mts +1 -1
  6. package/dist/cli/usage.mjs +3 -0
  7. package/dist/client/snapshot-artifact-ownership.d.mts +13 -0
  8. package/dist/client/snapshot-artifact-ownership.mjs +140 -0
  9. package/dist/client/snapshot-artifact-removal.d.mts +14 -0
  10. package/dist/client/snapshot-artifact-removal.mjs +125 -0
  11. package/dist/client/snapshot-partition-cleanup.d.mts +3 -0
  12. package/dist/client/snapshot-partition-cleanup.mjs +125 -0
  13. package/dist/client/snapshot-partition-copy.d.mts +18 -0
  14. package/dist/client/snapshot-partition-copy.mjs +55 -0
  15. package/dist/client/snapshot-partition-format.d.mts +36 -0
  16. package/dist/client/snapshot-partition-format.mjs +133 -0
  17. package/dist/client/snapshot-partition-io.d.mts +4 -0
  18. package/dist/client/snapshot-partition-io.mjs +52 -0
  19. package/dist/client/snapshot-partition-read.d.mts +15 -0
  20. package/dist/client/snapshot-partition-read.mjs +98 -0
  21. package/dist/client/snapshot-partition-write.d.mts +18 -0
  22. package/dist/client/snapshot-partition-write.mjs +148 -0
  23. package/dist/client/snapshot-partitions.d.mts +3 -0
  24. package/dist/client/snapshot-partitions.mjs +100 -0
  25. package/dist/client/snapshots.d.mts +5 -1
  26. package/dist/client/snapshots.mjs +61 -6
  27. package/dist/client/types.d.mts +42 -4
  28. package/dist/index.d.mts +3 -1
  29. package/dist/index.mjs +2 -0
  30. package/dist/plugin/.claude-mcp.json +12 -0
  31. package/dist/plugin/.codex-plugin/plugin.json +33 -0
  32. package/dist/plugin/.mcp.json +7 -0
  33. package/dist/plugin/skills/agent-blackboard/SKILL.md +79 -0
  34. package/package.json +1 -1
@@ -0,0 +1,18 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { FileHandle } from 'node:fs/promises';
3
+ import type { SnapshotBlock } from './snapshot-partition-format.mjs';
4
+ type ExactFileStats = {
5
+ isFile(): boolean;
6
+ nlink: bigint;
7
+ dev: bigint;
8
+ ino: bigint;
9
+ size: bigint;
10
+ };
11
+ export type ExactFileIdentity = {
12
+ dev: bigint;
13
+ ino: bigint;
14
+ size: bigint;
15
+ };
16
+ export declare function assertExactFile(stats: ExactFileStats, expected: ExactFileIdentity, message: string): void;
17
+ export declare function copyBlock(block: SnapshotBlock, output: FileHandle, hash: ReturnType<typeof createHash>): Promise<void>;
18
+ export {};
@@ -0,0 +1,55 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { open } from 'node:fs/promises';
4
+ import { writeAll } from './snapshot-partition-io.mjs';
5
+ export function assertExactFile(stats, expected, message) {
6
+ if (!stats.isFile() ||
7
+ stats.nlink !== 1n ||
8
+ stats.dev !== expected.dev ||
9
+ stats.ino !== expected.ino ||
10
+ stats.size !== expected.size)
11
+ throw new Error(message);
12
+ }
13
+ export async function copyBlock(block, output, hash) {
14
+ const input = await open(block.path, constants.O_RDONLY | constants.O_NOFOLLOW);
15
+ const buffer = Buffer.allocUnsafe(64 * 1024);
16
+ try {
17
+ let identity;
18
+ try {
19
+ if (!Number.isSafeInteger(block.bytes) || block.bytes < 0)
20
+ throw new Error('staged snapshot block has an invalid size');
21
+ identity = {
22
+ dev: BigInt(block.identity.dev),
23
+ ino: BigInt(block.identity.ino),
24
+ size: BigInt(block.bytes),
25
+ };
26
+ }
27
+ catch {
28
+ throw new Error('staged snapshot block has an invalid identity');
29
+ }
30
+ const opened = await input.stat({ bigint: true });
31
+ assertExactFile(opened, identity, 'staged snapshot block changed before publication');
32
+ let copied = 0n;
33
+ for (;;) {
34
+ const remaining = identity.size - copied;
35
+ if (remaining === 0n) {
36
+ const { bytesRead } = await input.read(buffer, 0, 1);
37
+ if (bytesRead)
38
+ throw new Error('staged snapshot block changed before publication');
39
+ break;
40
+ }
41
+ const { bytesRead } = await input.read(buffer, 0, Number(remaining > buffer.length ? buffer.length : remaining));
42
+ if (!bytesRead)
43
+ throw new Error('staged snapshot block changed before publication');
44
+ const bytes = buffer.subarray(0, bytesRead);
45
+ hash.update(bytes);
46
+ await writeAll(output, bytes);
47
+ copied += BigInt(bytesRead);
48
+ }
49
+ const completed = await input.stat({ bigint: true });
50
+ assertExactFile(completed, identity, 'staged snapshot block changed before publication');
51
+ }
52
+ finally {
53
+ await input.close();
54
+ }
55
+ }
@@ -0,0 +1,36 @@
1
+ import type { SnapshotCounts, SnapshotManifest } from './types.mjs';
2
+ export type SnapshotBlock = {
3
+ sessionId: string;
4
+ path: string;
5
+ identity: {
6
+ dev: string;
7
+ ino: string;
8
+ };
9
+ bytes: number;
10
+ sessions: number;
11
+ entries: number;
12
+ };
13
+ export type SnapshotRecord = {
14
+ type: 'session';
15
+ session: Record<string, unknown>;
16
+ } | {
17
+ type: 'entry';
18
+ entry: Record<string, unknown>;
19
+ } | {
20
+ type: 'manifest';
21
+ manifest: SnapshotManifest;
22
+ };
23
+ export type SnapshotState = {
24
+ sessions: number;
25
+ entries: number;
26
+ records: number;
27
+ lastSessionCreatedAt?: number;
28
+ lastEntryCreatedAt?: number;
29
+ currentSessionId?: string;
30
+ };
31
+ export declare function snapshotLine(value: unknown): string;
32
+ export declare function countsFor(block: Pick<SnapshotBlock, 'sessions' | 'entries'>, bytes: number): SnapshotCounts;
33
+ export declare function manifestFor(manifest: SnapshotManifest, block: Pick<SnapshotBlock, 'sessions' | 'entries'>): SnapshotManifest;
34
+ export declare function parseSnapshotRecord(line: string): SnapshotRecord;
35
+ export declare function consumeSnapshotRecord(record: SnapshotRecord, state: SnapshotState): void;
36
+ export declare function assertManifest(manifest: SnapshotManifest, state: SnapshotState): void;
@@ -0,0 +1,133 @@
1
+ const SESSION_ID = /^[A-Za-z0-9._:-]+$/;
2
+ function isObject(value) {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ }
5
+ function isTimestamp(value) {
6
+ return typeof value === 'string' && Number.isFinite(Date.parse(value));
7
+ }
8
+ function isCount(value) {
9
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
10
+ }
11
+ function isSelection(value) {
12
+ if (!isObject(value) || value.archived !== false)
13
+ return false;
14
+ if (value.agent !== undefined && typeof value.agent !== 'string')
15
+ return false;
16
+ if (value.version !== undefined && typeof value.version !== 'string')
17
+ return false;
18
+ if (value.parentSessionId !== undefined &&
19
+ value.parentSessionId !== null &&
20
+ (typeof value.parentSessionId !== 'string' || !SESSION_ID.test(value.parentSessionId)))
21
+ return false;
22
+ if (value.data !== undefined && !isObject(value.data))
23
+ return false;
24
+ return (value.inactiveForHours === undefined ||
25
+ (typeof value.inactiveForHours === 'number' &&
26
+ Number.isFinite(value.inactiveForHours) &&
27
+ value.inactiveForHours > 0));
28
+ }
29
+ function isManifest(value) {
30
+ if (!isObject(value) || value.schemaVersion !== 1 || value.status !== 'complete')
31
+ return false;
32
+ if (!isTimestamp(value.createdAt) ||
33
+ !isTimestamp(value.completedAt) ||
34
+ !isSelection(value.selection))
35
+ return false;
36
+ if (!isObject(value.counts) ||
37
+ !isCount(value.counts.sessions) ||
38
+ !isCount(value.counts.entries) ||
39
+ !isCount(value.counts.records))
40
+ return false;
41
+ return (isObject(value.ordering) &&
42
+ value.ordering.sessions === 'createdAt ascending' &&
43
+ value.ordering.entries === 'createdAt ascending within session' &&
44
+ value.consistency === 'best-effort');
45
+ }
46
+ function isSession(value) {
47
+ /* v8 ignore next -- all fields are validated as one structural contract */
48
+ return (isObject(value) &&
49
+ typeof value.id === 'string' &&
50
+ SESSION_ID.test(value.id) &&
51
+ (value.parentSessionId === null ||
52
+ (typeof value.parentSessionId === 'string' && SESSION_ID.test(value.parentSessionId))) &&
53
+ typeof value.agent === 'string' &&
54
+ typeof value.version === 'string' &&
55
+ isTimestamp(value.createdAt) &&
56
+ (value.lastEntryAt === null || isTimestamp(value.lastEntryAt)) &&
57
+ value.archivedAt === null &&
58
+ isObject(value.data));
59
+ }
60
+ function isEntry(value) {
61
+ return (isObject(value) &&
62
+ typeof value.sessionId === 'string' &&
63
+ SESSION_ID.test(value.sessionId) &&
64
+ isTimestamp(value.createdAt) &&
65
+ isObject(value.data));
66
+ }
67
+ export function snapshotLine(value) {
68
+ return `${JSON.stringify(value)}\n`;
69
+ }
70
+ export function countsFor(block, bytes) {
71
+ return {
72
+ sessions: block.sessions,
73
+ entries: block.entries,
74
+ records: block.sessions + block.entries + 1,
75
+ bytes,
76
+ };
77
+ }
78
+ export function manifestFor(manifest, block) {
79
+ const counts = countsFor(block, 0);
80
+ return {
81
+ ...manifest,
82
+ counts: { sessions: counts.sessions, entries: counts.entries, records: counts.records },
83
+ };
84
+ }
85
+ export function parseSnapshotRecord(line) {
86
+ let value;
87
+ try {
88
+ value = JSON.parse(line);
89
+ }
90
+ catch {
91
+ throw new Error('snapshot contains invalid JSONL');
92
+ }
93
+ if (!isObject(value))
94
+ throw new Error('snapshot contains an invalid record');
95
+ if (value.type === 'session' && isSession(value.session))
96
+ return { type: 'session', session: value.session };
97
+ if (value.type === 'entry' && isEntry(value.entry))
98
+ return { type: 'entry', entry: value.entry };
99
+ if (value.type === 'manifest' && isObject(value.manifest))
100
+ return { type: 'manifest', manifest: value.manifest };
101
+ throw new Error('snapshot contains an unsupported record');
102
+ }
103
+ export function consumeSnapshotRecord(record, state) {
104
+ if (record.type === 'manifest')
105
+ return;
106
+ if (record.type === 'session') {
107
+ const createdAt = Date.parse(record.session.createdAt);
108
+ if (state.lastSessionCreatedAt !== undefined && createdAt < state.lastSessionCreatedAt)
109
+ throw new Error('snapshot sessions are not ordered');
110
+ state.sessions += 1;
111
+ state.records += 1;
112
+ state.lastSessionCreatedAt = createdAt;
113
+ delete state.lastEntryCreatedAt;
114
+ state.currentSessionId = record.session.id;
115
+ return;
116
+ }
117
+ const createdAt = Date.parse(record.entry.createdAt);
118
+ if (state.currentSessionId !== record.entry.sessionId)
119
+ throw new Error('snapshot entries must follow their session');
120
+ if (state.lastEntryCreatedAt !== undefined && createdAt < state.lastEntryCreatedAt)
121
+ throw new Error('snapshot entries are not ordered');
122
+ state.entries += 1;
123
+ state.records += 1;
124
+ state.lastEntryCreatedAt = createdAt;
125
+ }
126
+ export function assertManifest(manifest, state) {
127
+ if (!isManifest(manifest))
128
+ throw new Error('snapshot is missing a complete terminal manifest');
129
+ if (manifest.counts.sessions !== state.sessions ||
130
+ manifest.counts.entries !== state.entries ||
131
+ manifest.counts.records !== state.records + 1)
132
+ throw new Error('snapshot manifest counts do not match its records');
133
+ }
@@ -0,0 +1,4 @@
1
+ import type { FileHandle } from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ export declare function writeAll(file: FileHandle, bytes: Uint8Array): Promise<void>;
4
+ export declare function readLines(file: FileHandle, hash?: ReturnType<typeof createHash>, onRead?: (bytes: number) => void | Promise<void>, expectedBytes?: bigint, label?: string): AsyncGenerator<string>;
@@ -0,0 +1,52 @@
1
+ import { createHash } from 'node:crypto';
2
+ const CHUNK_SIZE = 64 * 1024;
3
+ export async function writeAll(file, bytes) {
4
+ let offset = 0;
5
+ while (offset < bytes.byteLength) {
6
+ const { bytesWritten } = await file.write(bytes, offset);
7
+ /* v8 ignore next -- a successful FileHandle write cannot make zero-byte progress */
8
+ if (bytesWritten === 0)
9
+ throw new Error('could not write snapshot partition');
10
+ offset += bytesWritten;
11
+ }
12
+ }
13
+ export async function* readLines(file, hash, onRead, expectedBytes, label = 'snapshot') {
14
+ if (expectedBytes !== undefined &&
15
+ (expectedBytes < 0n || expectedBytes > BigInt(Number.MAX_SAFE_INTEGER)))
16
+ throw new Error(`${label} has an invalid size`);
17
+ const buffer = Buffer.allocUnsafe(CHUNK_SIZE);
18
+ const decoder = new TextDecoder('utf-8', { fatal: true });
19
+ let pending = '';
20
+ let position = 0;
21
+ for (;;) {
22
+ const remaining = expectedBytes === undefined ? undefined : Number(expectedBytes) - position;
23
+ if (remaining === 0) {
24
+ const { bytesRead } = await file.read(buffer, 0, 1, position);
25
+ if (bytesRead)
26
+ throw new Error(`${label} changed during publication`);
27
+ break;
28
+ }
29
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.byteLength, remaining ?? buffer.byteLength), position);
30
+ if (!bytesRead) {
31
+ if (remaining !== undefined)
32
+ throw new Error(`${label} changed during publication`);
33
+ break;
34
+ }
35
+ position += bytesRead;
36
+ const bytes = buffer.subarray(0, bytesRead);
37
+ hash?.update(bytes);
38
+ await onRead?.(bytesRead);
39
+ pending += decoder.decode(bytes, { stream: true });
40
+ for (;;) {
41
+ const newline = pending.indexOf('\n');
42
+ if (newline < 0)
43
+ break;
44
+ yield pending.slice(0, newline);
45
+ pending = pending.slice(newline + 1);
46
+ }
47
+ }
48
+ pending += decoder.decode();
49
+ /* v8 ignore next -- the last chunk normally ends at a record boundary */
50
+ if (pending)
51
+ yield pending;
52
+ }
@@ -0,0 +1,15 @@
1
+ import type { FileHandle } from 'node:fs/promises';
2
+ import type { SnapshotManifest } from './types.mjs';
3
+ export interface StagedSnapshot {
4
+ manifest: SnapshotManifest;
5
+ bytes: number;
6
+ checksum: string;
7
+ index: string;
8
+ indexIdentity: {
9
+ dev: string;
10
+ ino: string;
11
+ size: string;
12
+ };
13
+ }
14
+ /** Reads source once through its opened descriptor and stages session groups privately on disk. */
15
+ export declare function stageSnapshot(source: FileHandle, directory: string): Promise<StagedSnapshot>;
@@ -0,0 +1,98 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { open } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { assertManifest, consumeSnapshotRecord, parseSnapshotRecord, snapshotLine, } from './snapshot-partition-format.mjs';
5
+ import { readLines, writeAll } from './snapshot-partition-io.mjs';
6
+ import { assertDirectoryIdentity, captureDirectoryIdentity } from './snapshot-artifact-removal.mjs';
7
+ /** Reads source once through its opened descriptor and stages session groups privately on disk. */
8
+ export async function stageSnapshot(source, directory) {
9
+ const directoryIdentity = await captureDirectoryIdentity(directory, 'snapshot staging directory');
10
+ const index = join(directory, 'index.jsonl');
11
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
12
+ const indexFile = await open(index, 'wx', 0o600);
13
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
14
+ const hash = createHash('sha256');
15
+ const state = { sessions: 0, entries: 0, records: 0 };
16
+ let current;
17
+ let manifest;
18
+ let ordinal = 0;
19
+ let bytes = 0;
20
+ const finish = async () => {
21
+ if (!current)
22
+ return;
23
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
24
+ await current.file.sync();
25
+ await current.file.close();
26
+ const { file: _file, ...block } = current;
27
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
28
+ await writeAll(indexFile, Buffer.from(snapshotLine(block)));
29
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
30
+ current = undefined;
31
+ };
32
+ try {
33
+ for await (const sourceLine of readLines(source, hash, (read) => {
34
+ bytes += read;
35
+ })) {
36
+ if (!sourceLine)
37
+ throw new Error('snapshot contains a blank JSONL record');
38
+ if (manifest)
39
+ throw new Error('snapshot contains records after its manifest');
40
+ const record = parseSnapshotRecord(sourceLine);
41
+ if (record.type === 'manifest') {
42
+ await finish();
43
+ manifest = record.manifest;
44
+ assertManifest(manifest, state);
45
+ continue;
46
+ }
47
+ if (record.type === 'session') {
48
+ await finish();
49
+ ordinal += 1;
50
+ const path = join(directory, `session-${ordinal}.jsonl`);
51
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
52
+ const file = await open(path, 'wx', 0o600);
53
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
54
+ const identity = await file.stat({ bigint: true });
55
+ current = {
56
+ sessionId: record.session.id,
57
+ path,
58
+ identity: { dev: String(identity.dev), ino: String(identity.ino) },
59
+ bytes: 0,
60
+ sessions: 1,
61
+ entries: 0,
62
+ file,
63
+ };
64
+ }
65
+ else if (!current)
66
+ throw new Error('snapshot entries must follow their session');
67
+ consumeSnapshotRecord(record, state);
68
+ if (record.type === 'entry')
69
+ current.entries += 1;
70
+ const bytes = Buffer.from(`${sourceLine}\n`);
71
+ await writeAll(current.file, bytes);
72
+ current.bytes += bytes.byteLength;
73
+ }
74
+ if (!manifest)
75
+ throw new Error('snapshot is missing a complete terminal manifest');
76
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
77
+ await indexFile.sync();
78
+ const indexIdentity = await indexFile.stat({ bigint: true });
79
+ await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
80
+ return {
81
+ manifest,
82
+ bytes,
83
+ checksum: hash.digest('hex'),
84
+ index,
85
+ indexIdentity: {
86
+ dev: String(indexIdentity.dev),
87
+ ino: String(indexIdentity.ino),
88
+ size: String(indexIdentity.size),
89
+ },
90
+ };
91
+ }
92
+ finally {
93
+ /* v8 ignore next -- best-effort closure must not mask parse failure */
94
+ await current?.file.close().catch(() => undefined);
95
+ /* v8 ignore next -- best-effort closure must not mask parse failure */
96
+ await indexFile.close().catch(() => undefined);
97
+ }
98
+ }
@@ -0,0 +1,18 @@
1
+ import type { SnapshotManifest, SnapshotPartition } from './types.mjs';
2
+ type PartitionFileStats = {
3
+ isFile(): boolean;
4
+ nlink: bigint;
5
+ dev: bigint;
6
+ ino: bigint;
7
+ };
8
+ export declare function assertPartitionFile(stats: PartitionFileStats, expected: {
9
+ dev: bigint;
10
+ ino: bigint;
11
+ }, message: string): void;
12
+ /** Replays private staged groups into bounded, immutable partition files. */
13
+ export declare function writePartitions(index: string, indexIdentity: {
14
+ dev: string;
15
+ ino: string;
16
+ size: string;
17
+ }, manifest: SnapshotManifest, directory: string, maxSessions: number, maxBytes: number): Promise<SnapshotPartition[]>;
18
+ export {};
@@ -0,0 +1,148 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { lstat, open, rename } from 'node:fs/promises';
4
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { countsFor, manifestFor, snapshotLine, } from './snapshot-partition-format.mjs';
6
+ import { readLines, writeAll } from './snapshot-partition-io.mjs';
7
+ import { assertDirectoryIdentity, captureDirectoryIdentity } from './snapshot-artifact-removal.mjs';
8
+ import { assertExactFile, copyBlock } from './snapshot-partition-copy.mjs';
9
+ export function assertPartitionFile(stats, expected, message) {
10
+ if (!stats.isFile() ||
11
+ stats.nlink !== 1n ||
12
+ stats.dev !== expected.dev ||
13
+ stats.ino !== expected.ino)
14
+ throw new Error(message);
15
+ }
16
+ const STAGED_BLOCK_NAME = /^session-[1-9][0-9]*\.jsonl$/;
17
+ function assertStagedBlockPath(block, index) {
18
+ if (!isAbsolute(block.path) ||
19
+ dirname(resolve(block.path)) !== dirname(resolve(index)) ||
20
+ !STAGED_BLOCK_NAME.test(basename(block.path)))
21
+ throw new Error('staged snapshot block path is invalid');
22
+ }
23
+ /** Replays private staged groups into bounded, immutable partition files. */
24
+ export async function writePartitions(index, indexIdentity, manifest, directory, maxSessions, maxBytes) {
25
+ const partitions = [];
26
+ const stageDirectory = dirname(index);
27
+ const stageIdentity = await captureDirectoryIdentity(stageDirectory, 'staging directory');
28
+ const outputIdentity = await captureDirectoryIdentity(directory, 'output directory');
29
+ const assertStage = () => assertDirectoryIdentity(stageDirectory, stageIdentity, 'staging directory');
30
+ const assertOutput = () => assertDirectoryIdentity(directory, outputIdentity, 'output directory');
31
+ await assertStage();
32
+ await assertOutput();
33
+ const indexFile = await open(index, constants.O_RDONLY | constants.O_NOFOLLOW);
34
+ await assertStage();
35
+ let expectedIndex;
36
+ try {
37
+ expectedIndex = {
38
+ dev: BigInt(indexIdentity.dev),
39
+ ino: BigInt(indexIdentity.ino),
40
+ size: BigInt(indexIdentity.size),
41
+ };
42
+ if (expectedIndex.size < 0n || expectedIndex.size > BigInt(Number.MAX_SAFE_INTEGER))
43
+ throw new Error('staged snapshot index has an invalid identity');
44
+ }
45
+ catch {
46
+ await indexFile.close();
47
+ throw new Error('staged snapshot index has an invalid identity');
48
+ }
49
+ const openedIndex = await indexFile.stat({ bigint: true });
50
+ try {
51
+ assertExactFile(openedIndex, expectedIndex, 'staged snapshot index changed before publication');
52
+ }
53
+ catch (error) {
54
+ await indexFile.close();
55
+ throw error;
56
+ }
57
+ let active;
58
+ const start = async () => {
59
+ const number = partitions.length + 1;
60
+ const temporary = join(directory, `.partition-${number}.tmp`);
61
+ await assertOutput();
62
+ const file = await open(temporary, 'wx', 0o600);
63
+ active = {
64
+ block: {
65
+ sessionId: '',
66
+ path: '',
67
+ identity: { dev: '', ino: '' },
68
+ bytes: 0,
69
+ sessions: 0,
70
+ entries: 0,
71
+ },
72
+ file,
73
+ temporary,
74
+ hash: createHash('sha256'),
75
+ };
76
+ await assertOutput();
77
+ return active;
78
+ };
79
+ const finish = async () => {
80
+ if (!active)
81
+ return;
82
+ const partitionManifest = manifestFor(manifest, active.block);
83
+ const terminal = Buffer.from(snapshotLine({ type: 'manifest', manifest: partitionManifest }));
84
+ await assertOutput();
85
+ await writeAll(active.file, terminal);
86
+ active.hash.update(terminal);
87
+ await active.file.sync();
88
+ await active.file.chmod(0o400);
89
+ await assertOutput();
90
+ const temporaryIdentity = await active.file.stat({ bigint: true });
91
+ await active.file.close();
92
+ const temporary = await lstat(active.temporary, { bigint: true });
93
+ assertPartitionFile(temporary, temporaryIdentity, 'staged partition changed before publication');
94
+ const path = join(directory, `partition-${partitions.length + 1}.jsonl`);
95
+ await assertOutput();
96
+ await rename(active.temporary, path);
97
+ const published = await lstat(path, { bigint: true });
98
+ assertPartitionFile(published, temporaryIdentity, 'partition changed during publication');
99
+ await assertOutput();
100
+ const bytes = active.block.bytes + terminal.byteLength;
101
+ partitions.push({
102
+ path,
103
+ counts: countsFor(active.block, bytes),
104
+ checksum: { algorithm: 'sha256', value: active.hash.digest('hex') },
105
+ manifest: partitionManifest,
106
+ });
107
+ active = undefined;
108
+ };
109
+ try {
110
+ for await (const sourceLine of readLines(indexFile, undefined, undefined, expectedIndex.size, 'staged snapshot index')) {
111
+ await assertStage();
112
+ const block = JSON.parse(sourceLine);
113
+ assertStagedBlockPath(block, index);
114
+ if (active && active.block.sessions + block.sessions > maxSessions)
115
+ await finish();
116
+ let candidate = {
117
+ ...block,
118
+ sessions: (active?.block.sessions ?? 0) + block.sessions,
119
+ entries: (active?.block.entries ?? 0) + block.entries,
120
+ };
121
+ let terminalBytes = Buffer.byteLength(snapshotLine({ type: 'manifest', manifest: manifestFor(manifest, candidate) }));
122
+ if (active && active.block.bytes + block.bytes + terminalBytes > maxBytes) {
123
+ await finish();
124
+ candidate = { ...block };
125
+ terminalBytes = Buffer.byteLength(snapshotLine({ type: 'manifest', manifest: manifestFor(manifest, candidate) }));
126
+ }
127
+ if (block.bytes + terminalBytes > maxBytes)
128
+ throw new Error(`snapshot session ${block.sessionId} is too large for one partition`);
129
+ const target = active ?? (await start());
130
+ target.block.sessions += block.sessions;
131
+ target.block.entries += block.entries;
132
+ target.block.bytes += block.bytes;
133
+ await copyBlock(block, target.file, target.hash);
134
+ await assertStage();
135
+ }
136
+ const completedIndex = await indexFile.stat({ bigint: true });
137
+ assertExactFile(completedIndex, expectedIndex, 'staged snapshot index changed before publication');
138
+ await finish();
139
+ await assertStage();
140
+ await assertOutput();
141
+ return partitions;
142
+ }
143
+ finally {
144
+ await indexFile.close();
145
+ /* v8 ignore next -- best-effort closure must not mask an assembly failure */
146
+ await active?.file.close().catch(() => undefined);
147
+ }
148
+ }
@@ -0,0 +1,3 @@
1
+ import type { SnapshotPartitionOptions, SnapshotPartitionResult } from './types.mjs';
2
+ /** Splits a generated snapshot into bounded, whole-session, read-only JSONL files. */
3
+ export declare function partitionSnapshot(options: SnapshotPartitionOptions): Promise<SnapshotPartitionResult>;