agent-blackboard 0.6.1 → 0.8.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 (78) hide show
  1. package/README.md +32 -13
  2. package/dist/cli/append.mjs +16 -5
  3. package/dist/cli/args.d.mts +3 -2
  4. package/dist/cli/args.mjs +4 -3
  5. package/dist/cli/context.d.mts +2 -0
  6. package/dist/cli/env.d.mts +4 -4
  7. package/dist/cli/env.mjs +6 -6
  8. package/dist/cli/get.mjs +6 -6
  9. package/dist/cli/index.d.mts +1 -0
  10. package/dist/cli/index.mjs +10 -2
  11. package/dist/cli/revision-notice.d.mts +6 -0
  12. package/dist/cli/revision-notice.mjs +19 -0
  13. package/dist/cli/schemas-shadow.d.mts +3 -0
  14. package/dist/cli/schemas-shadow.mjs +47 -0
  15. package/dist/cli/schemas.d.mts +2 -0
  16. package/dist/cli/schemas.mjs +168 -0
  17. package/dist/cli/session-resolution.d.mts +19 -0
  18. package/dist/cli/session-resolution.mjs +63 -0
  19. package/dist/cli/sessions.mjs +23 -15
  20. package/dist/cli/snapshot.mjs +2 -1
  21. package/dist/cli/usage.d.mts +1 -1
  22. package/dist/cli/usage.mjs +18 -5
  23. package/dist/client/append.d.mts +2 -2
  24. package/dist/client/append.mjs +5 -1
  25. package/dist/client/entries.d.mts +2 -2
  26. package/dist/client/http.d.mts +2 -0
  27. package/dist/client/http.mjs +26 -8
  28. package/dist/client/schema-types.d.mts +119 -0
  29. package/dist/client/schema-types.mjs +1 -0
  30. package/dist/client/schemas-client.d.mts +21 -0
  31. package/dist/client/schemas-client.mjs +62 -0
  32. package/dist/client/schemas.d.mts +23 -0
  33. package/dist/client/schemas.mjs +68 -0
  34. package/dist/client/types.d.mts +10 -0
  35. package/dist/index.d.mts +19 -1
  36. package/dist/index.mjs +11 -0
  37. package/dist/mcp/dispatch.d.mts +2 -1
  38. package/dist/mcp/dispatch.mjs +14 -5
  39. package/dist/mcp/schema-fields.d.mts +37 -0
  40. package/dist/mcp/schema-fields.mjs +41 -0
  41. package/dist/mcp/schemas-registry-tools.d.mts +2 -0
  42. package/dist/mcp/schemas-registry-tools.mjs +63 -0
  43. package/dist/mcp/schemas.mjs +20 -41
  44. package/dist/mcp/server.d.mts +3 -2
  45. package/dist/mcp/server.mjs +5 -4
  46. package/dist/mcp/session-resolution.d.mts +23 -0
  47. package/dist/mcp/session-resolution.mjs +40 -0
  48. package/dist/mcp/tool-append.d.mts +3 -2
  49. package/dist/mcp/tool-append.mjs +11 -3
  50. package/dist/mcp/tool-get.d.mts +2 -1
  51. package/dist/mcp/tool-get.mjs +4 -3
  52. package/dist/mcp/tool-schemas.d.mts +7 -0
  53. package/dist/mcp/tool-schemas.mjs +26 -0
  54. package/dist/mcp/tool-sessions.d.mts +3 -2
  55. package/dist/mcp/tool-sessions.mjs +10 -11
  56. package/dist/plugin/.claude-mcp.json +1 -1
  57. package/dist/plugin/.codex-plugin/plugin.json +6 -6
  58. package/dist/plugin/.mcp.json +2 -2
  59. package/dist/plugin/skills/agent-blackboard/SKILL.md +23 -14
  60. package/dist/schemas/id.d.mts +8 -0
  61. package/dist/schemas/id.mjs +32 -0
  62. package/dist/schemas/local-store.d.mts +22 -0
  63. package/dist/schemas/local-store.mjs +159 -0
  64. package/dist/schemas/validate.d.mts +3 -0
  65. package/dist/schemas/validate.mjs +70 -0
  66. package/dist/session-id/harness.d.mts +44 -0
  67. package/dist/session-id/harness.mjs +61 -0
  68. package/dist/session-id/hook-payload.d.mts +19 -0
  69. package/dist/session-id/hook-payload.mjs +52 -0
  70. package/dist/session-id/persist.d.mts +53 -0
  71. package/dist/session-id/persist.mjs +127 -0
  72. package/dist/session-id/resolve.d.mts +46 -0
  73. package/dist/session-id/resolve.mjs +131 -0
  74. package/dist/session-id/root-codex-options.d.mts +9 -0
  75. package/dist/session-id/root-codex-options.mjs +13 -0
  76. package/dist/session-id/valid-id.d.mts +8 -0
  77. package/dist/session-id/valid-id.mjs +16 -0
  78. package/package.json +7 -5
