agent-blackboard 0.3.1 → 0.4.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 +15 -0
- package/dist/cli/snapshot.mjs +99 -6
- package/dist/cli/usage.d.mts +1 -1
- package/dist/cli/usage.mjs +3 -0
- package/dist/client/snapshot-partition-cleanup.d.mts +3 -0
- package/dist/client/snapshot-partition-cleanup.mjs +120 -0
- package/dist/client/snapshot-partition-format.d.mts +32 -0
- package/dist/client/snapshot-partition-format.mjs +135 -0
- package/dist/client/snapshot-partition-io.d.mts +4 -0
- package/dist/client/snapshot-partition-io.mjs +39 -0
- package/dist/client/snapshot-partition-read.d.mts +10 -0
- package/dist/client/snapshot-partition-read.mjs +73 -0
- package/dist/client/snapshot-partition-write.d.mts +3 -0
- package/dist/client/snapshot-partition-write.mjs +93 -0
- package/dist/client/snapshot-partitions.d.mts +3 -0
- package/dist/client/snapshot-partitions.mjs +95 -0
- package/dist/client/snapshots.d.mts +5 -1
- package/dist/client/snapshots.mjs +10 -0
- package/dist/client/types.d.mts +34 -4
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +2 -0
- package/dist/plugin/.claude-mcp.json +12 -0
- package/dist/plugin/.codex-plugin/plugin.json +33 -0
- package/dist/plugin/.mcp.json +7 -0
- package/dist/plugin/skills/agent-blackboard/SKILL.md +72 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -48,6 +48,8 @@ await sessions.archive('worker-456')
|
|
|
48
48
|
// The JSONL file stays local; the result contains only its verification metadata.
|
|
49
49
|
const snapshot = await snapshots.export({ selection: { agent: 'claude-code' } })
|
|
50
50
|
console.log(snapshot.path, snapshot.checksum.value)
|
|
51
|
+
const partitions = await snapshots.partition({ path: snapshot.path, checksum: snapshot.checksum })
|
|
52
|
+
await snapshots.cleanup({ path: snapshot.path, directory: partitions.directory })
|
|
51
53
|
|
|
52
54
|
const auth = new Auth({ baseUrl, adminToken })
|
|
53
55
|
await auth.createCredentials({ name: 'ci-bot' })
|
|
@@ -76,9 +78,22 @@ agent-blackboard append --session-id worker-456 --file findings.md
|
|
|
76
78
|
agent-blackboard get --session-id worker-456 --format jsonl
|
|
77
79
|
agent-blackboard sessions archive worker-456
|
|
78
80
|
agent-blackboard snapshot export --root-only --inactive-for-hours 8
|
|
81
|
+
agent-blackboard snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl
|
|
82
|
+
agent-blackboard snapshot cleanup --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
|
|
83
|
+
--directory /tmp/agent-blackboard-partitions-<suffix>
|
|
79
84
|
agent-blackboard mcp
|
|
80
85
|
```
|
|
81
86
|
|
|
87
|
+
`partition` only accepts a generated temporary snapshot, preserves each session and its ordered
|
|
88
|
+
entries as a single unit, and defaults to 25 sessions or 1 MiB per read-only partition. It can
|
|
89
|
+
verify the export checksum and counts. `cleanup` removes either generated temporary artifact, or both.
|
|
90
|
+
An explicit absolute `snapshot export --path` destination remains caller-owned and is never accepted
|
|
91
|
+
by either command.
|
|
92
|
+
|
|
93
|
+
The published package includes the canonical provider plugin at `dist/plugin`; it is copied during
|
|
94
|
+
the package build from this repository's `plugins/agent-blackboard` source, so no second tracked
|
|
95
|
+
skill copy can drift.
|
|
96
|
+
|
|
82
97
|
## MCP
|
|
83
98
|
|
|
84
99
|
The stdio MCP server exposes `session_create`, `session_ensure`, `session_search`, `session_patch`,
|
package/dist/cli/snapshot.mjs
CHANGED
|
@@ -1,23 +1,34 @@
|
|
|
1
1
|
import { Snapshots } from '../client/snapshots.mjs';
|
|
2
|
+
import { cleanupSnapshotPartitions } from '../client/snapshot-partition-cleanup.mjs';
|
|
3
|
+
import { partitionSnapshot } from '../client/snapshot-partitions.mjs';
|
|
2
4
|
import { parseArgs, stringFlag } from './args.mjs';
|
|
3
5
|
import { clientConfigFromEnv } from './env.mjs';
|
|
4
6
|
import { CliError } from './errors.mjs';
|
|
5
7
|
import { writeLine } from './output.mjs';
|
|
6
|
-
function optionalString(flags, key) {
|
|
8
|
+
function optionalString(flags, key, command = 'snapshot export') {
|
|
7
9
|
const value = stringFlag(flags, key);
|
|
8
10
|
if (Object.hasOwn(flags, key) && !value)
|
|
9
|
-
throw new CliError(
|
|
11
|
+
throw new CliError(`${command} --${key} requires a value.`);
|
|
10
12
|
return value;
|
|
11
13
|
}
|
|
14
|
+
function bareFlag(flags, key, command) {
|
|
15
|
+
const value = flags[key];
|
|
16
|
+
if (value === undefined)
|
|
17
|
+
return false;
|
|
18
|
+
if (value !== true)
|
|
19
|
+
throw new CliError(`${command} --${key} does not accept a value.`);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
12
22
|
function parentSelection(flags) {
|
|
13
23
|
const parentSessionId = optionalString(flags, 'parent-session-id');
|
|
14
|
-
|
|
24
|
+
const rootOnly = bareFlag(flags, 'root-only', 'snapshot export');
|
|
25
|
+
if (rootOnly && parentSessionId !== undefined) {
|
|
15
26
|
throw new CliError('snapshot export --root-only cannot be combined with --parent-session-id.');
|
|
16
27
|
}
|
|
17
28
|
if (parentSessionId !== undefined && !/^[A-Za-z0-9._:-]+$/.test(parentSessionId)) {
|
|
18
29
|
throw new CliError('snapshot export --parent-session-id is invalid.');
|
|
19
30
|
}
|
|
20
|
-
if (
|
|
31
|
+
if (rootOnly)
|
|
21
32
|
return { parentSessionId: null };
|
|
22
33
|
return parentSessionId === undefined ? {} : { parentSessionId };
|
|
23
34
|
}
|
|
@@ -58,12 +69,94 @@ function selectionFrom(flags) {
|
|
|
58
69
|
...(inactiveForHours === undefined ? {} : { inactiveForHours }),
|
|
59
70
|
};
|
|
60
71
|
}
|
|
72
|
+
function requiredString(flags, key, command) {
|
|
73
|
+
return (optionalString(flags, key) ??
|
|
74
|
+
(() => {
|
|
75
|
+
throw new CliError(`${command} requires --${key}.`);
|
|
76
|
+
})());
|
|
77
|
+
}
|
|
78
|
+
function positiveInteger(flags, key) {
|
|
79
|
+
const raw = optionalString(flags, key);
|
|
80
|
+
if (raw === undefined)
|
|
81
|
+
return undefined;
|
|
82
|
+
const value = Number(raw);
|
|
83
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
84
|
+
throw new CliError(`snapshot partition --${key} must be a positive integer.`);
|
|
85
|
+
}
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
function nonNegativeInteger(flags, key) {
|
|
89
|
+
const raw = optionalString(flags, key);
|
|
90
|
+
if (raw === undefined)
|
|
91
|
+
return undefined;
|
|
92
|
+
const value = Number(raw);
|
|
93
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
94
|
+
throw new CliError(`snapshot partition --${key} must be a non-negative integer.`);
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
function partitionCounts(flags) {
|
|
99
|
+
const sessions = nonNegativeInteger(flags, 'sessions');
|
|
100
|
+
const entries = nonNegativeInteger(flags, 'entries');
|
|
101
|
+
const records = nonNegativeInteger(flags, 'records');
|
|
102
|
+
const bytes = nonNegativeInteger(flags, 'bytes');
|
|
103
|
+
if ([sessions, entries, records, bytes].some((value) => value !== undefined)) {
|
|
104
|
+
if ([sessions, entries, records, bytes].some((value) => value === undefined)) {
|
|
105
|
+
throw new CliError('snapshot partition count verification requires --sessions, --entries, --records, and --bytes.');
|
|
106
|
+
}
|
|
107
|
+
return { sessions, entries, records, bytes };
|
|
108
|
+
}
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
function only(flags, allowed, command) {
|
|
112
|
+
for (const key of Object.keys(flags)) {
|
|
113
|
+
if (!allowed.includes(key))
|
|
114
|
+
throw new CliError(`${command} does not accept --${key}.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
61
117
|
/** Runs `snapshot export`, keeping JSONL evidence off stdout. */
|
|
62
118
|
export async function runSnapshot(argv, ctx) {
|
|
63
119
|
const [subcommand, ...rest] = argv;
|
|
64
|
-
if (subcommand !== 'export')
|
|
65
|
-
throw new CliError('snapshot requires: export.');
|
|
66
120
|
const { positional, flags } = parseArgs(rest);
|
|
121
|
+
if (subcommand === 'partition') {
|
|
122
|
+
only(flags, ['path', 'max-sessions', 'max-bytes', 'checksum', 'sessions', 'entries', 'records', 'bytes'], 'snapshot partition');
|
|
123
|
+
if (positional.length > 0)
|
|
124
|
+
throw new CliError('snapshot partition accepts flags only.');
|
|
125
|
+
const maxSessions = positiveInteger(flags, 'max-sessions');
|
|
126
|
+
const maxBytes = positiveInteger(flags, 'max-bytes');
|
|
127
|
+
const checksum = optionalString(flags, 'checksum');
|
|
128
|
+
const counts = partitionCounts(flags);
|
|
129
|
+
if (checksum !== undefined && !/^[a-f0-9]{64}$/.test(checksum)) {
|
|
130
|
+
throw new CliError('snapshot partition --checksum must be a SHA-256 hex digest.');
|
|
131
|
+
}
|
|
132
|
+
const result = await partitionSnapshot({
|
|
133
|
+
path: requiredString(flags, 'path', 'snapshot partition'),
|
|
134
|
+
...(maxSessions === undefined ? {} : { maxSessions }),
|
|
135
|
+
...(maxBytes === undefined ? {} : { maxBytes }),
|
|
136
|
+
...(checksum === undefined ? {} : { checksum: { algorithm: 'sha256', value: checksum } }),
|
|
137
|
+
...(counts === undefined ? {} : { counts }),
|
|
138
|
+
});
|
|
139
|
+
writeLine(ctx.stdout, JSON.stringify(result));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (subcommand === 'cleanup') {
|
|
143
|
+
only(flags, ['path', 'directory'], 'snapshot cleanup');
|
|
144
|
+
if (positional.length > 0)
|
|
145
|
+
throw new CliError('snapshot cleanup accepts flags only.');
|
|
146
|
+
const path = optionalString(flags, 'path', 'snapshot cleanup');
|
|
147
|
+
const directory = optionalString(flags, 'directory', 'snapshot cleanup');
|
|
148
|
+
if (!path && !directory)
|
|
149
|
+
throw new CliError('snapshot cleanup requires --path or --directory.');
|
|
150
|
+
await cleanupSnapshotPartitions({
|
|
151
|
+
...(path === undefined ? {} : { path }),
|
|
152
|
+
...(directory === undefined ? {} : { directory }),
|
|
153
|
+
});
|
|
154
|
+
writeLine(ctx.stdout, JSON.stringify({ removed: true }));
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (subcommand !== 'export')
|
|
158
|
+
throw new CliError('snapshot requires: export, partition, or cleanup.');
|
|
159
|
+
only(flags, ['path', 'agent', 'version', 'parent-session-id', 'root-only', 'data', 'inactive-for-hours'], 'snapshot export');
|
|
67
160
|
if (positional.length > 0)
|
|
68
161
|
throw new CliError('snapshot export accepts flags only.');
|
|
69
162
|
const path = optionalString(flags, 'path');
|
package/dist/cli/usage.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const USAGE = "agent-blackboard \u2014 an entry stream for autonomous agents\n\nUsage:\n agent-blackboard sessions create <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions ensure <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions list [--archived true|false] [--inactive-for-hours <hours>]\n agent-blackboard sessions get <id>\n agent-blackboard sessions patch <id> --data <json>\n agent-blackboard sessions archive <id>\n agent-blackboard append --session-id <id> <json>\n agent-blackboard append --session-id <id> --file <json|markdown|text>\n agent-blackboard get --session-id <id> [--format json|jsonl|markdown]\n agent-blackboard snapshot export [--path <absolute-path>] [--agent <name>] [--version <version>]\n [--parent-session-id <id>|--root-only] [--data <json>] [--inactive-for-hours <hours>]\n agent-blackboard credentials <subcommand>\n agent-blackboard mcp\n\nEnv:\n AGENT_BLACKBOARD_URL Server base URL\n AGENT_BLACKBOARD_TOKEN Client credential\n AGENT_BLACKBOARD_ADMIN_TOKEN Admin credential\n";
|
|
1
|
+
export declare const USAGE = "agent-blackboard \u2014 an entry stream for autonomous agents\n\nUsage:\n agent-blackboard sessions create <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions ensure <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions list [--archived true|false] [--inactive-for-hours <hours>]\n agent-blackboard sessions get <id>\n agent-blackboard sessions patch <id> --data <json>\n agent-blackboard sessions archive <id>\n agent-blackboard append --session-id <id> <json>\n agent-blackboard append --session-id <id> --file <json|markdown|text>\n agent-blackboard get --session-id <id> [--format json|jsonl|markdown]\n agent-blackboard snapshot export [--path <absolute-path>] [--agent <name>] [--version <version>]\n [--parent-session-id <id>|--root-only] [--data <json>] [--inactive-for-hours <hours>]\n agent-blackboard snapshot partition --path <generated-snapshot> [--max-sessions <count>]\n [--max-bytes <bytes>] [--checksum <sha256>] [--sessions <count> --entries <count> --records <count> --bytes <count>]\n agent-blackboard snapshot cleanup [--path <generated-snapshot>] [--directory <generated-partition-directory>]\n agent-blackboard credentials <subcommand>\n agent-blackboard mcp\n\nEnv:\n AGENT_BLACKBOARD_URL Server base URL\n AGENT_BLACKBOARD_TOKEN Client credential\n AGENT_BLACKBOARD_ADMIN_TOKEN Admin credential\n";
|
package/dist/cli/usage.mjs
CHANGED
|
@@ -12,6 +12,9 @@ Usage:
|
|
|
12
12
|
agent-blackboard get --session-id <id> [--format json|jsonl|markdown]
|
|
13
13
|
agent-blackboard snapshot export [--path <absolute-path>] [--agent <name>] [--version <version>]
|
|
14
14
|
[--parent-session-id <id>|--root-only] [--data <json>] [--inactive-for-hours <hours>]
|
|
15
|
+
agent-blackboard snapshot partition --path <generated-snapshot> [--max-sessions <count>]
|
|
16
|
+
[--max-bytes <bytes>] [--checksum <sha256>] [--sessions <count> --entries <count> --records <count> --bytes <count>]
|
|
17
|
+
agent-blackboard snapshot cleanup [--path <generated-snapshot>] [--directory <generated-partition-directory>]
|
|
15
18
|
agent-blackboard credentials <subcommand>
|
|
16
19
|
agent-blackboard mcp
|
|
17
20
|
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import fileSystem from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
const SOURCE_NAME = /^agent-blackboard-snapshot-[0-9a-f-]{36}\.jsonl$/;
|
|
6
|
+
const DIRECTORY_NAME = /^agent-blackboard-partitions-[0-9a-f-]{36}$/;
|
|
7
|
+
const OWNERSHIP_MARKER = '.agent-blackboard-partitions';
|
|
8
|
+
function assertGeneratedPath(path, expression, label) {
|
|
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;
|
|
16
|
+
try {
|
|
17
|
+
marker = await fileSystem.open(join(directory, OWNERSHIP_MARKER), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
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;
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
/* v8 ignore next -- marker close failure requires an OS-level fault */
|
|
29
|
+
await marker?.close().catch(() => undefined);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function removeCaptured(path, expression, directory) {
|
|
33
|
+
const label = directory ? 'partition directory' : 'snapshot path';
|
|
34
|
+
assertGeneratedPath(path, expression, label);
|
|
35
|
+
let initial;
|
|
36
|
+
try {
|
|
37
|
+
initial = await fileSystem.lstat(path);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
/* v8 ignore next -- tests cover ENOENT; another lstat code needs an OS-level fault */
|
|
41
|
+
if (error.code === 'ENOENT')
|
|
42
|
+
return;
|
|
43
|
+
/* v8 ignore next -- non-ENOENT lstat failure requires an OS-level fault */
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
/* v8 ignore next -- every unsafe target shape is rejected by the same branch */
|
|
47
|
+
if (initial.isSymbolicLink() ||
|
|
48
|
+
(!initial.isFile() && !directory) ||
|
|
49
|
+
(directory && !initial.isDirectory()) ||
|
|
50
|
+
(!directory && initial.nlink !== 1))
|
|
51
|
+
throw new Error(`${label} is not a generated ${directory ? 'directory' : 'regular file'}`);
|
|
52
|
+
const identity = basename(path);
|
|
53
|
+
if (directory)
|
|
54
|
+
await assertOwnershipMarker(path, identity);
|
|
55
|
+
const tombstone = join(tmpdir(), `.agent-blackboard-cleanup-${process.pid}-${crypto.randomUUID()}`);
|
|
56
|
+
let capturedPath = false;
|
|
57
|
+
try {
|
|
58
|
+
await fileSystem.rename(path, tombstone);
|
|
59
|
+
capturedPath = true;
|
|
60
|
+
const captured = await fileSystem.lstat(tombstone);
|
|
61
|
+
/* v8 ignore next -- replacement after random tombstone rename is race-only */
|
|
62
|
+
if (captured.isSymbolicLink() ||
|
|
63
|
+
captured.dev !== initial.dev ||
|
|
64
|
+
captured.ino !== initial.ino ||
|
|
65
|
+
captured.isDirectory() !== directory ||
|
|
66
|
+
(!directory && (!captured.isFile() || captured.nlink !== 1)))
|
|
67
|
+
throw new Error(`${label} changed while it was being removed`);
|
|
68
|
+
if (directory)
|
|
69
|
+
await assertOwnershipMarker(tombstone, identity);
|
|
70
|
+
await fileSystem.rm(tombstone, { recursive: directory, force: true });
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
/* v8 ignore next -- concurrent removal after capture is harmless */
|
|
74
|
+
if (error.code === 'ENOENT' && !capturedPath)
|
|
75
|
+
return;
|
|
76
|
+
/* v8 ignore next -- only a non-ENOENT rename failure reaches this without capture */
|
|
77
|
+
if (!capturedPath)
|
|
78
|
+
throw error;
|
|
79
|
+
try {
|
|
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
|
+
}
|
|
92
|
+
}
|
|
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
|
+
}
|
|
103
|
+
/* v8 ignore next -- non-ENOENT removal failure requires an OS-level fault */
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Removes generated snapshot and/or partition evidence, refusing arbitrary filesystem paths. */
|
|
108
|
+
export async function cleanupSnapshotPartitions(options) {
|
|
109
|
+
if (!options.path && !options.directory)
|
|
110
|
+
throw new Error('cleanup requires a snapshot path or partition directory');
|
|
111
|
+
const results = await Promise.allSettled([
|
|
112
|
+
...(options.path ? [removeCaptured(options.path, SOURCE_NAME, false)] : []),
|
|
113
|
+
...(options.directory ? [removeCaptured(options.directory, DIRECTORY_NAME, true)] : []),
|
|
114
|
+
]);
|
|
115
|
+
const failures = results.filter((result) => result.status === 'rejected');
|
|
116
|
+
if (failures.length) {
|
|
117
|
+
const reasons = failures.map((result) => String(result.reason)).join('; ');
|
|
118
|
+
throw new AggregateError(failures.map((result) => result.reason), `snapshot cleanup failed: ${reasons}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { SnapshotCounts, SnapshotManifest } from './types.mjs';
|
|
2
|
+
export type SnapshotBlock = {
|
|
3
|
+
sessionId: string;
|
|
4
|
+
path: string;
|
|
5
|
+
bytes: number;
|
|
6
|
+
sessions: number;
|
|
7
|
+
entries: number;
|
|
8
|
+
};
|
|
9
|
+
export type SnapshotRecord = {
|
|
10
|
+
type: 'session';
|
|
11
|
+
session: Record<string, unknown>;
|
|
12
|
+
} | {
|
|
13
|
+
type: 'entry';
|
|
14
|
+
entry: Record<string, unknown>;
|
|
15
|
+
} | {
|
|
16
|
+
type: 'manifest';
|
|
17
|
+
manifest: SnapshotManifest;
|
|
18
|
+
};
|
|
19
|
+
export type SnapshotState = {
|
|
20
|
+
sessions: number;
|
|
21
|
+
entries: number;
|
|
22
|
+
records: number;
|
|
23
|
+
lastSessionCreatedAt?: number;
|
|
24
|
+
lastEntryCreatedAt?: number;
|
|
25
|
+
currentSessionId?: string;
|
|
26
|
+
};
|
|
27
|
+
export declare function snapshotLine(value: unknown): string;
|
|
28
|
+
export declare function countsFor(block: Pick<SnapshotBlock, 'sessions' | 'entries'>, bytes: number): SnapshotCounts;
|
|
29
|
+
export declare function manifestFor(manifest: SnapshotManifest, block: Pick<SnapshotBlock, 'sessions' | 'entries'>): SnapshotManifest;
|
|
30
|
+
export declare function parseSnapshotRecord(line: string): SnapshotRecord;
|
|
31
|
+
export declare function consumeSnapshotRecord(record: SnapshotRecord, state: SnapshotState): void;
|
|
32
|
+
export declare function assertManifest(manifest: SnapshotManifest, state: SnapshotState): void;
|
|
@@ -0,0 +1,135 @@
|
|
|
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 = record.session.createdAt;
|
|
108
|
+
const createdAtInstant = Date.parse(createdAt);
|
|
109
|
+
if (state.lastSessionCreatedAt !== undefined && createdAtInstant < state.lastSessionCreatedAt)
|
|
110
|
+
throw new Error('snapshot sessions are not ordered');
|
|
111
|
+
state.sessions += 1;
|
|
112
|
+
state.records += 1;
|
|
113
|
+
state.lastSessionCreatedAt = createdAtInstant;
|
|
114
|
+
delete state.lastEntryCreatedAt;
|
|
115
|
+
state.currentSessionId = record.session.id;
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const createdAt = record.entry.createdAt;
|
|
119
|
+
const createdAtInstant = Date.parse(createdAt);
|
|
120
|
+
if (state.currentSessionId !== record.entry.sessionId)
|
|
121
|
+
throw new Error('snapshot entries must follow their session');
|
|
122
|
+
if (state.lastEntryCreatedAt !== undefined && createdAtInstant < state.lastEntryCreatedAt)
|
|
123
|
+
throw new Error('snapshot entries are not ordered');
|
|
124
|
+
state.entries += 1;
|
|
125
|
+
state.records += 1;
|
|
126
|
+
state.lastEntryCreatedAt = createdAtInstant;
|
|
127
|
+
}
|
|
128
|
+
export function assertManifest(manifest, state) {
|
|
129
|
+
if (!isManifest(manifest))
|
|
130
|
+
throw new Error('snapshot is missing a complete terminal manifest');
|
|
131
|
+
if (manifest.counts.sessions !== state.sessions ||
|
|
132
|
+
manifest.counts.entries !== state.entries ||
|
|
133
|
+
manifest.counts.records !== state.records + 1)
|
|
134
|
+
throw new Error('snapshot manifest counts do not match its records');
|
|
135
|
+
}
|
|
@@ -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): AsyncGenerator<string>;
|
|
@@ -0,0 +1,39 @@
|
|
|
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) {
|
|
14
|
+
const buffer = Buffer.allocUnsafe(CHUNK_SIZE);
|
|
15
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
16
|
+
let pending = '';
|
|
17
|
+
let position = 0;
|
|
18
|
+
for (;;) {
|
|
19
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.byteLength, position);
|
|
20
|
+
if (!bytesRead)
|
|
21
|
+
break;
|
|
22
|
+
position += bytesRead;
|
|
23
|
+
const bytes = buffer.subarray(0, bytesRead);
|
|
24
|
+
hash?.update(bytes);
|
|
25
|
+
onRead?.(bytesRead);
|
|
26
|
+
pending += decoder.decode(bytes, { stream: true });
|
|
27
|
+
for (;;) {
|
|
28
|
+
const newline = pending.indexOf('\n');
|
|
29
|
+
if (newline < 0)
|
|
30
|
+
break;
|
|
31
|
+
yield pending.slice(0, newline);
|
|
32
|
+
pending = pending.slice(newline + 1);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
pending += decoder.decode();
|
|
36
|
+
/* v8 ignore next -- the last chunk normally ends at a record boundary */
|
|
37
|
+
if (pending)
|
|
38
|
+
yield pending;
|
|
39
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
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
|
+
}
|
|
9
|
+
/** Reads source once through its opened descriptor and stages session groups privately on disk. */
|
|
10
|
+
export declare function stageSnapshot(source: FileHandle, directory: string): Promise<StagedSnapshot>;
|
|
@@ -0,0 +1,73 @@
|
|
|
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
|
+
/** Reads source once through its opened descriptor and stages session groups privately on disk. */
|
|
7
|
+
export async function stageSnapshot(source, directory) {
|
|
8
|
+
const index = join(directory, 'index.jsonl');
|
|
9
|
+
const indexFile = await open(index, 'wx', 0o600);
|
|
10
|
+
const hash = createHash('sha256');
|
|
11
|
+
const state = { sessions: 0, entries: 0, records: 0 };
|
|
12
|
+
let current;
|
|
13
|
+
let manifest;
|
|
14
|
+
let ordinal = 0;
|
|
15
|
+
let bytes = 0;
|
|
16
|
+
const finish = async () => {
|
|
17
|
+
if (!current)
|
|
18
|
+
return;
|
|
19
|
+
await current.file.sync();
|
|
20
|
+
await current.file.close();
|
|
21
|
+
const { file: _file, ...block } = current;
|
|
22
|
+
await writeAll(indexFile, Buffer.from(snapshotLine(block)));
|
|
23
|
+
current = undefined;
|
|
24
|
+
};
|
|
25
|
+
try {
|
|
26
|
+
for await (const sourceLine of readLines(source, hash, (read) => {
|
|
27
|
+
bytes += read;
|
|
28
|
+
})) {
|
|
29
|
+
if (!sourceLine)
|
|
30
|
+
throw new Error('snapshot contains a blank JSONL record');
|
|
31
|
+
if (manifest)
|
|
32
|
+
throw new Error('snapshot contains records after its manifest');
|
|
33
|
+
const record = parseSnapshotRecord(sourceLine);
|
|
34
|
+
if (record.type === 'manifest') {
|
|
35
|
+
await finish();
|
|
36
|
+
manifest = record.manifest;
|
|
37
|
+
assertManifest(manifest, state);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (record.type === 'session') {
|
|
41
|
+
await finish();
|
|
42
|
+
ordinal += 1;
|
|
43
|
+
const path = join(directory, `session-${ordinal}.jsonl`);
|
|
44
|
+
current = {
|
|
45
|
+
sessionId: record.session.id,
|
|
46
|
+
path,
|
|
47
|
+
bytes: 0,
|
|
48
|
+
sessions: 1,
|
|
49
|
+
entries: 0,
|
|
50
|
+
file: await open(path, 'wx', 0o600),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
else if (!current)
|
|
54
|
+
throw new Error('snapshot entries must follow their session');
|
|
55
|
+
consumeSnapshotRecord(record, state);
|
|
56
|
+
if (record.type === 'entry')
|
|
57
|
+
current.entries += 1;
|
|
58
|
+
const bytes = Buffer.from(`${sourceLine}\n`);
|
|
59
|
+
await writeAll(current.file, bytes);
|
|
60
|
+
current.bytes += bytes.byteLength;
|
|
61
|
+
}
|
|
62
|
+
if (!manifest)
|
|
63
|
+
throw new Error('snapshot is missing a complete terminal manifest');
|
|
64
|
+
await indexFile.sync();
|
|
65
|
+
return { manifest, bytes, checksum: hash.digest('hex'), index };
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
/* v8 ignore next -- best-effort closure must not mask parse failure */
|
|
69
|
+
await current?.file.close().catch(() => undefined);
|
|
70
|
+
/* v8 ignore next -- best-effort closure must not mask parse failure */
|
|
71
|
+
await indexFile.close().catch(() => undefined);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { SnapshotManifest, SnapshotPartition } from './types.mjs';
|
|
2
|
+
/** Replays private staged groups into bounded, immutable partition files. */
|
|
3
|
+
export declare function writePartitions(index: string, manifest: SnapshotManifest, directory: string, maxSessions: number, maxBytes: number): Promise<SnapshotPartition[]>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { chmod, open, rename } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { countsFor, manifestFor, snapshotLine, } from './snapshot-partition-format.mjs';
|
|
6
|
+
import { readLines, writeAll } from './snapshot-partition-io.mjs';
|
|
7
|
+
async function copyBlock(block, output, hash) {
|
|
8
|
+
const input = await open(block.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
9
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
10
|
+
try {
|
|
11
|
+
for (;;) {
|
|
12
|
+
const { bytesRead } = await input.read(buffer);
|
|
13
|
+
if (!bytesRead)
|
|
14
|
+
return;
|
|
15
|
+
const bytes = buffer.subarray(0, bytesRead);
|
|
16
|
+
hash.update(bytes);
|
|
17
|
+
await writeAll(output, bytes);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
finally {
|
|
21
|
+
await input.close();
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Replays private staged groups into bounded, immutable partition files. */
|
|
25
|
+
export async function writePartitions(index, manifest, directory, maxSessions, maxBytes) {
|
|
26
|
+
const partitions = [];
|
|
27
|
+
const indexFile = await open(index, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
28
|
+
let active;
|
|
29
|
+
const start = async () => {
|
|
30
|
+
const number = partitions.length + 1;
|
|
31
|
+
const temporary = join(directory, `.partition-${number}.tmp`);
|
|
32
|
+
active = {
|
|
33
|
+
block: { sessionId: '', path: '', bytes: 0, sessions: 0, entries: 0 },
|
|
34
|
+
file: await open(temporary, 'wx', 0o600),
|
|
35
|
+
temporary,
|
|
36
|
+
hash: createHash('sha256'),
|
|
37
|
+
};
|
|
38
|
+
return active;
|
|
39
|
+
};
|
|
40
|
+
const finish = async () => {
|
|
41
|
+
if (!active)
|
|
42
|
+
return;
|
|
43
|
+
const partitionManifest = manifestFor(manifest, active.block);
|
|
44
|
+
const terminal = Buffer.from(snapshotLine({ type: 'manifest', manifest: partitionManifest }));
|
|
45
|
+
await writeAll(active.file, terminal);
|
|
46
|
+
active.hash.update(terminal);
|
|
47
|
+
await active.file.sync();
|
|
48
|
+
await active.file.close();
|
|
49
|
+
await chmod(active.temporary, 0o400);
|
|
50
|
+
const path = join(directory, `partition-${partitions.length + 1}.jsonl`);
|
|
51
|
+
await rename(active.temporary, path);
|
|
52
|
+
const bytes = active.block.bytes + terminal.byteLength;
|
|
53
|
+
partitions.push({
|
|
54
|
+
path,
|
|
55
|
+
counts: countsFor(active.block, bytes),
|
|
56
|
+
checksum: { algorithm: 'sha256', value: active.hash.digest('hex') },
|
|
57
|
+
manifest: partitionManifest,
|
|
58
|
+
});
|
|
59
|
+
active = undefined;
|
|
60
|
+
};
|
|
61
|
+
try {
|
|
62
|
+
for await (const sourceLine of readLines(indexFile)) {
|
|
63
|
+
const block = JSON.parse(sourceLine);
|
|
64
|
+
if (active && active.block.sessions + block.sessions > maxSessions)
|
|
65
|
+
await finish();
|
|
66
|
+
let candidate = {
|
|
67
|
+
...block,
|
|
68
|
+
sessions: (active?.block.sessions ?? 0) + block.sessions,
|
|
69
|
+
entries: (active?.block.entries ?? 0) + block.entries,
|
|
70
|
+
};
|
|
71
|
+
let terminalBytes = Buffer.byteLength(snapshotLine({ type: 'manifest', manifest: manifestFor(manifest, candidate) }));
|
|
72
|
+
if (active && active.block.bytes + block.bytes + terminalBytes > maxBytes) {
|
|
73
|
+
await finish();
|
|
74
|
+
candidate = { ...block };
|
|
75
|
+
terminalBytes = Buffer.byteLength(snapshotLine({ type: 'manifest', manifest: manifestFor(manifest, candidate) }));
|
|
76
|
+
}
|
|
77
|
+
if (block.bytes + terminalBytes > maxBytes)
|
|
78
|
+
throw new Error(`snapshot session ${block.sessionId} is too large for one partition`);
|
|
79
|
+
const target = active ?? (await start());
|
|
80
|
+
target.block.sessions += block.sessions;
|
|
81
|
+
target.block.entries += block.entries;
|
|
82
|
+
target.block.bytes += block.bytes;
|
|
83
|
+
await copyBlock(block, target.file, target.hash);
|
|
84
|
+
}
|
|
85
|
+
await finish();
|
|
86
|
+
return partitions;
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await indexFile.close();
|
|
90
|
+
/* v8 ignore next -- best-effort closure must not mask an assembly failure */
|
|
91
|
+
await active?.file.close().catch(() => undefined);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -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>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { chmod, lstat, mkdir, mkdtemp, open, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { basename, dirname, isAbsolute, resolve } from 'node:path';
|
|
6
|
+
import { stageSnapshot } from './snapshot-partition-read.mjs';
|
|
7
|
+
import { writePartitions } from './snapshot-partition-write.mjs';
|
|
8
|
+
const MAX_SESSIONS = 25;
|
|
9
|
+
const MAX_BYTES = 1024 * 1024;
|
|
10
|
+
const SOURCE_NAME = /^agent-blackboard-snapshot-[0-9a-f-]{36}\.jsonl$/;
|
|
11
|
+
const OWNERSHIP_MARKER = '.agent-blackboard-partitions';
|
|
12
|
+
function assertLimit(value, fallback, label) {
|
|
13
|
+
const limit = value ?? fallback;
|
|
14
|
+
if (!Number.isSafeInteger(limit) || limit < 1)
|
|
15
|
+
throw new Error(`${label} must be a positive integer`);
|
|
16
|
+
return limit;
|
|
17
|
+
}
|
|
18
|
+
function assertGeneratedSnapshot(path) {
|
|
19
|
+
if (!isAbsolute(path))
|
|
20
|
+
throw new Error('snapshot path must be absolute');
|
|
21
|
+
if (dirname(resolve(path)) !== resolve(tmpdir()) || !SOURCE_NAME.test(basename(path)))
|
|
22
|
+
throw new Error('snapshot path must be a generated temporary snapshot path');
|
|
23
|
+
}
|
|
24
|
+
function assertVerification(bytes, checksum, manifest, options) {
|
|
25
|
+
if (options.checksum &&
|
|
26
|
+
(options.checksum.algorithm !== 'sha256' || options.checksum.value !== checksum))
|
|
27
|
+
throw new Error('snapshot checksum does not match');
|
|
28
|
+
if (options.counts &&
|
|
29
|
+
(options.counts.bytes !== bytes ||
|
|
30
|
+
options.counts.sessions !== manifest.counts.sessions ||
|
|
31
|
+
options.counts.entries !== manifest.counts.entries ||
|
|
32
|
+
options.counts.records !== manifest.counts.records)) {
|
|
33
|
+
throw new Error('snapshot counts do not match');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Splits a generated snapshot into bounded, whole-session, read-only JSONL files. */
|
|
37
|
+
export async function partitionSnapshot(options) {
|
|
38
|
+
assertGeneratedSnapshot(options.path);
|
|
39
|
+
const before = await lstat(options.path, { bigint: true });
|
|
40
|
+
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n)
|
|
41
|
+
throw new Error('snapshot path must be an unlinked generated regular file');
|
|
42
|
+
let source;
|
|
43
|
+
let stage;
|
|
44
|
+
let directory;
|
|
45
|
+
try {
|
|
46
|
+
source = await open(options.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
47
|
+
stage = await mkdtemp(resolve(tmpdir(), 'agent-blackboard-partition-stage-'));
|
|
48
|
+
directory = resolve(tmpdir(), `agent-blackboard-partitions-${randomUUID()}`);
|
|
49
|
+
await mkdir(directory, { mode: 0o700 });
|
|
50
|
+
await Promise.all([
|
|
51
|
+
chmod(stage, 0o700),
|
|
52
|
+
chmod(directory, 0o700),
|
|
53
|
+
writeFile(resolve(directory, OWNERSHIP_MARKER), `${basename(directory)}\n`, {
|
|
54
|
+
flag: 'wx',
|
|
55
|
+
mode: 0o400,
|
|
56
|
+
}),
|
|
57
|
+
]);
|
|
58
|
+
const opened = await source.stat({ bigint: true });
|
|
59
|
+
/* v8 ignore next -- a replacement between lstat and O_NOFOLLOW open is race-only */
|
|
60
|
+
if (!opened.isFile() ||
|
|
61
|
+
opened.nlink !== 1n ||
|
|
62
|
+
opened.dev !== before.dev ||
|
|
63
|
+
opened.ino !== before.ino)
|
|
64
|
+
throw new Error('snapshot path changed while it was being opened');
|
|
65
|
+
const staged = await stageSnapshot(source, stage);
|
|
66
|
+
const after = await source.stat({ bigint: true });
|
|
67
|
+
/* v8 ignore next -- source mutation during an owned read-only descriptor is race-only */
|
|
68
|
+
if (after.dev !== opened.dev ||
|
|
69
|
+
after.ino !== opened.ino ||
|
|
70
|
+
after.nlink !== 1n ||
|
|
71
|
+
opened.size !== BigInt(staged.bytes) ||
|
|
72
|
+
after.size !== BigInt(staged.bytes) ||
|
|
73
|
+
after.mtimeNs !== opened.mtimeNs ||
|
|
74
|
+
after.ctimeNs !== opened.ctimeNs)
|
|
75
|
+
throw new Error('snapshot path changed while it was being read');
|
|
76
|
+
await source.close();
|
|
77
|
+
source = undefined;
|
|
78
|
+
assertVerification(staged.bytes, staged.checksum, staged.manifest, options);
|
|
79
|
+
const partitions = await writePartitions(staged.index, staged.manifest, directory, assertLimit(options.maxSessions, MAX_SESSIONS, 'maxSessions'), assertLimit(options.maxBytes, MAX_BYTES, 'maxBytes'));
|
|
80
|
+
return { directory, partitions };
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
/* v8 ignore next -- false only when setup fails before assigning the output path */
|
|
84
|
+
if (directory)
|
|
85
|
+
await rm(directory, { recursive: true, force: true });
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
/* v8 ignore next -- best-effort descriptor closure must not mask the original failure */
|
|
90
|
+
await source?.close().catch(() => undefined);
|
|
91
|
+
/* v8 ignore next -- false only when setup fails before staging exists */
|
|
92
|
+
if (stage)
|
|
93
|
+
await rm(stage, { recursive: true, force: true });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
import type { ClientConfig, SnapshotExportOptions, SnapshotExportResult } from './types.mjs';
|
|
1
|
+
import type { ClientConfig, SnapshotExportOptions, SnapshotExportResult, SnapshotCleanupOptions, SnapshotPartitionOptions, SnapshotPartitionResult } from './types.mjs';
|
|
2
2
|
/** Streams an immutable server snapshot directly into a private local JSONL file. */
|
|
3
3
|
export declare class Snapshots {
|
|
4
4
|
#private;
|
|
5
5
|
constructor(config: ClientConfig);
|
|
6
6
|
export(options?: SnapshotExportOptions): Promise<SnapshotExportResult>;
|
|
7
|
+
/** Splits a generated export into bounded session-preserving files. */
|
|
8
|
+
partition(options: SnapshotPartitionOptions): Promise<SnapshotPartitionResult>;
|
|
9
|
+
/** Removes a generated partition directory. */
|
|
10
|
+
cleanup(options: SnapshotCleanupOptions): Promise<void>;
|
|
7
11
|
}
|
|
@@ -4,6 +4,8 @@ import { tmpdir } from 'node:os';
|
|
|
4
4
|
import { isAbsolute, join } from 'node:path';
|
|
5
5
|
import { rawRequest } from './http.mjs';
|
|
6
6
|
import { readSnapshot } from './snapshot-response.mjs';
|
|
7
|
+
import { cleanupSnapshotPartitions } from './snapshot-partition-cleanup.mjs';
|
|
8
|
+
import { partitionSnapshot } from './snapshot-partitions.mjs';
|
|
7
9
|
function queryFor(selection = {}) {
|
|
8
10
|
const query = {};
|
|
9
11
|
if (selection.agent !== undefined)
|
|
@@ -79,4 +81,12 @@ export class Snapshots {
|
|
|
79
81
|
await rm(target.path, { force: true });
|
|
80
82
|
}
|
|
81
83
|
}
|
|
84
|
+
/** Splits a generated export into bounded session-preserving files. */
|
|
85
|
+
partition(options) {
|
|
86
|
+
return partitionSnapshot(options);
|
|
87
|
+
}
|
|
88
|
+
/** Removes a generated partition directory. */
|
|
89
|
+
cleanup(options) {
|
|
90
|
+
return cleanupSnapshotPartitions(options);
|
|
91
|
+
}
|
|
82
92
|
}
|
package/dist/client/types.d.mts
CHANGED
|
@@ -120,9 +120,39 @@ export interface SnapshotExportOptions {
|
|
|
120
120
|
export interface SnapshotExportResult {
|
|
121
121
|
path: string;
|
|
122
122
|
counts: SnapshotCounts;
|
|
123
|
-
checksum:
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
123
|
+
checksum: SnapshotChecksum;
|
|
124
|
+
manifest: SnapshotManifest;
|
|
125
|
+
}
|
|
126
|
+
export interface SnapshotChecksum {
|
|
127
|
+
algorithm: 'sha256';
|
|
128
|
+
value: string;
|
|
129
|
+
}
|
|
130
|
+
/** Verification metadata returned by `Snapshots.export` and accepted by `partition`. */
|
|
131
|
+
export interface SnapshotVerification {
|
|
132
|
+
checksum?: SnapshotChecksum;
|
|
133
|
+
counts?: SnapshotCounts;
|
|
134
|
+
}
|
|
135
|
+
export interface SnapshotPartitionOptions extends SnapshotVerification {
|
|
136
|
+
/** A generated temporary snapshot returned by `Snapshots.export` without `path`. */
|
|
137
|
+
path: string;
|
|
138
|
+
/** Maximum whole sessions in one partition. Defaults to 25. */
|
|
139
|
+
maxSessions?: number;
|
|
140
|
+
/** Maximum bytes in one partition. Defaults to 1 MiB. */
|
|
141
|
+
maxBytes?: number;
|
|
142
|
+
}
|
|
143
|
+
export interface SnapshotPartition {
|
|
144
|
+
path: string;
|
|
145
|
+
counts: SnapshotCounts;
|
|
146
|
+
checksum: SnapshotChecksum;
|
|
127
147
|
manifest: SnapshotManifest;
|
|
128
148
|
}
|
|
149
|
+
export interface SnapshotPartitionResult {
|
|
150
|
+
directory: string;
|
|
151
|
+
partitions: SnapshotPartition[];
|
|
152
|
+
}
|
|
153
|
+
export interface SnapshotCleanupOptions {
|
|
154
|
+
/** A generated temporary snapshot returned by `Snapshots.export` without `path`. */
|
|
155
|
+
path?: string;
|
|
156
|
+
/** A generated temporary partition directory returned by `Snapshots.partition`. */
|
|
157
|
+
directory?: string;
|
|
158
|
+
}
|
package/dist/index.d.mts
CHANGED
|
@@ -17,4 +17,6 @@ export { Entries } from './client/entries.mjs';
|
|
|
17
17
|
export { formatError } from './format-error.mjs';
|
|
18
18
|
export { Sessions } from './client/sessions.mjs';
|
|
19
19
|
export { Snapshots } from './client/snapshots.mjs';
|
|
20
|
-
export
|
|
20
|
+
export { cleanupSnapshotPartitions } from './client/snapshot-partition-cleanup.mjs';
|
|
21
|
+
export { partitionSnapshot } from './client/snapshot-partitions.mjs';
|
|
22
|
+
export type { AppendEntryInput, ClientConfig, CreateSessionInput, CredentialCreated, CredentialSummary, EntryWireFormat, GetEntriesQuery, GetRawEntriesQuery, ListSessionsQuery, PatchSessionInput, ReadRetryOptions, Session, SessionEntry, StructuredEntryFormat, SnapshotCounts, SnapshotExportOptions, SnapshotExportResult, SnapshotChecksum, SnapshotCleanupOptions, SnapshotManifest, SnapshotPartition, SnapshotPartitionOptions, SnapshotPartitionResult, SnapshotSelection, SnapshotVerification, } from './client/types.mjs';
|
package/dist/index.mjs
CHANGED
|
@@ -16,3 +16,5 @@ export { Entries } from './client/entries.mjs';
|
|
|
16
16
|
export { formatError } from './format-error.mjs';
|
|
17
17
|
export { Sessions } from './client/sessions.mjs';
|
|
18
18
|
export { Snapshots } from './client/snapshots.mjs';
|
|
19
|
+
export { cleanupSnapshotPartitions } from './client/snapshot-partition-cleanup.mjs';
|
|
20
|
+
export { partitionSnapshot } from './client/snapshot-partitions.mjs';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "agent-blackboard",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "A session-scoped entry stream for autonomous agents working unmonitored, for Codex.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Jonathan Ong",
|
|
7
|
+
"email": "jonathanrichardong@gmail.com",
|
|
8
|
+
"url": "https://github.com/jonathanong"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/jonathanong/agent-blackboard",
|
|
11
|
+
"repository": "https://github.com/jonathanong/agent-blackboard",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"keywords": ["entries", "agent", "mcp", "retrospective", "codex"],
|
|
14
|
+
"skills": "./skills/",
|
|
15
|
+
"interface": {
|
|
16
|
+
"displayName": "agent-blackboard",
|
|
17
|
+
"shortDescription": "Session entries for autonomous agents",
|
|
18
|
+
"longDescription": "Use agent-blackboard from Codex to create explicit root and subagent sessions, record entries while working, and review them later.",
|
|
19
|
+
"developerName": "Jonathan Ong",
|
|
20
|
+
"category": "Coding",
|
|
21
|
+
"capabilities": ["Interactive", "Write"],
|
|
22
|
+
"websiteURL": "https://github.com/jonathanong/agent-blackboard",
|
|
23
|
+
"privacyPolicyURL": "https://github.com/jonathanong/agent-blackboard",
|
|
24
|
+
"termsOfServiceURL": "https://github.com/jonathanong/agent-blackboard",
|
|
25
|
+
"defaultPrompt": [
|
|
26
|
+
"Record a note about what I just did",
|
|
27
|
+
"Get my entries for this session",
|
|
28
|
+
"Patch my entries with the PR number"
|
|
29
|
+
],
|
|
30
|
+
"brandColor": "#2563EB",
|
|
31
|
+
"screenshots": []
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: agent-blackboard
|
|
3
|
+
description: Create sessions and record entries in agent-blackboard, an append-only stream for autonomous agent work. Use when recording progress, decisions, or findings, or reviewing a known session later.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# agent-blackboard
|
|
7
|
+
|
|
8
|
+
`agent-blackboard` is an append-only, session-scoped entry stream, not a knowledge base. This
|
|
9
|
+
skill explains how to use it; project instructions decide what is worth recording.
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
- **Session ids are explicit.** The caller must choose an id and create the session before writing.
|
|
14
|
+
The service never infers or generates one.
|
|
15
|
+
- **Subagents get their own sessions.** Create each subagent session with its direct parent's id in
|
|
16
|
+
`parentSessionId`. Root sessions use `parentSessionId: null`.
|
|
17
|
+
- **Agent identity is explicit.** Every session creation includes the actual agent name and version.
|
|
18
|
+
- **Sessions can carry data.** Session patches shallow-merge a free-form `data` object.
|
|
19
|
+
- **`data` is unstructured.** Every entry carries a free-form `data` object. Attach whatever is
|
|
20
|
+
useful — a note, a branch name, a PR number, a decision and its rationale. There is no schema.
|
|
21
|
+
- **Entries are strictly append-only.** An entry's `data` cannot be changed after it is written; to
|
|
22
|
+
enrich or correct an earlier observation, append a new entry rather than editing the original.
|
|
23
|
+
Archival applies to the whole session.
|
|
24
|
+
|
|
25
|
+
## Using it via MCP
|
|
26
|
+
|
|
27
|
+
If the `agent-blackboard` MCP server is connected, use its tools directly:
|
|
28
|
+
|
|
29
|
+
- `session_create` — create a root or subagent session with explicit `sessionId` and
|
|
30
|
+
`parentSessionId` (use `null` for a root), plus `agent` and `version`.
|
|
31
|
+
- `session_search` — find undistilled or archived sessions with exact metadata, data, and optional
|
|
32
|
+
`inactiveForHours` filters.
|
|
33
|
+
- `session_patch` — shallow-merge `data` into an unarchived session.
|
|
34
|
+
- `session_archive` — mark a session as distilled; archival is one-time and metadata becomes
|
|
35
|
+
immutable.
|
|
36
|
+
- `entry_append` — append `data` to any existing session, including an archived one.
|
|
37
|
+
- `entry_get` — read entries from one explicit session.
|
|
38
|
+
- `snapshot_export` — stream all selected active sessions and entries to a private read-only JSONL
|
|
39
|
+
file, returning only its path, counts, checksum, and manifest.
|
|
40
|
+
|
|
41
|
+
## Using it via the CLI
|
|
42
|
+
|
|
43
|
+
Without MCP, or from a shell/script, run the published CLI through `npx`. This does not require a
|
|
44
|
+
local clone of the agent-blackboard repository:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npx -y agent-blackboard@0.4.0 sessions create root-123 --agent claude-code --version 1.0.13
|
|
48
|
+
npx -y agent-blackboard@0.4.0 sessions create worker-456 --parent-session-id root-123 \
|
|
49
|
+
--agent claude-code --version 1.0.13
|
|
50
|
+
npx -y agent-blackboard@0.4.0 sessions patch worker-456 --data '{"branch":"fix/retry"}'
|
|
51
|
+
npx -y agent-blackboard@0.4.0 append --session-id worker-456 '{"note":"found the failing edge case"}'
|
|
52
|
+
npx -y agent-blackboard@0.4.0 get --session-id worker-456 --format markdown
|
|
53
|
+
npx -y agent-blackboard@0.4.0 snapshot export --root-only --inactive-for-hours 8
|
|
54
|
+
npx -y agent-blackboard@0.4.0 snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl
|
|
55
|
+
npx -y agent-blackboard@0.4.0 snapshot cleanup --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
|
|
56
|
+
--directory /tmp/agent-blackboard-partitions-<suffix>
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Output defaults to JSON; pass `--format jsonl` or `--format markdown` for streaming or
|
|
60
|
+
human-readable reads.
|
|
61
|
+
|
|
62
|
+
`snapshot partition` accepts only a generated temporary export path, preserves whole sessions and
|
|
63
|
+
their entry order, and creates private read-only partition files. It defaults to 25 sessions or
|
|
64
|
+
1 MiB per partition. `snapshot cleanup` accepts either generated artifact or both; use it when the
|
|
65
|
+
bounded evidence is no longer needed. Explicit `snapshot export --path` destinations remain available
|
|
66
|
+
for caller-controlled export, but cannot be partitioned or cleaned up by these commands.
|
|
67
|
+
|
|
68
|
+
## What this skill does not do
|
|
69
|
+
|
|
70
|
+
This skill only covers **how** to create sessions and append and get entries. It does not prescribe
|
|
71
|
+
**what** to record — write, or look for, a project-specific skill that layers that guidance on top
|
|
72
|
+
of this one.
|
package/package.json
CHANGED