agent-blackboard 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +23 -7
  2. package/dist/cli/data-array-contains.d.mts +1 -0
  3. package/dist/cli/data-array-contains.mjs +19 -0
  4. package/dist/cli/sessions.mjs +21 -0
  5. package/dist/cli/snapshot-partition-options.d.mts +9 -0
  6. package/dist/cli/snapshot-partition-options.mjs +22 -0
  7. package/dist/cli/snapshot.mjs +35 -29
  8. package/dist/cli/usage.d.mts +1 -1
  9. package/dist/cli/usage.mjs +2 -2
  10. package/dist/client/sessions.mjs +2 -0
  11. package/dist/client/snapshot-artifact-ownership.d.mts +13 -0
  12. package/dist/client/snapshot-artifact-ownership.mjs +140 -0
  13. package/dist/client/snapshot-artifact-removal.d.mts +14 -0
  14. package/dist/client/snapshot-artifact-removal.mjs +125 -0
  15. package/dist/client/snapshot-partition-cleanup.d.mts +1 -1
  16. package/dist/client/snapshot-partition-cleanup.mjs +83 -78
  17. package/dist/client/snapshot-partition-copy.d.mts +18 -0
  18. package/dist/client/snapshot-partition-copy.mjs +55 -0
  19. package/dist/client/snapshot-partition-format.d.mts +4 -0
  20. package/dist/client/snapshot-partition-format.mjs +11 -8
  21. package/dist/client/snapshot-partition-io.d.mts +1 -1
  22. package/dist/client/snapshot-partition-io.mjs +17 -4
  23. package/dist/client/snapshot-partition-read.d.mts +5 -0
  24. package/dist/client/snapshot-partition-read.mjs +27 -2
  25. package/dist/client/snapshot-partition-write.d.mts +16 -1
  26. package/dist/client/snapshot-partition-write.mjs +78 -23
  27. package/dist/client/snapshot-partitions.mjs +35 -30
  28. package/dist/client/snapshots.mjs +53 -6
  29. package/dist/client/types.d.mts +10 -0
  30. package/dist/mcp/schemas.mjs +35 -0
  31. package/dist/mcp/tool-sessions.mjs +24 -1
  32. package/dist/mcp/tool-snapshot.mjs +11 -0
  33. package/dist/plugin/.claude-mcp.json +1 -1
  34. package/dist/plugin/.codex-plugin/plugin.json +2 -1
  35. package/dist/plugin/.mcp.json +6 -4
  36. package/dist/plugin/skills/agent-blackboard/SKILL.md +38 -15
  37. package/package.json +1 -1
package/README.md CHANGED
@@ -45,11 +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)
51
- const partitions = await snapshots.partition({ path: snapshot.path, checksum: snapshot.checksum })
52
- await snapshots.cleanup({ path: snapshot.path, directory: partitions.directory })
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
+ })
53
61
 
54
62
  const auth = new Auth({ baseUrl, adminToken })
55
63
  await auth.createCredentials({ name: 'ci-bot' })
@@ -78,18 +86,26 @@ agent-blackboard append --session-id worker-456 --file findings.md
78
86
  agent-blackboard get --session-id worker-456 --format jsonl
79
87
  agent-blackboard sessions archive worker-456
80
88
  agent-blackboard snapshot export --root-only --inactive-for-hours 8
81
- agent-blackboard snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl
89
+ agent-blackboard snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
90
+ --cleanup-token <cleanup-token>
82
91
  agent-blackboard snapshot cleanup --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
83
- --directory /tmp/agent-blackboard-partitions-<suffix>
92
+ --directory /tmp/agent-blackboard-partitions-<suffix> --cleanup-token <cleanup-token>
84
93
  agent-blackboard mcp