@@ -10,14 +10,18 @@ skill explains how to use it; project instructions decide what is worth recordin
10
10
 
11
11
  ## How it works
12
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.
13
+ - **Session ids are explicit.** Choose an id and create the session before writing. The service
14
+ never infers or generates one. When an id is omitted, the MCP server or CLI resolves it from the
15
+ host's harness environment. Never rely on this for subagents.
15
16
  - **Subagents get their own sessions.** Create each subagent session with its direct parent's id in
16
17
  `parentSessionId`. Root sessions use `parentSessionId: null`.
17
18
  - **Agent identity is explicit.** Every session creation includes the actual agent name and version.
18
19
  - **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.
20
+ - **`data` is JSON with optional schema validation.** Every entry carries a JSON `data` object.
21
+ Unschematized entries remain allowed when the server runs in `optional` (default) or `shadow`
22
+ mode; when a deployment registers JSON Schema 2020-12 entry schemas, pass `schemaId` (and optional
23
+ `schemaVersion`) on `entry_append` (or `--schema <id>[@<version>]` in the CLI) so the server
24
+ validates and records the schema version on the entry.
21
25
  - **Repository context has a standard convention.** When recording repository work, use
22
26
  `repositories` as a sorted, deduplicated array of lowercase GitHub `owner/name` strings. The
23
27
  session's `data.repositories` is the cumulative union; an entry's `data.repositories` contains
@@ -42,10 +46,15 @@ If the `agent-blackboard` MCP server is connected, use its tools directly:
42
46
  - `session_patch` — shallow-merge `data` into an unarchived session.
43
47
  - `session_archive` — mark a session as distilled; archival is one-time and metadata becomes
44
48
  immutable.
45
- - `entry_append` — append `data` to any existing session, including an archived one.
49
+ - `entry_append` — append `data` to any existing session, including an archived one. Optionally
50
+ supply `schemaId` (and `schemaVersion`) for server-side JSON Schema validation.
46
51
  - `entry_get` — read entries from one explicit session.
47
52
  - `snapshot_export` — stream all selected active sessions and entries to a private read-only JSONL
48
53
  file, returning only its path, counts, checksum, and manifest.
54
+ - `schema_list` — list registered JSON Schemas and the current schema registry revision.
55
+ - `schema_get` — inspect one registered schema (latest version or an explicit `version`).
56
+ - `schema_pull` — sync the full schema registry into the local cache (`If-None-Match`).
57
+ - `schema_validate` — validate an entry payload offline against a locally pulled schema.
49
58
 
50
59
  ## Using it via the CLI
51
60
 
@@ -53,17 +62,17 @@ Without MCP, or from a shell/script, run the published CLI through `npx`. This d
53
62
  local clone of the agent-blackboard repository:
54
63
 
55
64
  ```bash
56
- npx -y agent-blackboard@0.6.1 sessions create root-123 --agent claude-code --version 1.0.13
57
- npx -y agent-blackboard@0.6.1 sessions create worker-456 --parent-session-id root-123 \
65
+ npx -y agent-blackboard@0.8.0 sessions create root-123 --agent claude-code --version 1.0.13
66
+ npx -y agent-blackboard@0.8.0 sessions create worker-456 --parent-session-id root-123 \
58
67
  --agent claude-code --version 1.0.13
59
- npx -y agent-blackboard@0.6.1 sessions patch worker-456 --data '{"branch":"fix/retry"}'
60
- npx -y agent-blackboard@0.6.1 sessions patch worker-456 --data '{"repositories":["owner/name"]}'
61
- npx -y agent-blackboard@0.6.1 append --session-id worker-456 '{"repositories":["owner/name"],"note":"found the failing edge case"}'
62
- npx -y agent-blackboard@0.6.1 get --session-id worker-456 --format markdown
63
- npx -y agent-blackboard@0.6.1 snapshot export --root-only --inactive-for-hours 8
64
- npx -y agent-blackboard@0.6.1 snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
68
+ npx -y agent-blackboard@0.8.0 sessions patch worker-456 --data '{"branch":"fix/retry"}'
69
+ npx -y agent-blackboard@0.8.0 sessions patch worker-456 --data '{"repositories":["owner/name"]}'
70
+ npx -y agent-blackboard@0.8.0 append --session-id worker-456 '{"repositories":["owner/name"],"note":"found the failing edge case"}'
71
+ npx -y agent-blackboard@0.8.0 get --session-id worker-456 --format markdown
72
+ npx -y agent-blackboard@0.8.0 snapshot export --root-only --inactive-for-hours 8
73
+ npx -y agent-blackboard@0.8.0 snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
65
74
  --cleanup-token <cleanup-token>
66
- npx -y agent-blackboard@0.6.1 snapshot cleanup --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
75
+ npx -y agent-blackboard@0.8.0 snapshot cleanup --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
67
76
  --directory /tmp/agent-blackboard-partitions-<suffix> --cleanup-token <cleanup-token>
68
77
  ```
