agent-blackboard 0.4.0 → 0.6.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.
- package/README.md +23 -7
- package/dist/cli/data-array-contains.d.mts +1 -0
- package/dist/cli/data-array-contains.mjs +19 -0
- package/dist/cli/sessions.mjs +21 -0
- package/dist/cli/snapshot-partition-options.d.mts +9 -0
- package/dist/cli/snapshot-partition-options.mjs +22 -0
- package/dist/cli/snapshot.mjs +35 -29
- package/dist/cli/usage.d.mts +1 -1
- package/dist/cli/usage.mjs +2 -2
- package/dist/client/sessions.mjs +2 -0
- package/dist/client/snapshot-artifact-ownership.d.mts +13 -0
- package/dist/client/snapshot-artifact-ownership.mjs +140 -0
- package/dist/client/snapshot-artifact-removal.d.mts +14 -0
- package/dist/client/snapshot-artifact-removal.mjs +125 -0
- package/dist/client/snapshot-partition-cleanup.d.mts +1 -1
- package/dist/client/snapshot-partition-cleanup.mjs +83 -78
- package/dist/client/snapshot-partition-copy.d.mts +18 -0
- package/dist/client/snapshot-partition-copy.mjs +55 -0
- package/dist/client/snapshot-partition-format.d.mts +4 -0
- package/dist/client/snapshot-partition-format.mjs +11 -8
- package/dist/client/snapshot-partition-io.d.mts +1 -1
- package/dist/client/snapshot-partition-io.mjs +17 -4
- package/dist/client/snapshot-partition-read.d.mts +5 -0
- package/dist/client/snapshot-partition-read.mjs +27 -2
- package/dist/client/snapshot-partition-write.d.mts +16 -1
- package/dist/client/snapshot-partition-write.mjs +78 -23
- package/dist/client/snapshot-partitions.mjs +35 -30
- package/dist/client/snapshots.mjs +53 -6
- package/dist/client/types.d.mts +10 -0
- package/dist/mcp/schemas.mjs +35 -0
- package/dist/mcp/tool-sessions.mjs +24 -1
- package/dist/mcp/tool-snapshot.mjs +11 -0
- package/dist/plugin/.claude-mcp.json +1 -1
- package/dist/plugin/.codex-plugin/plugin.json +2 -1
- package/dist/plugin/.mcp.json +6 -4
- package/dist/plugin/skills/agent-blackboard/SKILL.md +38 -15
- package/package.json +1 -1
|
@@ -1,116 +1,121 @@
|
|
|
1
1
|
import { constants } from 'node:fs';
|
|
2
|
-
import
|
|
2
|
+
import { chmod, lstat, mkdtemp, open, rename, rmdir } from 'node:fs/promises';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
|
-
import { basename,
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
if (!isAbsolute(path) ||
|
|
10
|
-
dirname(resolve(path)) !== resolve(tmpdir()) ||
|
|
11
|
-
!expression.test(basename(path)))
|
|
12
|
-
throw new Error(`${label} must be a generated temporary ${label}`);
|
|
13
|
-
}
|
|
14
|
-
async function assertOwnershipMarker(directory, identity) {
|
|
15
|
-
let marker;
|
|
4
|
+
import { basename, join } from 'node:path';
|
|
5
|
+
import { assertCleanupToken, assertGeneratedPath, assertPartitionMarker, assertSnapshotMarker, DIRECTORY_NAME, forgetCleanupToken, knownCleanupToken, snapshotMarkerPath, SOURCE_NAME, } from './snapshot-artifact-ownership.mjs';
|
|
6
|
+
import { assertDirectoryContents, removeDetached, removeDirectoryContents, restore, } from './snapshot-artifact-removal.mjs';
|
|
7
|
+
async function assertSnapshotOwnership(path, token) {
|
|
8
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
16
9
|
try {
|
|
17
|
-
|
|
18
|
-
const info = await marker.stat();
|
|
19
|
-
if (!info.isFile() || info.nlink !== 1 || (await marker.readFile('utf8')) !== `${identity}\n`)
|
|
20
|
-
throw new Error('partition directory does not contain its ownership marker');
|
|
21
|
-
}
|
|
22
|
-
catch (error) {
|
|
23
|
-
if (error.code === 'ENOENT')
|
|
24
|
-
throw new Error('partition directory does not contain its ownership marker');
|
|
25
|
-
throw error;
|
|
10
|
+
await assertSnapshotMarker(path, file, token);
|
|
26
11
|
}
|
|
27
12
|
finally {
|
|
28
|
-
|
|
29
|
-
await marker?.close().catch(() => undefined);
|
|
13
|
+
await file.close();
|
|
30
14
|
}
|
|
31
15
|
}
|
|
32
|
-
async function
|
|
16
|
+
async function removeEmpty(path) {
|
|
17
|
+
await rmdir(path).catch(() => undefined);
|
|
18
|
+
}
|
|
19
|
+
async function removeCaptured(path, expression, directory, token) {
|
|
33
20
|
const label = directory ? 'partition directory' : 'snapshot path';
|
|
34
21
|
assertGeneratedPath(path, expression, label);
|
|
35
22
|
let initial;
|
|
36
23
|
try {
|
|
37
|
-
initial = await
|
|
24
|
+
initial = await lstat(path, { bigint: true });
|
|
38
25
|
}
|
|
39
26
|
catch (error) {
|
|
40
|
-
/* v8 ignore
|
|
27
|
+
/* v8 ignore start -- only ENOENT is deterministic; other codes need an OS fault */
|
|
41
28
|
if (error.code === 'ENOENT')
|
|
42
29
|
return;
|
|
43
|
-
/* v8 ignore next -- non-ENOENT lstat failure requires an OS-level fault */
|
|
44
30
|
throw error;
|
|
31
|
+
/* v8 ignore stop */
|
|
45
32
|
}
|
|
46
|
-
/* v8 ignore
|
|
33
|
+
/* v8 ignore start -- a replacement after the preflight check is race-only */
|
|
47
34
|
if (initial.isSymbolicLink() ||
|
|
48
|
-
(!initial.isFile()
|
|
35
|
+
(!directory && !initial.isFile()) ||
|
|
49
36
|
(directory && !initial.isDirectory()) ||
|
|
50
|
-
(!directory && initial.nlink !==
|
|
37
|
+
(!directory && initial.nlink !== 1n))
|
|
51
38
|
throw new Error(`${label} is not a generated ${directory ? 'directory' : 'regular file'}`);
|
|
52
|
-
|
|
39
|
+
assertCleanupToken(token);
|
|
53
40
|
if (directory)
|
|
54
|
-
await
|
|
55
|
-
|
|
56
|
-
|
|
41
|
+
await assertPartitionMarker(path, token);
|
|
42
|
+
else
|
|
43
|
+
await assertSnapshotOwnership(path, token);
|
|
44
|
+
if (directory)
|
|
45
|
+
await assertDirectoryContents(path, label);
|
|
46
|
+
const marker = directory ? undefined : snapshotMarkerPath(path);
|
|
47
|
+
let markerIdentity;
|
|
48
|
+
if (!directory) {
|
|
49
|
+
const identity = await lstat(marker, { bigint: true });
|
|
50
|
+
/* v8 ignore next -- replacing a validated marker before this lstat is race-only */
|
|
51
|
+
if (!identity.isFile() || identity.isSymbolicLink() || identity.nlink !== 1n)
|
|
52
|
+
throw new Error(`${label} ownership marker changed`);
|
|
53
|
+
markerIdentity = identity;
|
|
54
|
+
}
|
|
55
|
+
const quarantine = await mkdtemp(join(tmpdir(), '.agent-blackboard-cleanup-'));
|
|
56
|
+
await chmod(quarantine, 0o700);
|
|
57
|
+
const captured = join(quarantine, basename(path));
|
|
58
|
+
const capturedMarker = directory ? undefined : snapshotMarkerPath(captured);
|
|
59
|
+
let moved = false;
|
|
60
|
+
let markerMoved = false;
|
|
57
61
|
try {
|
|
58
|
-
await
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
await rename(path, captured);
|
|
63
|
+
moved = true;
|
|
64
|
+
const capturedStat = await lstat(captured, { bigint: true });
|
|
65
|
+
if (capturedStat.isSymbolicLink() ||
|
|
66
|
+
capturedStat.dev !== initial.dev ||
|
|
67
|
+
capturedStat.ino !== initial.ino ||
|
|
68
|
+
capturedStat.isDirectory() !== directory ||
|
|
69
|
+
(!directory && (!capturedStat.isFile() || capturedStat.nlink !== 1n)))
|
|
70
|
+
/* v8 ignore next -- replacing the detached target between rename and stat is race-only */
|
|
67
71
|
throw new Error(`${label} changed while it was being removed`);
|
|
72
|
+
/* v8 ignore stop */
|
|
68
73
|
if (directory)
|
|
69
|
-
await
|
|
70
|
-
|
|
74
|
+
await assertPartitionMarker(captured, token);
|
|
75
|
+
else {
|
|
76
|
+
await rename(marker, capturedMarker);
|
|
77
|
+
markerMoved = true;
|
|
78
|
+
await assertSnapshotOwnership(captured, token);
|
|
79
|
+
}
|
|
80
|
+
if (directory) {
|
|
81
|
+
await removeDirectoryContents(captured, quarantine, label, initial);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
await removeDetached(capturedMarker, quarantine, `${label} ownership marker`, markerIdentity);
|
|
85
|
+
await removeDetached(captured, quarantine, label, initial);
|
|
86
|
+
}
|
|
87
|
+
await rmdir(quarantine);
|
|
88
|
+
forgetCleanupToken(path);
|
|
71
89
|
}
|
|
72
90
|
catch (error) {
|
|
73
|
-
/* v8 ignore
|
|
74
|
-
if (
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (directory) {
|
|
81
|
-
try {
|
|
82
|
-
await fileSystem.writeFile(join(tombstone, OWNERSHIP_MARKER), `${identity}\n`, {
|
|
83
|
-
flag: 'wx',
|
|
84
|
-
mode: 0o400,
|
|
85
|
-
});
|
|
86
|
-
}
|
|
87
|
-
catch (markerError) {
|
|
88
|
-
/* v8 ignore next -- a non-EEXIST marker repair failure needs an OS-level fault */
|
|
89
|
-
if (markerError.code !== 'EEXIST')
|
|
90
|
-
throw markerError;
|
|
91
|
-
}
|
|
91
|
+
/* v8 ignore start -- post-detach failures require an OS-level race or filesystem fault */
|
|
92
|
+
if (moved && !directory) {
|
|
93
|
+
try {
|
|
94
|
+
await restore(path, captured, markerMoved ? marker : undefined, capturedMarker, initial, markerIdentity);
|
|
95
|
+
}
|
|
96
|
+
catch (restoreError) {
|
|
97
|
+
throw new AggregateError([error, restoreError], 'artifact cleanup failed and target was not restored');
|
|
92
98
|
}
|
|
93
|
-
await fileSystem.rename(tombstone, path);
|
|
94
|
-
}
|
|
95
|
-
catch (restoreError) {
|
|
96
|
-
/* v8 ignore start -- restore failure requires a concurrent replacement or OS fault */
|
|
97
|
-
/* v8 ignore next -- a fully removed tombstone means cleanup ultimately succeeded */
|
|
98
|
-
if (restoreError.code === 'ENOENT')
|
|
99
|
-
return;
|
|
100
|
-
throw new AggregateError([error, restoreError], `${label} cleanup failed; retained retryable artifact at ${tombstone}`);
|
|
101
|
-
/* v8 ignore stop */
|
|
102
99
|
}
|
|
103
|
-
/* v8 ignore
|
|
100
|
+
/* v8 ignore stop */
|
|
101
|
+
/* v8 ignore next -- preserve the primary pre-detach failure */
|
|
104
102
|
throw error;
|
|
105
103
|
}
|
|
104
|
+
finally {
|
|
105
|
+
await removeEmpty(quarantine);
|
|
106
|
+
}
|
|
106
107
|
}
|
|
107
|
-
/** Removes generated snapshot and/or partition evidence
|
|
108
|
+
/** Removes generated snapshot and/or partition evidence using an explicit capability. */
|
|
108
109
|
export async function cleanupSnapshotPartitions(options) {
|
|
109
110
|
if (!options.path && !options.directory)
|
|
110
111
|
throw new Error('cleanup requires a snapshot path or partition directory');
|
|
112
|
+
const inferredToken = options.path
|
|
113
|
+
? knownCleanupToken(options.path)
|
|
114
|
+
: knownCleanupToken(options.directory);
|
|
115
|
+
const token = options.cleanupToken ?? inferredToken;
|
|
111
116
|
const results = await Promise.allSettled([
|
|
112
|
-
...(options.path ? [removeCaptured(options.path, SOURCE_NAME, false)] : []),
|
|
113
|
-
...(options.directory ? [removeCaptured(options.directory, DIRECTORY_NAME, true)] : []),
|
|
117
|
+
...(options.path ? [removeCaptured(options.path, SOURCE_NAME, false, token)] : []),
|
|
118
|
+
...(options.directory ? [removeCaptured(options.directory, DIRECTORY_NAME, true, token)] : []),
|
|
114
119
|
]);
|
|
115
120
|
const failures = results.filter((result) => result.status === 'rejected');
|
|
116
121
|
if (failures.length) {
|
|
@@ -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
|
+
}
|
|
@@ -21,6 +21,11 @@ function isSelection(value) {
|
|
|
21
21
|
return false;
|
|
22
22
|
if (value.data !== undefined && !isObject(value.data))
|
|
23
23
|
return false;
|
|
24
|
+
if (value.dataArrayContains !== undefined &&
|
|
25
|
+
(!isObject(value.dataArrayContains) ||
|
|
26
|
+
Object.keys(value.dataArrayContains).length === 0 ||
|
|
27
|
+
Object.entries(value.dataArrayContains).some(([key, item]) => key.length === 0 || typeof item !== 'string' || item.length === 0)))
|
|
28
|
+
return false;
|
|
24
29
|
return (value.inactiveForHours === undefined ||
|
|
25
30
|
(typeof value.inactiveForHours === 'number' &&
|
|
26
31
|
Number.isFinite(value.inactiveForHours) &&
|
|
@@ -104,26 +109,24 @@ export function consumeSnapshotRecord(record, state) {
|
|
|
104
109
|
if (record.type === 'manifest')
|
|
105
110
|
return;
|
|
106
111
|
if (record.type === 'session') {
|
|
107
|
-
const createdAt = record.session.createdAt;
|
|
108
|
-
|
|
109
|
-
if (state.lastSessionCreatedAt !== undefined && createdAtInstant < state.lastSessionCreatedAt)
|
|
112
|
+
const createdAt = Date.parse(record.session.createdAt);
|
|
113
|
+
if (state.lastSessionCreatedAt !== undefined && createdAt < state.lastSessionCreatedAt)
|
|
110
114
|
throw new Error('snapshot sessions are not ordered');
|
|
111
115
|
state.sessions += 1;
|
|
112
116
|
state.records += 1;
|
|
113
|
-
state.lastSessionCreatedAt =
|
|
117
|
+
state.lastSessionCreatedAt = createdAt;
|
|
114
118
|
delete state.lastEntryCreatedAt;
|
|
115
119
|
state.currentSessionId = record.session.id;
|
|
116
120
|
return;
|
|
117
121
|
}
|
|
118
|
-
const createdAt = record.entry.createdAt;
|
|
119
|
-
const createdAtInstant = Date.parse(createdAt);
|
|
122
|
+
const createdAt = Date.parse(record.entry.createdAt);
|
|
120
123
|
if (state.currentSessionId !== record.entry.sessionId)
|
|
121
124
|
throw new Error('snapshot entries must follow their session');
|
|
122
|
-
if (state.lastEntryCreatedAt !== undefined &&
|
|
125
|
+
if (state.lastEntryCreatedAt !== undefined && createdAt < state.lastEntryCreatedAt)
|
|
123
126
|
throw new Error('snapshot entries are not ordered');
|
|
124
127
|
state.entries += 1;
|
|
125
128
|
state.records += 1;
|
|
126
|
-
state.lastEntryCreatedAt =
|
|
129
|
+
state.lastEntryCreatedAt = createdAt;
|
|
127
130
|
}
|
|
128
131
|
export function assertManifest(manifest, state) {
|
|
129
132
|
if (!isManifest(manifest))
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { FileHandle } from 'node:fs/promises';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
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): AsyncGenerator<string>;
|
|
4
|
+
export declare function readLines(file: FileHandle, hash?: ReturnType<typeof createHash>, onRead?: (bytes: number) => void | Promise<void>, expectedBytes?: bigint, label?: string): AsyncGenerator<string>;
|
|
@@ -10,19 +10,32 @@ export async function writeAll(file, bytes) {
|
|
|
10
10
|
offset += bytesWritten;
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
-
export async function* readLines(file, hash, onRead) {
|
|
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`);
|
|
14
17
|
const buffer = Buffer.allocUnsafe(CHUNK_SIZE);
|
|
15
18
|
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
16
19
|
let pending = '';
|
|
17
20
|
let position = 0;
|
|
18
21
|
for (;;) {
|
|
19
|
-
const
|
|
20
|
-
if (
|
|
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`);
|
|
21
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
|
+
}
|
|
22
35
|
position += bytesRead;
|
|
23
36
|
const bytes = buffer.subarray(0, bytesRead);
|
|
24
37
|
hash?.update(bytes);
|
|
25
|
-
onRead?.(bytesRead);
|
|
38
|
+
await onRead?.(bytesRead);
|
|
26
39
|
pending += decoder.decode(bytes, { stream: true });
|
|
27
40
|
for (;;) {
|
|
28
41
|
const newline = pending.indexOf('\n');
|
|
@@ -5,6 +5,11 @@ export interface StagedSnapshot {
|
|
|
5
5
|
bytes: number;
|
|
6
6
|
checksum: string;
|
|
7
7
|
index: string;
|
|
8
|
+
indexIdentity: {
|
|
9
|
+
dev: string;
|
|
10
|
+
ino: string;
|
|
11
|
+
size: string;
|
|
12
|
+
};
|
|
8
13
|
}
|
|
9
14
|
/** Reads source once through its opened descriptor and stages session groups privately on disk. */
|
|
10
15
|
export declare function stageSnapshot(source: FileHandle, directory: string): Promise<StagedSnapshot>;
|
|
@@ -3,10 +3,14 @@ import { open } from 'node:fs/promises';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { assertManifest, consumeSnapshotRecord, parseSnapshotRecord, snapshotLine, } from './snapshot-partition-format.mjs';
|
|
5
5
|
import { readLines, writeAll } from './snapshot-partition-io.mjs';
|
|
6
|
+
import { assertDirectoryIdentity, captureDirectoryIdentity } from './snapshot-artifact-removal.mjs';
|
|
6
7
|
/** Reads source once through its opened descriptor and stages session groups privately on disk. */
|
|
7
8
|
export async function stageSnapshot(source, directory) {
|
|
9
|
+
const directoryIdentity = await captureDirectoryIdentity(directory, 'snapshot staging directory');
|
|
8
10
|
const index = join(directory, 'index.jsonl');
|
|
11
|
+
await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
|
|
9
12
|
const indexFile = await open(index, 'wx', 0o600);
|
|
13
|
+
await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
|
|
10
14
|
const hash = createHash('sha256');
|
|
11
15
|
const state = { sessions: 0, entries: 0, records: 0 };
|
|
12
16
|
let current;
|
|
@@ -16,10 +20,13 @@ export async function stageSnapshot(source, directory) {
|
|
|
16
20
|
const finish = async () => {
|
|
17
21
|
if (!current)
|
|
18
22
|
return;
|
|
23
|
+
await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
|
|
19
24
|
await current.file.sync();
|
|
20
25
|
await current.file.close();
|
|
21
26
|
const { file: _file, ...block } = current;
|
|
27
|
+
await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
|
|
22
28
|
await writeAll(indexFile, Buffer.from(snapshotLine(block)));
|
|
29
|
+
await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
|
|
23
30
|
current = undefined;
|
|
24
31
|
};
|
|
25
32
|
try {
|
|
@@ -41,13 +48,18 @@ export async function stageSnapshot(source, directory) {
|
|
|
41
48
|
await finish();
|
|
42
49
|
ordinal += 1;
|
|
43
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 });
|
|
44
55
|
current = {
|
|
45
56
|
sessionId: record.session.id,
|
|
46
57
|
path,
|
|
58
|
+
identity: { dev: String(identity.dev), ino: String(identity.ino) },
|
|
47
59
|
bytes: 0,
|
|
48
60
|
sessions: 1,
|
|
49
61
|
entries: 0,
|
|
50
|
-
file
|
|
62
|
+
file,
|
|
51
63
|
};
|
|
52
64
|
}
|
|
53
65
|
else if (!current)
|
|
@@ -61,8 +73,21 @@ export async function stageSnapshot(source, directory) {
|
|
|
61
73
|
}
|
|
62
74
|
if (!manifest)
|
|
63
75
|
throw new Error('snapshot is missing a complete terminal manifest');
|
|
76
|
+
await assertDirectoryIdentity(directory, directoryIdentity, 'snapshot staging directory');
|
|
64
77
|
await indexFile.sync();
|
|
65
|
-
|
|
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
|
+
};
|
|
66
91
|
}
|
|
67
92
|
finally {
|
|
68
93
|
/* v8 ignore next -- best-effort closure must not mask parse failure */
|
|
@@ -1,3 +1,18 @@
|
|
|
1
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;
|
|
2
12
|
/** Replays private staged groups into bounded, immutable partition files. */
|
|
3
|
-
export declare function writePartitions(index: string,
|
|
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 {};
|
|
@@ -1,40 +1,79 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { constants } from 'node:fs';
|
|
3
|
-
import {
|
|
4
|
-
import { join } from 'node:path';
|
|
3
|
+
import { lstat, open, rename } from 'node:fs/promises';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
5
5
|
import { countsFor, manifestFor, snapshotLine, } from './snapshot-partition-format.mjs';
|
|
6
6
|
import { readLines, writeAll } from './snapshot-partition-io.mjs';
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
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');
|
|
23
22
|
}
|
|
24
23
|
/** Replays private staged groups into bounded, immutable partition files. */
|
|
25
|
-
export async function writePartitions(index, manifest, directory, maxSessions, maxBytes) {
|
|
24
|
+
export async function writePartitions(index, indexIdentity, manifest, directory, maxSessions, maxBytes) {
|
|
26
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();
|
|
27
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
|
+
}
|
|
28
57
|
let active;
|
|
29
58
|
const start = async () => {
|
|
30
59
|
const number = partitions.length + 1;
|
|
31
60
|
const temporary = join(directory, `.partition-${number}.tmp`);
|
|
61
|
+
await assertOutput();
|
|
62
|
+
const file = await open(temporary, 'wx', 0o600);
|
|
32
63
|
active = {
|
|
33
|
-
block: {
|
|
34
|
-
|
|
64
|
+
block: {
|
|
65
|
+
sessionId: '',
|
|
66
|
+
path: '',
|
|
67
|
+
identity: { dev: '', ino: '' },
|
|
68
|
+
bytes: 0,
|
|
69
|
+
sessions: 0,
|
|
70
|
+
entries: 0,
|
|
71
|
+
},
|
|
72
|
+
file,
|
|
35
73
|
temporary,
|
|
36
74
|
hash: createHash('sha256'),
|
|
37
75
|
};
|
|
76
|
+
await assertOutput();
|
|
38
77
|
return active;
|
|
39
78
|
};
|
|
40
79
|
const finish = async () => {
|
|
@@ -42,13 +81,22 @@ export async function writePartitions(index, manifest, directory, maxSessions, m
|
|
|
42
81
|
return;
|
|
43
82
|
const partitionManifest = manifestFor(manifest, active.block);
|
|
44
83
|
const terminal = Buffer.from(snapshotLine({ type: 'manifest', manifest: partitionManifest }));
|
|
84
|
+
await assertOutput();
|
|
45
85
|
await writeAll(active.file, terminal);
|
|
46
86
|
active.hash.update(terminal);
|
|
47
87
|
await active.file.sync();
|
|
88
|
+
await active.file.chmod(0o400);
|
|
89
|
+
await assertOutput();
|
|
90
|
+
const temporaryIdentity = await active.file.stat({ bigint: true });
|
|
48
91
|
await active.file.close();
|
|
49
|
-
await
|
|
92
|
+
const temporary = await lstat(active.temporary, { bigint: true });
|
|
93
|
+
assertPartitionFile(temporary, temporaryIdentity, 'staged partition changed before publication');
|
|
50
94
|
const path = join(directory, `partition-${partitions.length + 1}.jsonl`);
|
|
95
|
+
await assertOutput();
|
|
51
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();
|
|
52
100
|
const bytes = active.block.bytes + terminal.byteLength;
|
|
53
101
|
partitions.push({
|
|
54
102
|
path,
|
|
@@ -59,8 +107,10 @@ export async function writePartitions(index, manifest, directory, maxSessions, m
|
|
|
59
107
|
active = undefined;
|
|
60
108
|
};
|
|
61
109
|
try {
|
|
62
|
-
for await (const sourceLine of readLines(indexFile)) {
|
|
110
|
+
for await (const sourceLine of readLines(indexFile, undefined, undefined, expectedIndex.size, 'staged snapshot index')) {
|
|
111
|
+
await assertStage();
|
|
63
112
|
const block = JSON.parse(sourceLine);
|
|
113
|
+
assertStagedBlockPath(block, index);
|
|
64
114
|
if (active && active.block.sessions + block.sessions > maxSessions)
|
|
65
115
|
await finish();
|
|
66
116
|
let candidate = {
|
|
@@ -81,8 +131,13 @@ export async function writePartitions(index, manifest, directory, maxSessions, m
|
|
|
81
131
|
target.block.entries += block.entries;
|
|
82
132
|
target.block.bytes += block.bytes;
|
|
83
133
|
await copyBlock(block, target.file, target.hash);
|
|
134
|
+
await assertStage();
|
|
84
135
|
}
|
|
136
|
+
const completedIndex = await indexFile.stat({ bigint: true });
|
|
137
|
+
assertExactFile(completedIndex, expectedIndex, 'staged snapshot index changed before publication');
|
|
85
138
|
await finish();
|
|
139
|
+
await assertStage();
|
|
140
|
+
await assertOutput();
|
|
86
141
|
return partitions;
|
|
87
142
|
}
|
|
88
143
|
finally {
|