85
94
  ```
86
95
 
87
96
  `partition` only accepts a generated temporary snapshot, preserves each session and its ordered
88
97
  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.
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.
90
101
  An explicit absolute `snapshot export --path` destination remains caller-owned and is never accepted
91
102
  by either command.
92
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
+
93
109
  The published package includes the canonical provider plugin at `dist/plugin`; it is copied during
94
110
  the package build from this repository's `plugins/agent-blackboard` source, so no second tracked
95
111
  skill copy can drift.
@@ -0,0 +1 @@
1
+ export declare function parseDataArrayContains(raw: string | undefined, command: string): Record<string, string> | undefined;
@@ -0,0 +1,19 @@
1
+ import { CliError } from './errors.mjs';
2
+ export function parseDataArrayContains(raw, command) {
3
+ if (raw === undefined)
4
+ return undefined;
5
+ try {
6
+ const parsed = JSON.parse(raw);
7
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
8
+ throw new Error();
9
+ const entries = Object.entries(parsed);
10
+ if (entries.length === 0 ||
11
+ entries.some(([key, value]) => key.length === 0 || typeof value !== 'string' || value.length === 0)) {
12
+ throw new Error();
13
+ }
14
+ return parsed;
15
+ }
16
+ catch {
17
+ throw new CliError(`${command} must be a JSON object with string values.`);
18
+ }
19
+ }
@@ -53,9 +53,30 @@ export async function runSessions(argv, ctx) {
53
53
  if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {
54
54
  throw new CliError('sessions list --limit must be a positive integer.');
55
55
  }
56
+ const dataArrayContainsFlag = stringFlag(flags, 'data-array-contains');
57
+ let dataArrayContains;
58
+ if (Object.hasOwn(flags, 'data-array-contains') && dataArrayContainsFlag === undefined) {
59
+ throw new CliError('sessions list --data-array-contains requires JSON.');
60
+ }
61
+ if (dataArrayContainsFlag !== undefined) {
62
+ try {
63
+ const parsed = JSON.parse(dataArrayContainsFlag);
64
+ if (!parsed ||
65
+ typeof parsed !== 'object' ||
66
+ Array.isArray(parsed) ||
67
+ Object.keys(parsed).length === 0 ||
68
+ Object.entries(parsed).some(([key, value]) => key.length === 0 || typeof value !== 'string' || value.length === 0))
69
+ throw new Error();
70
+ dataArrayContains = parsed;
71
+ }
72
+ catch {
73
+ throw new CliError('sessions list --data-array-contains must be a JSON object with string values.');
74
+ }
75
+ }
56
76
  const query = {
57
77
  ...(archivedFlag === undefined ? {} : { archived: archivedFlag === 'true' }),
58
78
  ...(inactiveForHours === undefined ? {} : { inactiveForHours }),
79
+ ...(dataArrayContains === undefined ? {} : { dataArrayContains }),
59
80
  };
60
81
  if (limit !== undefined) {
61
82
  // `--limit` fetches a single bounded page instead of the full drain below —
@@ -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
+ }
@@ -4,7 +4,20 @@ import { partitionSnapshot } from '../client/snapshot-partitions.mjs';
4
4
  import { parseArgs, stringFlag } from './args.mjs';
5
5
  import { clientConfigFromEnv } from './env.mjs';
6
6
  import { CliError } from './errors.mjs';
7
+ import { parseDataArrayContains } from './data-array-contains.mjs';
7
8
  import { writeLine } from './output.mjs';
9
+ import { partitionCounts } from './snapshot-partition-options.mjs';
10
+ const PARTITION_FLAGS = [
11
+ 'path',
12
+ 'cleanup-token',
13
+ 'max-sessions',
14
+ 'max-bytes',
15
+ 'checksum',
16
+ 'sessions',
17
+ 'entries',
18
+ 'records',
19
+ 'bytes',
20
+ ];
8
21
  function optionalString(flags, key, command = 'snapshot export') {
9
22
  const value = stringFlag(flags, key);
10
23
  if (Object.hasOwn(flags, key) && !value)
@@ -60,17 +73,19 @@ function selectionFrom(flags) {
60
73
  const agent = optionalString(flags, 'agent');
61
74
  const version = optionalString(flags, 'version');
62
75
  const data = dataSelection(flags);
76
+ const dataArrayContains = parseDataArrayContains(optionalString(flags, 'data-array-contains'), 'snapshot export --data-array-contains');
63
77
  const inactiveForHours = inactivitySelection(flags);
64
78
  return {
65
79
  ...(agent === undefined ? {} : { agent }),
66
80
  ...(version === undefined ? {} : { version }),
67
81
  ...parentSelection(flags),
68
82
  ...(data === undefined ? {} : { data }),
83
+ ...(dataArrayContains === undefined ? {} : { dataArrayContains }),
69
84
  ...(inactiveForHours === undefined ? {} : { inactiveForHours }),
70
85
  };
71
86
  }
72
87
  function requiredString(flags, key, command) {
73
- return (optionalString(flags, key) ??
88
+ return (optionalString(flags, key, command) ??
74
89
  (() => {
75
90
  throw new CliError(`${command} requires --${key}.`);
76
91
  })());
@@ -85,29 +100,6 @@ function positiveInteger(flags, key) {
85
100
  }
86
101
  return value;
87
102
  }
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
103
  function only(flags, allowed, command) {
112
104
  for (const key of Object.keys(flags)) {
113
105
  if (!allowed.includes(key))
@@ -119,18 +111,21 @@ export async function runSnapshot(argv, ctx) {
119
111
  const [subcommand, ...rest] = argv;
120
112
  const { positional, flags } = parseArgs(rest);
121
113
  if (subcommand === 'partition') {
122
- only(flags, ['path', 'max-sessions', 'max-bytes', 'checksum', 'sessions', 'entries', 'records', 'bytes'], 'snapshot partition');
114
+ only(flags, PARTITION_FLAGS, 'snapshot partition');
123
115
  if (positional.length > 0)
124
116
  throw new CliError('snapshot partition accepts flags only.');
117
+ const path = requiredString(flags, 'path', 'snapshot partition');
125
118
  const maxSessions = positiveInteger(flags, 'max-sessions');
126
119
  const maxBytes = positiveInteger(flags, 'max-bytes');
127
120
  const checksum = optionalString(flags, 'checksum');
128
- const counts = partitionCounts(flags);
121
+ const counts = partitionCounts(flags, optionalString);
129
122
  if (checksum !== undefined && !/^[a-f0-9]{64}$/.test(checksum)) {
130
123
  throw new CliError('snapshot partition --checksum must be a SHA-256 hex digest.');
131
124
  }
125
+ const cleanupToken = requiredString(flags, 'cleanup-token', 'snapshot partition');
132
126
  const result = await partitionSnapshot({
133
- path: requiredString(flags, 'path', 'snapshot partition'),
127
+ path,
128
+ cleanupToken,
134
129
  ...(maxSessions === undefined ? {} : { maxSessions }),
135
130
  ...(maxBytes === undefined ? {} : { maxBytes }),
136
131
  ...(checksum === undefined ? {} : { checksum: { algorithm: 'sha256', value: checksum } }),
@@ -140,23 +135,34 @@ export async function runSnapshot(argv, ctx) {
140
135
  return;
141
136
  }
142
137
  if (subcommand === 'cleanup') {
143
- only(flags, ['path', 'directory'], 'snapshot cleanup');
138
+ only(flags, ['path', 'directory', 'cleanup-token'], 'snapshot cleanup');
144
139
  if (positional.length > 0)
145
140
  throw new CliError('snapshot cleanup accepts flags only.');
146
141
  const path = optionalString(flags, 'path', 'snapshot cleanup');
147
142
  const directory = optionalString(flags, 'directory', 'snapshot cleanup');
148
143
  if (!path && !directory)
149
144
  throw new CliError('snapshot cleanup requires --path or --directory.');
145
+ const cleanupToken = requiredString(flags, 'cleanup-token', 'snapshot cleanup');
150
146
  await cleanupSnapshotPartitions({
151
147
  ...(path === undefined ? {} : { path }),
152
148
  ...(directory === undefined ? {} : { directory }),
149
+ cleanupToken,
153
150
  });
154
151
  writeLine(ctx.stdout, JSON.stringify({ removed: true }));
155
152
  return;
156
153
  }
157
154
  if (subcommand !== 'export')
158
155
  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');
156
+ only(flags, [
157
+ 'path',
158
+ 'agent',
159
+ 'version',
160
+ 'parent-session-id',
161
+ 'root-only',
162
+ 'data',
163
+ 'data-array-contains',
164
+ 'inactive-for-hours',
165
+ ], 'snapshot export');
160
166
  if (positional.length > 0)
161
167
  throw new CliError('snapshot export accepts flags only.');
162
168
  const path = optionalString(flags, 'path');
@@ -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 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";
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";
@@ -12,9 +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>]
15
+ agent-blackboard snapshot partition --path <generated-snapshot> --cleanup-token <token> [--max-sessions <count>]
16
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>]
17
+ agent-blackboard snapshot cleanup [--path <generated-snapshot>] [--directory <generated-partition-directory>] --cleanup-token <token>
18
18
  agent-blackboard credentials <subcommand>
19
19
  agent-blackboard mcp
20
20
 
@@ -28,6 +28,8 @@ function buildListSessionsQuery(query) {
28
28
  }
29
29
  if (query.data !== undefined)
30
30
  wire.data = JSON.stringify(query.data);
31
+ if (query.dataArrayContains !== undefined)
32
+ wire.dataArrayContains = JSON.stringify(query.dataArrayContains);
31
33
  if (query.inactiveForHours !== undefined) {
32
34
  wire.inactiveForHours = String(query.inactiveForHours);
33
35
  }
@@ -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
+ }
@@ -1,3 +1,3 @@
1
1
  import type { SnapshotCleanupOptions } from './types.mjs';
2
- /** Removes generated snapshot and/or partition evidence, refusing arbitrary filesystem paths. */
2
+ /** Removes generated snapshot and/or partition evidence using an explicit capability. */
3
3
  export declare function cleanupSnapshotPartitions(options: SnapshotCleanupOptions): Promise<void>;