69
78
 
@@ -0,0 +1,8 @@
1
+ export interface ParsedSchemaRef {
2
+ id: string;
3
+ version?: number;
4
+ }
5
+ export declare function isValidSchemaId(value: string): boolean;
6
+ export declare function parseSchemaVersion(raw: string): number | undefined;
7
+ export declare function parseSchemaRef(raw: string): ParsedSchemaRef | undefined;
8
+ export declare function formatSchemaRef(id: string, version: number): string;
@@ -0,0 +1,32 @@
1
+ const SCHEMA_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
2
+ const MAX_SCHEMA_ID_LENGTH = 128;
3
+ const POSITIVE_INT_PATTERN = /^[1-9][0-9]*$/;
4
+ export function isValidSchemaId(value) {
5
+ return (value.length > 0 &&
6
+ value.length <= MAX_SCHEMA_ID_LENGTH &&
7
+ !value.includes('..') &&
8
+ value !== '__proto__' &&
9
+ !Object.hasOwn(Object.prototype, value) &&
10
+ SCHEMA_ID_PATTERN.test(value));
11
+ }
12
+ export function parseSchemaVersion(raw) {
13
+ if (!POSITIVE_INT_PATTERN.test(raw))
14
+ return undefined;
15
+ const value = Number.parseInt(raw, 10);
16
+ return Number.isSafeInteger(value) ? value : undefined;
17
+ }
18
+ export function parseSchemaRef(raw) {
19
+ const atIndex = raw.indexOf('@');
20
+ if (atIndex === -1) {
21
+ return isValidSchemaId(raw) ? { id: raw } : undefined;
22
+ }
23
+ const id = raw.slice(0, atIndex);
24
+ const versionRaw = raw.slice(atIndex + 1);
25
+ if (!isValidSchemaId(id))
26
+ return undefined;
27
+ const version = parseSchemaVersion(versionRaw);
28
+ return version === undefined ? undefined : { id, version };
29
+ }
30
+ export function formatSchemaRef(id, version) {
31
+ return `${id}@${version}`;
32
+ }
@@ -0,0 +1,22 @@
1
+ import type { SchemaBundle, SchemaSummary } from '../client/schema-types.mjs';
2
+ export declare const DEFAULT_SCHEMAS_RELATIVE = ".local/agent-blackboard/schemas";
3
+ export interface LocalSchemaManifest {
4
+ revision: number;
5
+ pulledAt: string;
6
+ /** Normalized server base URL this cache was pulled from. */
7
+ source?: string;
8
+ /** SHA-256 digest of all version files so torn writes fail verification on read. */
9
+ bundleHash?: string;
10
+ schemas: Array<SchemaSummary & {
11
+ versions: number[];
12
+ }>;
13
+ }
14
+ /** Normalizes a server `baseUrl` into a canonical cache-origin key. */
15
+ export declare function normalizeRegistrySource(baseUrl: string): string;
16
+ export declare function resolveSchemasDir(cwd: string, env: NodeJS.ProcessEnv, explicitDir?: string): string;
17
+ export declare function readLocalManifest(dir: string): LocalSchemaManifest | undefined;
18
+ export declare function writeLocalBundle(dir: string, bundle: SchemaBundle, now?: () => Date, source?: string): {
19
+ schemaCount: number;
20
+ versionCount: number;
21
+ };
22
+ export declare function readLocalBundle(dir: string, expectedSource?: string): SchemaBundle | undefined;
@@ -0,0 +1,159 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { enclosingWorktreeRoot } from '../session-id/persist.mjs';
5
+ import { formatSchemaRef, isValidSchemaId } from './id.mjs';
6
+ export const DEFAULT_SCHEMAS_RELATIVE = '.local/agent-blackboard/schemas';
7
+ const MANIFEST_FILE = 'manifest.json';
8
+ const VERSIONS_DIR = 'versions';
9
+ const LATEST_DIR = 'latest';
10
+ /** Normalizes a server `baseUrl` into a canonical cache-origin key. */
11
+ export function normalizeRegistrySource(baseUrl) {
12
+ try {
13
+ const url = new URL(baseUrl);
14
+ return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
15
+ }
16
+ catch {
17
+ return baseUrl.replace(/\/+$/, '');
18
+ }
19
+ }
20
+ export function resolveSchemasDir(cwd, env, explicitDir) {
21
+ if (explicitDir)
22
+ return resolve(cwd, explicitDir);
23
+ const envDir = env.AGENT_BLACKBOARD_SCHEMAS_DIR?.trim();
24
+ if (envDir)
25
+ return resolve(cwd, envDir);
26
+ return join(enclosingWorktreeRoot(cwd), DEFAULT_SCHEMAS_RELATIVE);
27
+ }
28
+ function writeFileAtomic(targetPath, content) {
29
+ mkdirSync(dirname(targetPath), { recursive: true });
30
+ const temp = `${targetPath}.${process.pid}.${randomUUID()}.tmp`;
31
+ try {
32
+ writeFileSync(temp, content, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
33
+ renameSync(temp, targetPath);
34
+ }
35
+ catch (error) {
36
+ rmSync(temp, { force: true });
37
+ throw error;
38
+ }
39
+ }
40
+ export function readLocalManifest(dir) {
41
+ try {
42
+ const raw = readFileSync(join(dir, MANIFEST_FILE), 'utf8');
43
+ const parsed = JSON.parse(raw);
44
+ if (typeof parsed === 'object' &&
45
+ parsed !== null &&
46
+ typeof parsed.revision === 'number' &&
47
+ Array.isArray(parsed.schemas)) {
48
+ return parsed;
49
+ }
50
+ return undefined;
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ }
56
+ function removeStaleJsonFiles(dir, keep) {
57
+ for (const name of readdirSync(dir)) {
58
+ if (name.endsWith('.json') && !keep.has(name)) {
59
+ rmSync(join(dir, name), { force: true });
60
+ }
61
+ }
62
+ }
63
+ export function writeLocalBundle(dir, bundle, now = () => new Date(), source) {
64
+ // Validate all ids and version numbers before writing any file so a bad bundle never leaves torn state.
65
+ for (const entry of bundle.schemas) {
66
+ if (!isValidSchemaId(entry.id)) {
67
+ throw new Error(`refusing to write unsafe schema id: ${entry.id}`);
68
+ }
69
+ for (const versionRecord of entry.versions) {
70
+ if (!Number.isSafeInteger(versionRecord.version) || versionRecord.version < 1) {
71
+ throw new Error(`refusing to write invalid schema version for ${entry.id}`);
72
+ }
73
+ }
74
+ }
75
+ const versionsDir = join(dir, VERSIONS_DIR);
76
+ const latestDir = join(dir, LATEST_DIR);
77
+ mkdirSync(versionsDir, { recursive: true });
78
+ mkdirSync(latestDir, { recursive: true });
79
+ const keepLatest = new Set();
80
+ const keepVersions = new Set();
81
+ let versionCount = 0;
82
+ const manifestSchemas = [];
83
+ const hash = createHash('sha256');
84
+ for (const entry of bundle.schemas) {
85
+ const versionNumbers = [];
86
+ for (const versionRecord of entry.versions) {
87
+ const fileName = `${formatSchemaRef(entry.id, versionRecord.version)}.json`;
88
+ const serialized = `${JSON.stringify(versionRecord, null, 2)}\n`;
89
+ keepVersions.add(fileName);
90
+ hash.update(`${fileName}\0${serialized}\0`);
91
+ writeFileAtomic(join(versionsDir, fileName), serialized);
92
+ versionNumbers.push(versionRecord.version);
93
+ versionCount += 1;
94
+ }
95
+ const latestRecord = entry.versions.find((v) => v.version === entry.latestVersion);
96
+ if (latestRecord) {
97
+ const latestFile = `${entry.id}.json`;
98
+ keepLatest.add(latestFile);
99
+ writeFileAtomic(join(latestDir, latestFile), `${JSON.stringify(latestRecord.schema, null, 2)}\n`);
100
+ }
101
+ const { versions: _omit, ...summary } = entry;
102
+ manifestSchemas.push({ ...summary, versions: versionNumbers });
103
+ }
104
+ removeStaleJsonFiles(versionsDir, keepVersions);
105
+ removeStaleJsonFiles(latestDir, keepLatest);
106
+ const manifest = {
107
+ revision: bundle.revision,
108
+ pulledAt: now().toISOString(),
109
+ ...(source === undefined ? {} : { source }),
110
+ bundleHash: hash.digest('hex'),
111
+ schemas: manifestSchemas,
112
+ };
113
+ writeFileAtomic(join(dir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
114
+ return { schemaCount: bundle.schemas.length, versionCount };
115
+ }
116
+ function isPlainObject(value) {
117
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
118
+ }
119
+ function isValidVersionRecord(value, expectedId, expectedVersion) {
120
+ return (isPlainObject(value) &&
121
+ value.id === expectedId &&
122
+ value.version === expectedVersion &&
123
+ typeof value.ref === 'string' &&
124
+ isPlainObject(value.schema));
125
+ }
126
+ export function readLocalBundle(dir, expectedSource) {
127
+ const manifest = readLocalManifest(dir);
128
+ if (!manifest)
129
+ return undefined;
130
+ if (expectedSource !== undefined && manifest.source !== expectedSource)
131
+ return undefined;
132
+ const versionsDir = join(dir, VERSIONS_DIR);
133
+ const schemas = [];
134
+ const hash = createHash('sha256');
135
+ try {
136
+ for (const entry of manifest.schemas) {
137
+ if (!isValidSchemaId(entry.id) || !Array.isArray(entry.versions))
138
+ return undefined;
139
+ const versions = [];
140
+ for (const versionNum of entry.versions) {
141
+ const fileName = `${formatSchemaRef(entry.id, versionNum)}.json`;
142
+ const raw = readFileSync(join(versionsDir, fileName), 'utf8');
143
+ const parsed = JSON.parse(raw);
144
+ if (!isValidVersionRecord(parsed, entry.id, versionNum))
145
+ return undefined;
146
+ hash.update(`${fileName}\0${raw}\0`);
147
+ versions.push(parsed);
148
+ }
149
+ const { versions: _v, ...summary } = entry;
150
+ schemas.push({ ...summary, versions });
151
+ }
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
156
+ if (manifest.bundleHash !== hash.digest('hex'))
157
+ return undefined;
158
+ return { revision: manifest.revision, schemas };
159
+ }
@@ -0,0 +1,3 @@
1
+ import type { SchemaBundle, SchemaValidationResult } from '../client/schema-types.mjs';
2
+ export declare function validateAgainstBundle(bundle: SchemaBundle, schemaRefRaw: string, data: unknown): SchemaValidationResult;
3
+ export declare function validateAgainstLocalSchemas(dir: string, schemaRefRaw: string, data: unknown): SchemaValidationResult;
@@ -0,0 +1,70 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ import addFormats from 'ajv-formats';
3
+ import { formatSchemaRef, parseSchemaRef } from './id.mjs';
4
+ import { readLocalBundle } from './local-store.mjs';
5
+ const registerFormats = addFormats;
6
+ export function validateAgainstBundle(bundle, schemaRefRaw, data) {
7
+ const parsed = parseSchemaRef(schemaRefRaw);
8
+ if (!parsed) {
9
+ throw new Error(`Invalid schema reference: ${schemaRefRaw}`);
10
+ }
11
+ const entry = bundle.schemas.find((s) => s.id === parsed.id);
12
+ if (!entry) {
13
+ throw new Error(`Schema not found in local copy: ${parsed.id}`);
14
+ }
15
+ if (entry.deprecatedAt !== null) {
16
+ throw new Error(`Schema is deprecated: ${entry.id}`);
17
+ }
18
+ const targetVersion = parsed.version ?? entry.latestVersion;
19
+ const targetRecord = entry.versions.find((v) => v.version === targetVersion);
20
+ if (!targetRecord) {
21
+ throw new Error(`Schema version not found in local copy: ${formatSchemaRef(parsed.id, targetVersion)}`);
22
+ }
23
+ const ajv = new Ajv2020({
24
+ strictSchema: true,
25
+ strictTypes: false,
26
+ strictRequired: false,
27
+ allErrors: true,
28
+ });
29
+ ajv.addKeyword('$anchor');
30
+ registerFormats(ajv);
31
+ const ref = formatSchemaRef(entry.id, targetRecord.version);
32
+ let validate;
33
+ try {
34
+ for (const schemaEntry of bundle.schemas) {
35
+ for (const ver of schemaEntry.versions) {
36
+ ajv.addSchema(structuredClone(ver.schema), formatSchemaRef(schemaEntry.id, ver.version));
37
+ }
38
+ const latest = schemaEntry.versions.find((v) => v.version === schemaEntry.latestVersion);
39
+ if (latest) {
40
+ ajv.addSchema(structuredClone(latest.schema), schemaEntry.id);
41
+ }
42
+ }
43
+ validate = ajv.getSchema(ref);
44
+ }
45
+ catch (error) {
46
+ throw new Error(`Local schema ${ref} failed to compile: ${error.message}`, {
47
+ cause: error,
48
+ });
49
+ }
50
+ if (validate.$async) {
51
+ throw new Error(`Local schema ${ref} uses unsupported $async validation`);
52
+ }
53
+ const valid = Boolean(validate(data));
54
+ const errors = valid
55
+ ? []
56
+ : validate.errors.map((err) => ({
57
+ instancePath: err.instancePath,
58
+ schemaPath: err.schemaPath,
59
+ keyword: err.keyword,
60
+ message: String(err.message),
61
+ }));
62
+ return { valid, schema: ref, revision: bundle.revision, errors };
63
+ }
64
+ export function validateAgainstLocalSchemas(dir, schemaRefRaw, data) {
65
+ const bundle = readLocalBundle(dir);
66
+ if (!bundle) {
67
+ throw new Error(`No valid local schema registry copy found in ${dir}. Run: agent-blackboard schemas pull`);
68
+ }
69
+ return validateAgainstBundle(bundle, schemaRefRaw, data);
70
+ }
@@ -0,0 +1,44 @@
1
+ /** Every coding-agent harness this package can recognize from its environment. */
2
+ export declare const HARNESS_IDS: readonly ['claude', 'codex', 'grok', 'cursor'];
3
+ export type HarnessId = (typeof HARNESS_IDS)[number];
4
+ /**
5
+ * The precedence used when picking a single harness session id from the environment, for callers
6
+ * that need one answer (e.g. agent derivation). Ambient resolution in `resolveSessionIdentity`
7
+ * applies its own, finer-grained rules instead.
8
+ */
9
+ export declare const HARNESS_SESSION_PRECEDENCE: readonly HarnessId[];
10
+ /** Every harness signal present in an environment, without choosing between them. */
11
+ export interface HarnessEnvironment {
12
+ readonly claude: {
13
+ readonly compatMode: boolean;
14
+ readonly sessionId?: string;
15
+ };
16
+ readonly codex: {
17
+ readonly sessionId?: string;
18
+ };
19
+ readonly cursor: {
20
+ readonly agentMarker: boolean;
21
+ readonly sessionId?: string;
22
+ };
23
+ readonly grok: {
24
+ readonly agentMarker: boolean;
25
+ readonly hookEvent: boolean;
26
+ readonly sessionId?: string;
27
+ };
28
+ }
29
+ export interface HarnessSessionIdentity {
30
+ readonly harness: HarnessId;
31
+ readonly sessionId: string;
32
+ }
33
+ type Env = Readonly<Record<string, string | undefined>>;
34
+ /**
35
+ * Reads the env-marker table: `CLAUDECODE`/`CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`,
36
+ * `CURSOR_AGENT`/`CURSOR_SESSION_ID`, and `GROK_AGENT`/`GROK_HOOK_EVENT`/`GROK_SESSION_ID`.
37
+ * Empty values count as absent. Never throws.
38
+ */
39
+ export declare function inspectHarnessEnvironment(env: Env): HarnessEnvironment;
40
+ /** The first harness in `precedence` with a session id, or `undefined` when none has one. */
41
+ export declare function selectHarnessSession(environment: HarnessEnvironment, precedence: readonly HarnessId[]): HarnessSessionIdentity | undefined;
42
+ /** Classifies a transcript path by the harness directory layout it lives under. */
43
+ export declare function transcriptPathHarness(transcriptPath: string | undefined): HarnessId | undefined;
44
+ export {};
@@ -0,0 +1,61 @@
1
+ /** Every coding-agent harness this package can recognize from its environment. */
2
+ export const HARNESS_IDS = ['claude', 'codex', 'grok', 'cursor'];
3
+ /**
4
+ * The precedence used when picking a single harness session id from the environment, for callers
5
+ * that need one answer (e.g. agent derivation). Ambient resolution in `resolveSessionIdentity`
6
+ * applies its own, finer-grained rules instead.
7
+ */
8
+ export const HARNESS_SESSION_PRECEDENCE = [
9
+ 'codex',
10
+ 'claude',
11
+ 'cursor',
12
+ 'grok',
13
+ ];
14
+ function session(value) {
15
+ return value ? { sessionId: value } : {};
16
+ }
17
+ /**
18
+ * Reads the env-marker table: `CLAUDECODE`/`CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`,
19
+ * `CURSOR_AGENT`/`CURSOR_SESSION_ID`, and `GROK_AGENT`/`GROK_HOOK_EVENT`/`GROK_SESSION_ID`.
20
+ * Empty values count as absent. Never throws.
21
+ */
22
+ export function inspectHarnessEnvironment(env) {
23
+ return {
24
+ claude: {
25
+ compatMode: env.CLAUDECODE === '1',
26
+ ...session(env.CLAUDE_CODE_SESSION_ID),
27
+ },
28
+ codex: session(env.CODEX_THREAD_ID),
29
+ cursor: {
30
+ agentMarker: Boolean(env.CURSOR_AGENT),
31
+ ...session(env.CURSOR_SESSION_ID),
32
+ },
33
+ grok: {
34
+ agentMarker: Boolean(env.GROK_AGENT),
35
+ hookEvent: Boolean(env.GROK_HOOK_EVENT),
36
+ ...session(env.GROK_SESSION_ID),
37
+ },
38
+ };
39
+ }
40
+ /** The first harness in `precedence` with a session id, or `undefined` when none has one. */
41
+ export function selectHarnessSession(environment, precedence) {
42
+ for (const harness of precedence) {
43
+ const sessionId = environment[harness].sessionId;
44
+ if (sessionId)
45
+ return { harness, sessionId };
46
+ }
47
+ return undefined;
48
+ }
49
+ /** Classifies a transcript path by the harness directory layout it lives under. */
50
+ export function transcriptPathHarness(transcriptPath) {
51
+ const path = transcriptPath?.replaceAll('\\', '/');
52
+ if (!path)
53
+ return undefined;
54
+ if (path.includes('/.codex/') && path.endsWith('.jsonl'))
55
+ return 'codex';
56
+ if (path.includes('/.grok/') && path.endsWith('/updates.jsonl'))
57
+ return 'grok';
58
+ if (path.includes('/.claude/projects/') && path.endsWith('.jsonl'))
59
+ return 'claude';
60
+ return undefined;
61
+ }
@@ -0,0 +1,19 @@
1
+ import type { HarnessId } from './harness.mjs';
2
+ /** A harness hook's JSON payload. Only its session-id keys and `cwd` are read. */
3
+ export type HookPayload = Readonly<Record<string, unknown>>;
4
+ type Env = Readonly<Record<string, string | undefined>>;
5
+ /** The first key in `keys` holding a valid session id, or `''`. */
6
+ export declare function hookPayloadSessionId(payload: HookPayload, keys?: readonly string[]): string;
7
+ export declare function cursorPayloadSessionId(payload: HookPayload): string;
8
+ export declare function grokHookSessionId(payload: HookPayload, env: Env): string;
9
+ /**
10
+ * SessionStart hook: persists (or generates) the Cursor/Grok id. No-op for other runtimes. Writes
11
+ * under the payload's `cwd` when present, else `root`; either is normalized to its worktree root.
12
+ */
13
+ export declare function persistHookSessionStart(runtime: HarnessId | undefined, payload: HookPayload, env: Env, root: string, generateId?: () => string): {
14
+ generated: boolean;
15
+ sessionId: string;
16
+ } | undefined;
17
+ /** Later hooks: refreshes the persisted Cursor/Grok id when the payload carries a real one. */
18
+ export declare function persistHookRealSessionId(runtime: HarnessId | undefined, payload: HookPayload, env: Env, root: string): void;
19
+ export {};
@@ -0,0 +1,52 @@
1
+ import { persistRealSessionId, resolveAndPersistSessionStartId, } from './persist.mjs';
2
+ import { sanitizeSessionId } from './valid-id.mjs';
3
+ /** The first key in `keys` holding a valid session id, or `''`. */
4
+ export function hookPayloadSessionId(payload, keys = ['session_id', 'sessionId']) {
5
+ for (const key of keys) {
6
+ const id = sanitizeSessionId(payload[key]);
7
+ if (id !== '')
8
+ return id;
9
+ }
10
+ return '';
11
+ }
12
+ export function cursorPayloadSessionId(payload) {
13
+ return hookPayloadSessionId(payload, ['session_id', 'sessionId', 'conversation_id']);
14
+ }
15
+ export function grokHookSessionId(payload, env) {
16
+ return sanitizeSessionId(env.GROK_SESSION_ID) || hookPayloadSessionId(payload);
17
+ }
18
+ // The payload's own `cwd` (when present) decides the worktree, so a hook process launched from an
19
+ // outer checkout still writes where resolution from that cwd will read.
20
+ function hookRoot(payload, root) {
21
+ return typeof payload.cwd === 'string' && payload.cwd !== '' ? payload.cwd : root;
22
+ }
23
+ // Claude and Codex expose their session id to every process through env, so only the
24
+ // Claude-compat runtimes without one (Grok and Cursor) persist it for later hook-less readers.
25
+ function hookRuntimeSessionId(runtime, payload, env) {
26
+ if (runtime === 'grok')
27
+ return { harness: 'grok', sessionId: grokHookSessionId(payload, env) };
28
+ if (runtime === 'cursor')
29
+ return { harness: 'cursor', sessionId: cursorPayloadSessionId(payload) };
30
+ return undefined;
31
+ }
32
+ /**
33
+ * SessionStart hook: persists (or generates) the Cursor/Grok id. No-op for other runtimes. Writes
34
+ * under the payload's `cwd` when present, else `root`; either is normalized to its worktree root.
35
+ */
36
+ export function persistHookSessionStart(runtime, payload, env, root, generateId) {
37
+ const hook = hookRuntimeSessionId(runtime, payload, env);
38
+ if (hook === undefined)
39
+ return undefined;
40
+ return resolveAndPersistSessionStartId({
41
+ harness: hook.harness,
42
+ root: hookRoot(payload, root),
43
+ generateId,
44
+ payloadId: hook.sessionId,
45
+ });
46
+ }
47
+ /** Later hooks: refreshes the persisted Cursor/Grok id when the payload carries a real one. */
48
+ export function persistHookRealSessionId(runtime, payload, env, root) {
49
+ const hook = hookRuntimeSessionId(runtime, payload, env);
50
+ if (hook !== undefined)
51
+ persistRealSessionId(hookRoot(payload, root), hook.harness, hook.sessionId);
52
+ }
@@ -0,0 +1,53 @@
1
+ /** Harnesses that do not expose their session id to every child process, so it is persisted. */
2
+ export type PersistedHarness = 'codex' | 'cursor' | 'grok';
3
+ /** Persisted-file locations, relative to a worktree root. Each holds one id and a newline. */
4
+ export declare const SESSION_PERSIST_RELATIVE: {
5
+ readonly codex: '.local/codex-session-id';
6
+ readonly cursor: '.local/cursor-session-id';
7
+ readonly grok: '.local/grok-session-id';
8
+ };
9
+ /** The nearest ancestor of `cwd` (inclusive) containing `.git`, or `cwd` itself if none does. */
10
+ export declare function enclosingWorktreeRoot(cwd: string): string;
11
+ /**
12
+ * The persisted-file path for `harness`. `root` may be any directory inside the worktree: it is
13
+ * normalized through `enclosingWorktreeRoot`, so every read and write in this module agrees on the
14
+ * same file regardless of which subdirectory a caller runs from. A directory without its own
15
+ * `.git` inside a repository therefore maps to that repository's `.local/`.
16
+ */
17
+ export declare function sessionPersistPath(root: string, harness: PersistedHarness): string;
18
+ /**
19
+ * Reads a persisted id. Missing or malformed files yield `undefined`, unless `strict`, where a
20
+ * malformed file or any read error other than `ENOENT` throws.
21
+ */
22
+ export declare function readPersistedSessionId(root: string, harness: PersistedHarness, options?: {
23
+ strict?: boolean;
24
+ }): string | undefined;
25
+ /** Persists a real (harness-supplied) id; invalid or empty ids and write failures are ignored. */
26
+ export declare function persistRealSessionId(root: string, harness: PersistedHarness, sessionId: string): void;
27
+ /**
28
+ * Session-start persistence for hook callers: a real payload id wins and is written; otherwise a
29
+ * valid persisted id is reused; otherwise `<harness>-<uuid>` is generated and written. Never
30
+ * throws on write failure.
31
+ */
32
+ export declare function resolveAndPersistSessionStartId(options: {
33
+ root: string;
34
+ harness: PersistedHarness;
35
+ payloadId: string;
36
+ generateId?: (() => string) | undefined;
37
+ }): {
38
+ generated: boolean;
39
+ sessionId: string;
40
+ };
41
+ /**
42
+ * Root Codex persistence. Unlike the hook path, an interactive root Codex caller cannot continue
43
+ * without a durable id, so write and read-back failures surface as errors.
44
+ */
45
+ export declare function resolveAndPersistRootCodexSessionId(options: {
46
+ root: string;
47
+ payloadId?: string | undefined;
48
+ newSession?: boolean | undefined;
49
+ generateId?: (() => string) | undefined;
50
+ }): {
51
+ generated: boolean;
52
+ sessionId: string;
53
+ };