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.
- package/README.md +33 -2
- package/dist/cli/snapshot-partition-options.d.mts +9 -0
- package/dist/cli/snapshot-partition-options.mjs +22 -0
- package/dist/cli/snapshot.mjs +93 -6
- package/dist/cli/usage.d.mts +1 -1
- package/dist/cli/usage.mjs +3 -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 +3 -0
- package/dist/client/snapshot-partition-cleanup.mjs +125 -0
- 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 +36 -0
- package/dist/client/snapshot-partition-format.mjs +133 -0
- package/dist/client/snapshot-partition-io.d.mts +4 -0
- package/dist/client/snapshot-partition-io.mjs +52 -0
- package/dist/client/snapshot-partition-read.d.mts +15 -0
- package/dist/client/snapshot-partition-read.mjs +98 -0
- package/dist/client/snapshot-partition-write.d.mts +18 -0
- package/dist/client/snapshot-partition-write.mjs +148 -0
- package/dist/client/snapshot-partitions.d.mts +3 -0
- package/dist/client/snapshot-partitions.mjs +100 -0
- package/dist/client/snapshots.d.mts +5 -1
- package/dist/client/snapshots.mjs +61 -6
- package/dist/client/types.d.mts +42 -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 +79 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,9 +45,19 @@ for await (const current of entries.get({ sessionId: 'worker-456' })) {
|
|
|
45
45
|
|
|
46
46
|
await sessions.archive('worker-456')
|
|
47
47
|
|
|
48
|
-
// The JSONL file stays local; the result contains only its verification metadata.
|
|
48
|
+
// The JSONL file stays local; the result contains only its verification metadata and cleanup capability.
|
|
49
49
|
const snapshot = await snapshots.export({ selection: { agent: 'claude-code' } })
|
|
50
|
-
console.log(snapshot.path, snapshot.checksum.value)
|
|
50
|
+
console.log(snapshot.path, snapshot.checksum.value, snapshot.cleanupToken)
|
|
51
|
+
const partitions = await snapshots.partition({
|
|
52
|
+
path: snapshot.path,
|
|
53
|
+
cleanupToken: snapshot.cleanupToken,
|
|
54
|
+
checksum: snapshot.checksum,
|
|
55
|
+
})
|
|
56
|
+
await snapshots.cleanup({
|
|
57
|
+
path: snapshot.path,
|
|
58
|
+
directory: partitions.directory,
|
|
59
|
+
cleanupToken: partitions.cleanupToken,
|
|
60
|
+
})
|
|
51
61
|
|
|
52
62
|
const auth = new Auth({ baseUrl, adminToken })
|
|
53
63
|
await auth.createCredentials({ name: 'ci-bot' })
|
|
@@ -76,9 +86,30 @@ agent-blackboard append --session-id worker-456 --file findings.md
|
|
|
76
86
|
agent-blackboard get --session-id worker-456 --format jsonl
|
|
77
87
|
agent-blackboard sessions archive worker-456
|
|
78
88
|
agent-blackboard snapshot export --root-only --inactive-for-hours 8
|
|
89
|
+
agent-blackboard snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
|
|
90
|
+
--cleanup-token <cleanup-token>
|
|
91
|
+
agent-blackboard snapshot cleanup --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
|
|
92
|
+
--directory /tmp/agent-blackboard-partitions-<suffix> --cleanup-token <cleanup-token>
|
|
79
93
|
agent-blackboard mcp
|
|
80
94
|
```
|
|
81
95
|
|
|
96
|
+
`partition` only accepts a generated temporary snapshot, preserves each session and its ordered
|
|
97
|
+
entries as a single unit, and defaults to 25 sessions or 1 MiB per read-only partition. It can
|
|
98
|
+
verify the export checksum and counts. Both commands require the capability returned in the generated
|
|
99
|
+
export result; this keeps ownership authorization out of forgeable filenames or markers. `cleanup`
|
|
100
|
+
removes either generated temporary artifact, or both.
|
|
101
|
+
An explicit absolute `snapshot export --path` destination remains caller-owned and is never accepted
|
|
102
|
+
by either command.
|
|
103
|
+
|
|
104
|
+
Generated names, private modes, capabilities, and identity checks reject substitutions visible at
|
|
105
|
+
operation boundaries. The pure-Node package does not defend against a malicious concurrent process
|
|
106
|
+
with the same operating-system user identity that swaps a pathname between those checks, so keep
|
|
107
|
+
snapshot artifacts out of mutually untrusted same-UID process environments.
|
|
108
|
+
|
|
109
|
+
The published package includes the canonical provider plugin at `dist/plugin`; it is copied during
|
|
110
|
+
the package build from this repository's `plugins/agent-blackboard` source, so no second tracked
|
|
111
|
+
skill copy can drift.
|
|
112
|
+
|
|
82
113
|
## MCP
|
|
83
114
|
|
|
84
115
|
The stdio MCP server exposes `session_create`, `session_ensure`, `session_search`, `session_patch`,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
type Flags = Record<string, string | boolean>;
|
|
2
|
+
type OptionalString = (flags: Flags, key: string) => string | undefined;
|
|
3
|
+
export declare function partitionCounts(flags: Flags, optionalString: OptionalString): {
|
|
4
|
+
sessions: number;
|
|
5
|
+
entries: number;
|
|
6
|
+
records: number;
|
|
7
|
+
bytes: number;
|
|
8
|
+
} | undefined;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CliError } from './errors.mjs';
|
|
2
|
+
function nonNegativeInteger(raw, key) {
|
|
3
|
+
if (raw === undefined)
|
|
4
|
+
return undefined;
|
|
5
|
+
const value = Number(raw);
|
|
6
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
7
|
+
throw new CliError(`snapshot partition --${key} must be a non-negative integer.`);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
export function partitionCounts(flags, optionalString) {
|
|
12
|
+
const sessions = nonNegativeInteger(optionalString(flags, 'sessions'), 'sessions');
|
|
13
|
+
const entries = nonNegativeInteger(optionalString(flags, 'entries'), 'entries');
|
|
14
|
+
const records = nonNegativeInteger(optionalString(flags, 'records'), 'records');
|
|
15
|
+
const bytes = nonNegativeInteger(optionalString(flags, 'bytes'), 'bytes');
|
|
16
|
+
if ([sessions, entries, records, bytes].every((value) => value === undefined))
|
|
17
|
+
return undefined;
|
|
18
|
+
if ([sessions, entries, records, bytes].some((value) => value === undefined)) {
|
|
19
|
+
throw new CliError('snapshot partition count verification requires --sessions, --entries, --records, and --bytes.');
|
|
20
|
+
}
|
|
21
|
+
return { sessions: sessions, entries: entries, records: records, bytes: bytes };
|
|
22
|
+
}
|
package/dist/cli/snapshot.mjs
CHANGED
|
@@ -1,23 +1,46 @@
|
|
|
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
|
-
|
|
8
|
+
import { partitionCounts } from './snapshot-partition-options.mjs';
|
|
9
|
+
const PARTITION_FLAGS = [
|
|
10
|
+
'path',
|
|
11
|
+
'cleanup-token',
|
|
12
|
+
'max-sessions',
|
|
13
|
+
'max-bytes',
|
|
14
|
+
'checksum',
|
|
15
|
+
'sessions',
|
|
16
|
+
'entries',
|
|
17
|
+
'records',
|
|
18
|
+
'bytes',
|
|
19
|
+
];
|
|
20
|
+
function optionalString(flags, key, command = 'snapshot export') {
|
|
7
21
|
const value = stringFlag(flags, key);
|
|
8
22
|
if (Object.hasOwn(flags, key) && !value)
|
|
9
|
-
throw new CliError(
|
|
23
|
+
throw new CliError(`${command} --${key} requires a value.`);
|
|
10
24
|
return value;
|
|
11
25
|
}
|
|
26
|
+
function bareFlag(flags, key, command) {
|
|
27
|
+
const value = flags[key];
|
|
28
|
+
if (value === undefined)
|
|
29
|
+
return false;
|
|
30
|
+
if (value !== true)
|
|
31
|
+
throw new CliError(`${command} --${key} does not accept a value.`);
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
12
34
|
function parentSelection(flags) {
|
|
13
35
|
const parentSessionId = optionalString(flags, 'parent-session-id');
|
|
14
|
-
|
|
36
|
+
const rootOnly = bareFlag(flags, 'root-only', 'snapshot export');
|
|
37
|
+
if (rootOnly && parentSessionId !== undefined) {
|
|
15
38
|
throw new CliError('snapshot export --root-only cannot be combined with --parent-session-id.');
|
|
16
39
|
}
|
|
17
40
|
if (parentSessionId !== undefined && !/^[A-Za-z0-9._:-]+$/.test(parentSessionId)) {
|
|
18
41
|
throw new CliError('snapshot export --parent-session-id is invalid.');
|
|
19
42
|
}
|
|
20
|
-
if (
|
|
43
|
+
if (rootOnly)
|
|
21
44
|
return { parentSessionId: null };
|
|
22
45
|
return parentSessionId === undefined ? {} : { parentSessionId };
|
|
23
46
|
}
|
|
@@ -58,12 +81,76 @@ function selectionFrom(flags) {
|
|
|
58
81
|
...(inactiveForHours === undefined ? {} : { inactiveForHours }),
|
|
59
82
|
};
|
|
60
83
|
}
|
|
84
|
+
function requiredString(flags, key, command) {
|
|
85
|
+
return (optionalString(flags, key, command) ??
|
|
86
|
+
(() => {
|
|
87
|
+
throw new CliError(`${command} requires --${key}.`);
|
|
88
|
+
})());
|
|
89
|
+
}
|
|
90
|
+
function positiveInteger(flags, key) {
|
|
91
|
+
const raw = optionalString(flags, key);
|
|
92
|
+
if (raw === undefined)
|
|
93
|
+
return undefined;
|
|
94
|
+
const value = Number(raw);
|
|
95
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
96
|
+
throw new CliError(`snapshot partition --${key} must be a positive integer.`);
|
|
97
|
+
}
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
function only(flags, allowed, command) {
|
|
101
|
+
for (const key of Object.keys(flags)) {
|
|
102
|
+
if (!allowed.includes(key))
|
|
103
|
+
throw new CliError(`${command} does not accept --${key}.`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
61
106
|
/** Runs `snapshot export`, keeping JSONL evidence off stdout. */
|
|
62
107
|
export async function runSnapshot(argv, ctx) {
|
|
63
108
|
const [subcommand, ...rest] = argv;
|
|
64
|
-
if (subcommand !== 'export')
|
|
65
|
-
throw new CliError('snapshot requires: export.');
|
|
66
109
|
const { positional, flags } = parseArgs(rest);
|
|
110
|
+
if (subcommand === 'partition') {
|
|
111
|
+
only(flags, PARTITION_FLAGS, 'snapshot partition');
|
|
112
|
+
if (positional.length > 0)
|
|
113
|
+
throw new CliError('snapshot partition accepts flags only.');
|
|
114
|
+
const path = requiredString(flags, 'path', 'snapshot partition');
|
|
115
|
+
const maxSessions = positiveInteger(flags, 'max-sessions');
|
|
116
|
+
const maxBytes = positiveInteger(flags, 'max-bytes');
|
|
117
|
+
const checksum = optionalString(flags, 'checksum');
|
|
118
|
+
const counts = partitionCounts(flags, optionalString);
|
|
119
|
+
if (checksum !== undefined && !/^[a-f0-9]{64}$/.test(checksum)) {
|
|
120
|
+
throw new CliError('snapshot partition --checksum must be a SHA-256 hex digest.');
|
|
121
|
+
}
|
|
122
|
+
const cleanupToken = requiredString(flags, 'cleanup-token', 'snapshot partition');
|
|
123
|
+
const result = await partitionSnapshot({
|
|
124
|
+
path,
|
|
125
|
+
cleanupToken,
|
|
126
|
+
...(maxSessions === undefined ? {} : { maxSessions }),
|
|
127
|
+
...(maxBytes === undefined ? {} : { maxBytes }),
|
|
128
|
+
...(checksum === undefined ? {} : { checksum: { algorithm: 'sha256', value: checksum } }),
|
|
129
|
+
...(counts === undefined ? {} : { counts }),
|
|
130
|
+
});
|
|
131
|
+
writeLine(ctx.stdout, JSON.stringify(result));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (subcommand === 'cleanup') {
|
|
135
|
+
only(flags, ['path', 'directory', 'cleanup-token'], 'snapshot cleanup');
|
|
136
|
+
if (positional.length > 0)
|
|
137
|
+
throw new CliError('snapshot cleanup accepts flags only.');
|
|
138
|
+
const path = optionalString(flags, 'path', 'snapshot cleanup');
|
|
139
|
+
const directory = optionalString(flags, 'directory', 'snapshot cleanup');
|
|
140
|
+
if (!path && !directory)
|
|
141
|
+
throw new CliError('snapshot cleanup requires --path or --directory.');
|
|
142
|
+
const cleanupToken = requiredString(flags, 'cleanup-token', 'snapshot cleanup');
|
|
143
|
+
await cleanupSnapshotPartitions({
|
|
144
|
+
...(path === undefined ? {} : { path }),
|
|
145
|
+
...(directory === undefined ? {} : { directory }),
|
|
146
|
+
cleanupToken,
|
|
147
|
+
});
|
|
148
|
+
writeLine(ctx.stdout, JSON.stringify({ removed: true }));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (subcommand !== 'export')
|
|
152
|
+
throw new CliError('snapshot requires: export, partition, or cleanup.');
|
|
153
|
+
only(flags, ['path', 'agent', 'version', 'parent-session-id', 'root-only', 'data', 'inactive-for-hours'], 'snapshot export');
|
|
67
154
|
if (positional.length > 0)
|
|
68
155
|
throw new CliError('snapshot export accepts flags only.');
|
|
69
156
|
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> --cleanup-token <token> [--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>] --cleanup-token <token>\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> --cleanup-token <token> [--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>] --cleanup-token <token>
|
|
15
18
|
agent-blackboard credentials <subcommand>
|
|
16
19
|
agent-blackboard mcp
|
|
17
20
|
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { FileHandle } from 'node:fs/promises';
|
|
2
|
+
export declare const SOURCE_NAME: RegExp;
|
|
3
|
+
export declare const DIRECTORY_NAME: RegExp;
|
|
4
|
+
export declare function createCleanupToken(): string;
|
|
5
|
+
export declare function assertCleanupToken(token: string | undefined): asserts token is string;
|
|
6
|
+
export declare function knownCleanupToken(path: string): string | undefined;
|
|
7
|
+
export declare function forgetCleanupToken(path: string): void;
|
|
8
|
+
export declare function assertGeneratedPath(path: string, expression: RegExp, label: string): void;
|
|
9
|
+
export declare function snapshotMarkerPath(path: string): string;
|
|
10
|
+
export declare function writeSnapshotMarker(path: string, source: FileHandle, token: string): Promise<void>;
|
|
11
|
+
export declare function assertSnapshotMarker(path: string, source: FileHandle, token: string): Promise<void>;
|
|
12
|
+
export declare function writePartitionMarker(directory: string, token: string): Promise<void>;
|
|
13
|
+
export declare function assertPartitionMarker(directory: string, token: string): Promise<void>;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, open } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
6
|
+
export const SOURCE_NAME = /^agent-blackboard-snapshot-[0-9a-f-]{36}\.jsonl$/;
|
|
7
|
+
export const DIRECTORY_NAME = /^agent-blackboard-partitions-[A-Za-z0-9]+$/;
|
|
8
|
+
const OWNER_MARKER = '.agent-blackboard-partition-owner';
|
|
9
|
+
const SOURCE_MARKER_SUFFIX = '.owner';
|
|
10
|
+
const TOKEN_BYTES = 32;
|
|
11
|
+
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
12
|
+
const HASH_PATTERN = /^[a-f0-9]{64}$/;
|
|
13
|
+
const capabilities = new Map();
|
|
14
|
+
const WINDOWS_DRIVE_ABSOLUTE = /^[A-Za-z]:[\\/]/;
|
|
15
|
+
const WINDOWS_UNC_ABSOLUTE = /^(?:\\\\|\/\/)/;
|
|
16
|
+
export function createCleanupToken() {
|
|
17
|
+
return randomBytes(TOKEN_BYTES).toString('base64url');
|
|
18
|
+
}
|
|
19
|
+
export function assertCleanupToken(token) {
|
|
20
|
+
if (token === undefined || !TOKEN_PATTERN.test(token))
|
|
21
|
+
throw new Error('cleanupToken must be a valid generated capability');
|
|
22
|
+
}
|
|
23
|
+
function rememberCleanupToken(path, token) {
|
|
24
|
+
capabilities.set(path, token);
|
|
25
|
+
}
|
|
26
|
+
export function knownCleanupToken(path) {
|
|
27
|
+
return capabilities.get(path);
|
|
28
|
+
}
|
|
29
|
+
export function forgetCleanupToken(path) {
|
|
30
|
+
capabilities.delete(path);
|
|
31
|
+
}
|
|
32
|
+
export function assertGeneratedPath(path, expression, label) {
|
|
33
|
+
if ((!isAbsolute(path) && !WINDOWS_DRIVE_ABSOLUTE.test(path) && !WINDOWS_UNC_ABSOLUTE.test(path)) ||
|
|
34
|
+
dirname(resolve(path)) !== resolve(tmpdir()) ||
|
|
35
|
+
!expression.test(basename(path)))
|
|
36
|
+
throw new Error(`${label} must be a generated temporary ${label}`);
|
|
37
|
+
}
|
|
38
|
+
export function snapshotMarkerPath(path) {
|
|
39
|
+
return `${path}${SOURCE_MARKER_SUFFIX}`;
|
|
40
|
+
}
|
|
41
|
+
function tokenHash(token) {
|
|
42
|
+
return createHash('sha256').update(token, 'utf8').digest('hex');
|
|
43
|
+
}
|
|
44
|
+
function markerText(marker) {
|
|
45
|
+
return `${JSON.stringify(marker)}\n`;
|
|
46
|
+
}
|
|
47
|
+
function identityOf(stats) {
|
|
48
|
+
return { dev: String(stats.dev), ino: String(stats.ino) };
|
|
49
|
+
}
|
|
50
|
+
function parseMarker(value, kind) {
|
|
51
|
+
let parsed;
|
|
52
|
+
try {
|
|
53
|
+
parsed = JSON.parse(value);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw new Error(`invalid ${kind} ownership marker`);
|
|
57
|
+
}
|
|
58
|
+
if (!parsed ||
|
|
59
|
+
typeof parsed !== 'object' ||
|
|
60
|
+
parsed.version !== 1 ||
|
|
61
|
+
parsed.kind !== kind ||
|
|
62
|
+
!HASH_PATTERN.test(parsed.tokenHash) ||
|
|
63
|
+
typeof parsed.dev !== 'string' ||
|
|
64
|
+
typeof parsed.ino !== 'string')
|
|
65
|
+
throw new Error(`invalid ${kind} ownership marker`);
|
|
66
|
+
return parsed;
|
|
67
|
+
}
|
|
68
|
+
async function readMarker(path, kind, token) {
|
|
69
|
+
let before;
|
|
70
|
+
try {
|
|
71
|
+
before = await lstat(path, { bigint: true });
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
throw new Error(`invalid ${kind} ownership marker`);
|
|
75
|
+
}
|
|
76
|
+
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n)
|
|
77
|
+
throw new Error(`invalid ${kind} ownership marker`);
|
|
78
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
79
|
+
try {
|
|
80
|
+
const opened = await file.stat({ bigint: true });
|
|
81
|
+
/* v8 ignore start -- descriptor identity mismatch requires an OS-level replacement race */
|
|
82
|
+
if (!opened.isFile() ||
|
|
83
|
+
opened.nlink !== 1n ||
|
|
84
|
+
opened.dev !== before.dev ||
|
|
85
|
+
opened.ino !== before.ino)
|
|
86
|
+
/* v8 ignore next -- replacing an ownership marker between lstat and descriptor stat is race-only */
|
|
87
|
+
throw new Error(`invalid ${kind} ownership marker`);
|
|
88
|
+
/* v8 ignore stop */
|
|
89
|
+
const marker = parseMarker((await file.readFile()).toString('utf8'), kind);
|
|
90
|
+
if (marker.tokenHash !== tokenHash(token))
|
|
91
|
+
throw new Error(`invalid ${kind} ownership marker`);
|
|
92
|
+
return marker;
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
await file.close();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function writeMarker(path, kind, token, identity) {
|
|
99
|
+
const file = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o400);
|
|
100
|
+
try {
|
|
101
|
+
await file.writeFile(markerText({ version: 1, kind, tokenHash: tokenHash(token), ...identityOf(identity) }), 'utf8');
|
|
102
|
+
await file.sync();
|
|
103
|
+
await file.chmod(0o400);
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
await file.close();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export async function writeSnapshotMarker(path, source, token) {
|
|
110
|
+
const identity = await source.stat({ bigint: true });
|
|
111
|
+
if (!identity.isFile() || identity.nlink !== 1n)
|
|
112
|
+
throw new Error('snapshot is not a private file');
|
|
113
|
+
await writeMarker(snapshotMarkerPath(path), 'snapshot', token, identity);
|
|
114
|
+
rememberCleanupToken(path, token);
|
|
115
|
+
}
|
|
116
|
+
export async function assertSnapshotMarker(path, source, token) {
|
|
117
|
+
const identity = await source.stat({ bigint: true });
|
|
118
|
+
if (!identity.isFile() || identity.nlink !== 1n)
|
|
119
|
+
throw new Error('snapshot is not a private file');
|
|
120
|
+
const marker = await readMarker(snapshotMarkerPath(path), 'snapshot', token);
|
|
121
|
+
const expected = identityOf(identity);
|
|
122
|
+
if (marker.dev !== expected.dev || marker.ino !== expected.ino)
|
|
123
|
+
throw new Error('snapshot ownership marker does not match its file');
|
|
124
|
+
}
|
|
125
|
+
export async function writePartitionMarker(directory, token) {
|
|
126
|
+
const identity = await lstat(directory, { bigint: true });
|
|
127
|
+
if (!identity.isDirectory())
|
|
128
|
+
throw new Error('partition directory is not a directory');
|
|
129
|
+
await writeMarker(join(directory, OWNER_MARKER), 'partition-directory', token, identity);
|
|
130
|
+
rememberCleanupToken(directory, token);
|
|
131
|
+
}
|
|
132
|
+
export async function assertPartitionMarker(directory, token) {
|
|
133
|
+
const identity = await lstat(directory, { bigint: true });
|
|
134
|
+
if (!identity.isDirectory() || (identity.mode & 511n) !== 448n)
|
|
135
|
+
throw new Error('partition directory is not a private generated directory');
|
|
136
|
+
const marker = await readMarker(join(directory, OWNER_MARKER), 'partition-directory', token);
|
|
137
|
+
const expected = identityOf(identity);
|
|
138
|
+
if (marker.dev !== expected.dev || marker.ino !== expected.ino)
|
|
139
|
+
throw new Error('partition ownership marker does not match its directory');
|
|
140
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type Identity = {
|
|
2
|
+
dev: bigint;
|
|
3
|
+
ino: bigint;
|
|
4
|
+
};
|
|
5
|
+
export declare function captureDirectoryIdentity(directory: string, label: string): Promise<Identity>;
|
|
6
|
+
export declare function assertDirectoryIdentity(directory: string, expected: Identity | undefined, label: string): Promise<void>;
|
|
7
|
+
export declare function removeDetached(path: string, quarantine: string, label: string, expected?: Identity): Promise<void>;
|
|
8
|
+
/** Removes one private regular file without following or recursively deleting a path. */
|
|
9
|
+
export declare function removeOwnedFile(path: string, label: string, expected: Identity): Promise<void>;
|
|
10
|
+
export declare function assertDirectoryContents(directory: string, label: string, expected?: Identity): Promise<void>;
|
|
11
|
+
export declare function removeDirectoryContents(directory: string, quarantine: string, label: string, expected?: Identity): Promise<void>;
|
|
12
|
+
/** Removes a private, direct-entry-only directory without recursive path deletion. */
|
|
13
|
+
export declare function removeOwnedDirectory(directory: string, label: string, expected?: Identity): Promise<void>;
|
|
14
|
+
export declare function restore(original: string, captured: string, marker: string | undefined, capturedMarker: string | undefined, expected: Identity, expectedMarker: Identity | undefined): Promise<void>;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmod, link, lstat, mkdtemp, readdir, rename, rm, rmdir } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
function isPrivateFile(stats) {
|
|
6
|
+
return stats.isFile() && !stats.isSymbolicLink() && stats.nlink === 1n;
|
|
7
|
+
}
|
|
8
|
+
function hasIdentity(stats, expected) {
|
|
9
|
+
return stats.dev === expected.dev && stats.ino === expected.ino;
|
|
10
|
+
}
|
|
11
|
+
function isPrivateDirectory(stats) {
|
|
12
|
+
const mode = BigInt(stats.mode);
|
|
13
|
+
return stats.isDirectory() && !stats.isSymbolicLink() && (mode & 511n) === 448n;
|
|
14
|
+
}
|
|
15
|
+
export async function captureDirectoryIdentity(directory, label) {
|
|
16
|
+
const stats = await lstat(directory, { bigint: true });
|
|
17
|
+
if (!isPrivateDirectory(stats))
|
|
18
|
+
throw new Error(`${label} is not a private directory`);
|
|
19
|
+
return { dev: stats.dev, ino: stats.ino };
|
|
20
|
+
}
|
|
21
|
+
export async function assertDirectoryIdentity(directory, expected, label) {
|
|
22
|
+
if (!expected)
|
|
23
|
+
return;
|
|
24
|
+
const stats = await lstat(directory, { bigint: true });
|
|
25
|
+
if (!isPrivateDirectory(stats) || !hasIdentity(stats, expected))
|
|
26
|
+
throw new Error(`${label} changed while it was being removed`);
|
|
27
|
+
}
|
|
28
|
+
export async function removeDetached(path, quarantine, label, expected) {
|
|
29
|
+
const before = await lstat(path, { bigint: true });
|
|
30
|
+
if (!isPrivateFile(before) || (expected && !hasIdentity(before, expected)))
|
|
31
|
+
throw new Error(`${label} changed while it was being removed`);
|
|
32
|
+
const detached = join(quarantine, `.entry-${randomUUID()}`);
|
|
33
|
+
await rename(path, detached);
|
|
34
|
+
const after = await lstat(detached, { bigint: true });
|
|
35
|
+
/* v8 ignore start -- replacing a detached entry between rename and stat is race-only */
|
|
36
|
+
if (!isPrivateFile(after) || !hasIdentity(after, before)) {
|
|
37
|
+
/* v8 ignore next -- replacing a detached entry between rename and stat is race-only */
|
|
38
|
+
throw new Error(`${label} changed while it was being removed`);
|
|
39
|
+
}
|
|
40
|
+
/* v8 ignore stop */
|
|
41
|
+
await rm(detached, { force: true });
|
|
42
|
+
}
|
|
43
|
+
/** Removes one private regular file without following or recursively deleting a path. */
|
|
44
|
+
export async function removeOwnedFile(path, label, expected) {
|
|
45
|
+
const quarantine = await mkdtemp(join(tmpdir(), '.agent-blackboard-cleanup-'));
|
|
46
|
+
await chmod(quarantine, 0o700);
|
|
47
|
+
try {
|
|
48
|
+
await removeDetached(path, quarantine, label, expected);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
/* v8 ignore next -- a concurrent quarantine replacement is OS-race-only; never recurse */
|
|
52
|
+
await rmdir(quarantine).catch(() => undefined);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async function privateChildren(directory, label) {
|
|
56
|
+
const entries = await readdir(directory);
|
|
57
|
+
return Promise.all(entries.map(async (entry) => {
|
|
58
|
+
const path = join(directory, entry);
|
|
59
|
+
const identity = await lstat(path, { bigint: true });
|
|
60
|
+
if (!isPrivateFile(identity))
|
|
61
|
+
throw new Error(`${label} contains an unsafe entry`);
|
|
62
|
+
return { path, identity };
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
export async function assertDirectoryContents(directory, label, expected) {
|
|
66
|
+
await assertDirectoryIdentity(directory, expected, label);
|
|
67
|
+
await privateChildren(directory, label);
|
|
68
|
+
await assertDirectoryIdentity(directory, expected, label);
|
|
69
|
+
}
|
|
70
|
+
export async function removeDirectoryContents(directory, quarantine, label, expected) {
|
|
71
|
+
await assertDirectoryIdentity(directory, expected, label);
|
|
72
|
+
const children = await privateChildren(directory, label);
|
|
73
|
+
await assertDirectoryIdentity(directory, expected, label);
|
|
74
|
+
for (const child of children) {
|
|
75
|
+
await assertDirectoryIdentity(directory, expected, label);
|
|
76
|
+
await removeDetached(child.path, quarantine, label, child.identity);
|
|
77
|
+
}
|
|
78
|
+
await assertDirectoryIdentity(directory, expected, label);
|
|
79
|
+
await rmdir(directory);
|
|
80
|
+
}
|
|
81
|
+
/** Removes a private, direct-entry-only directory without recursive path deletion. */
|
|
82
|
+
export async function removeOwnedDirectory(directory, label, expected) {
|
|
83
|
+
const quarantine = await mkdtemp(join(tmpdir(), '.agent-blackboard-cleanup-'));
|
|
84
|
+
await chmod(quarantine, 0o700);
|
|
85
|
+
try {
|
|
86
|
+
await removeDirectoryContents(directory, quarantine, label, expected);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
/* v8 ignore next -- a concurrent quarantine replacement is OS-race-only; never recurse */
|
|
90
|
+
await rmdir(quarantine).catch(() => undefined);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function restoreFile(original, captured, expected) {
|
|
94
|
+
const identity = await lstat(captured, { bigint: true });
|
|
95
|
+
/* v8 ignore start -- a restore identity mismatch requires an OS-level race */
|
|
96
|
+
if (!isPrivateFile(identity) || !hasIdentity(identity, expected)) {
|
|
97
|
+
/* v8 ignore next -- a restore identity mismatch requires an OS-level race */
|
|
98
|
+
throw new Error('captured artifact changed while it was being restored');
|
|
99
|
+
}
|
|
100
|
+
/* v8 ignore stop */
|
|
101
|
+
await link(captured, original);
|
|
102
|
+
await rm(captured, { force: true });
|
|
103
|
+
}
|
|
104
|
+
export async function restore(original, captured, marker, capturedMarker, expected, expectedMarker) {
|
|
105
|
+
const errors = [];
|
|
106
|
+
if (marker && capturedMarker) {
|
|
107
|
+
try {
|
|
108
|
+
await restoreFile(marker, capturedMarker, expectedMarker);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
/* v8 ignore next -- restoring a marker fails only after an OS-level race or fault */
|
|
112
|
+
errors.push(error);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
await restoreFile(original, captured, expected);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
/* v8 ignore next -- restoring a source fails only after an OS-level race or fault */
|
|
120
|
+
errors.push(error);
|
|
121
|
+
}
|
|
122
|
+
/* v8 ignore next -- aggregate restore failure requires an OS-level race or fault */
|
|
123
|
+
if (errors.length)
|
|
124
|
+
throw new AggregateError(errors, 'artifact cleanup could not restore its target');
|
|
125
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { chmod, lstat, mkdtemp, open, rename, rmdir } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
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);
|
|
9
|
+
try {
|
|
10
|
+
await assertSnapshotMarker(path, file, token);
|
|
11
|
+
}
|
|
12
|
+
finally {
|
|
13
|
+
await file.close();
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
async function removeEmpty(path) {
|
|
17
|
+
await rmdir(path).catch(() => undefined);
|
|
18
|
+
}
|
|
19
|
+
async function removeCaptured(path, expression, directory, token) {
|
|
20
|
+
const label = directory ? 'partition directory' : 'snapshot path';
|
|
21
|
+
assertGeneratedPath(path, expression, label);
|
|
22
|
+
let initial;
|
|
23
|
+
try {
|
|
24
|
+
initial = await lstat(path, { bigint: true });
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
/* v8 ignore start -- only ENOENT is deterministic; other codes need an OS fault */
|
|
28
|
+
if (error.code === 'ENOENT')
|
|
29
|
+
return;
|
|
30
|
+
throw error;
|
|
31
|
+
/* v8 ignore stop */
|
|
32
|
+
}
|
|
33
|
+
/* v8 ignore start -- a replacement after the preflight check is race-only */
|
|
34
|
+
if (initial.isSymbolicLink() ||
|
|
35
|
+
(!directory && !initial.isFile()) ||
|
|
36
|
+
(directory && !initial.isDirectory()) ||
|
|
37
|
+
(!directory && initial.nlink !== 1n))
|
|
38
|
+
throw new Error(`${label} is not a generated ${directory ? 'directory' : 'regular file'}`);
|
|
39
|
+
assertCleanupToken(token);
|
|
40
|
+
if (directory)
|
|
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;
|
|
61
|
+
try {
|
|
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 */
|
|
71
|
+
throw new Error(`${label} changed while it was being removed`);
|
|
72
|
+
/* v8 ignore stop */
|
|
73
|
+
if (directory)
|
|
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);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
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');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/* v8 ignore stop */
|
|
101
|
+
/* v8 ignore next -- preserve the primary pre-detach failure */
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
await removeEmpty(quarantine);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Removes generated snapshot and/or partition evidence using an explicit capability. */
|
|
109
|
+
export async function cleanupSnapshotPartitions(options) {
|
|
110
|
+
if (!options.path && !options.directory)
|
|
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;
|
|
116
|
+
const results = await Promise.allSettled([
|
|
117
|
+
...(options.path ? [removeCaptured(options.path, SOURCE_NAME, false, token)] : []),
|
|
118
|
+
...(options.directory ? [removeCaptured(options.directory, DIRECTORY_NAME, true, token)] : []),
|
|
119
|
+
]);
|
|
120
|
+
const failures = results.filter((result) => result.status === 'rejected');
|
|
121
|
+
if (failures.length) {
|
|
122
|
+
const reasons = failures.map((result) => String(result.reason)).join('; ');
|
|
123
|
+
throw new AggregateError(failures.map((result) => result.reason), `snapshot cleanup failed: ${reasons}`);
|
|
124
|
+
}
|
|
125
|
+
}
|