@brightbeamai/chap-coordinator 0.2.10 → 0.2.12

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/canonical.ts","../src/crypto.ts","../src/ids.ts","../src/jsonrpc.ts","../src/patch.ts","../src/storage/store.ts","../src/api.ts","../src/types.ts","../src/profiles/audit_scitt.ts","../src/profiles/control.ts","../src/profiles/deliberation.ts","../src/profiles/handoff.ts","../src/profiles/routing.ts","../src/profiles/security_signed.ts","../src/profiles/whisper.ts","../src/coordinator.ts","../src/policy.ts","../src/transports/wrap.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/canonical\n *\n * Deterministic JSON canonicalisation for CHAP. CHAP signs and hashes the\n * canonicalisation of envelopes.\n *\n * Follows RFC 8785 (JCS) for objects, arrays, strings, booleans, and null,\n * with one deliberate restriction on numbers. RFC 8785 mandates the\n * ECMAScript number-to-string algorithm, which is hard to reproduce\n * byte-identically across languages; a subtle mismatch would make a chain\n * written by one implementation fail verification against another. To make\n * cross-implementation agreement provable rather than approximate, a CHAP\n * canonical number MUST be an integer within the safe-integer range\n * (abs value <= Number.MAX_SAFE_INTEGER). Non-integers and larger\n * magnitudes are rejected: represent them as strings. The Python reference\n * enforces the identical rule.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport const ZERO_HASH = \"sha256:\" + \"0\".repeat(64);\n\nconst NON_INTEGER_ERROR =\n 'CHAP canonical numbers must be integers; represent decimals as strings ' +\n '(e.g. \"8.2\") so the hash is deterministic across implementations.';\nconst NUMBER_RANGE_ERROR =\n \"CHAP canonical integers must be within the safe-integer range \" +\n \"(abs value <= Number.MAX_SAFE_INTEGER); represent larger numbers as strings.\";\n\nfunction canonicalString(s: string): string {\n // JSON string escaping; \\uXXXX for control chars\n return JSON.stringify(s);\n}\n\nfunction canonicalNumber(n: number): string {\n if (!Number.isFinite(n)) {\n throw new Error(\n \"Non-finite numbers are not permitted in a CHAP canonical value\",\n );\n }\n if (!Number.isInteger(n)) {\n throw new Error(NON_INTEGER_ERROR);\n }\n if (Math.abs(n) > Number.MAX_SAFE_INTEGER) {\n throw new Error(NUMBER_RANGE_ERROR);\n }\n // A safe integer's toString() is always plain decimal digits (no\n // exponent), byte-identical to Python's str(int(...)).\n return n.toString();\n}\n\nfunction canon(value: unknown): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return canonicalString(value);\n if (typeof value === \"number\") return canonicalNumber(value);\n if (Array.isArray(value)) {\n return \"[\" + value.map(canon).join(\",\") + \"]\";\n }\n if (typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const key of keys) {\n parts.push(canonicalString(key) + \":\" + canon(obj[key]));\n }\n return \"{\" + parts.join(\",\") + \"}\";\n }\n throw new TypeError(`Cannot canonicalise value of type ${typeof value}`);\n}\n\n/** Return the JCS canonical UTF-8 bytes for a JSON-compatible value. */\nexport function canonicalize(value: unknown): Buffer {\n return Buffer.from(canon(value), \"utf-8\");\n}\n\n/** Return ``sha256:<64-hex>`` digest of bytes. */\nexport function sha256Hex(data: Buffer | string): string {\n const h = createHash(\"sha256\");\n h.update(typeof data === \"string\" ? Buffer.from(data, \"utf-8\") : data);\n return \"sha256:\" + h.digest(\"hex\");\n}\n\n/** Convenience: content hash for an artefact payload via JCS. */\nexport function contentHash(content: unknown): string {\n return sha256Hex(canonicalize(content));\n}\n","/**\n * @brightbeamai/chap-coordinator/crypto\n *\n * Ed25519 signing/verification for the security-signed/1.0 profile.\n *\n * Uses Node's built-in crypto (no external dependencies). Keys are\n * represented as RFC 7517 JWKs with kty=OKP, crv=Ed25519.\n */\n\nimport {\n createPrivateKey,\n createPublicKey,\n KeyObject,\n sign as nodeSign,\n verify as nodeVerify,\n randomBytes,\n createHash,\n} from \"node:crypto\";\n\nconst ED25519_OID = Buffer.from(\"302a300506032b6570032100\", \"hex\");\n\nfunction b64urlNoPad(buf: Buffer): string {\n return buf.toString(\"base64\").replace(/=+$/, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\nfunction b64urlDecode(s: string): Buffer {\n const pad = \"=\".repeat((4 - (s.length % 4)) % 4);\n return Buffer.from(s.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad, \"base64\");\n}\n\nexport interface Jwk {\n kty: \"OKP\";\n crv: \"Ed25519\";\n kid: string;\n x: string;\n d?: string;\n use?: string;\n alg?: string;\n}\n\n/**\n * Deterministically derive a 32-byte Ed25519 seed from a participant URI.\n * Demo / test only. production deployments supply real keys.\n */\nexport function deriveSeed(uri: string): Buffer {\n return createHash(\"sha256\").update(\"chap:\" + uri).digest();\n}\n\n/**\n * Build a Node KeyObject (private key) from a raw 32-byte Ed25519 seed.\n */\nexport function privateKeyFromSeed(seed: Buffer): KeyObject {\n if (seed.length !== 32) {\n throw new Error(\"Ed25519 seed must be 32 bytes\");\n }\n // PKCS#8 DER for Ed25519: SEQ(SEQ(OID), OCTET(OCTET(seed)))\n const pkcs8 = Buffer.concat([\n Buffer.from(\"302e020100300506032b657004220420\", \"hex\"),\n seed,\n ]);\n return createPrivateKey({ key: pkcs8, format: \"der\", type: \"pkcs8\" });\n}\n\n/** Public key bytes (32 bytes) from a private key. */\nexport function publicKeyBytes(privateKey: KeyObject): Buffer {\n const pub = createPublicKey(privateKey);\n const der = pub.export({ format: \"der\", type: \"spki\" }) as Buffer;\n // SPKI for Ed25519 is the OID prefix + 32-byte raw public key\n return der.subarray(der.length - 32);\n}\n\n/** Public KeyObject from raw 32-byte Ed25519 public key. */\nexport function publicKeyFromRaw(raw: Buffer): KeyObject {\n if (raw.length !== 32) {\n throw new Error(\"Ed25519 public key must be 32 bytes\");\n }\n const der = Buffer.concat([ED25519_OID, raw]);\n return createPublicKey({ key: der, format: \"der\", type: \"spki\" });\n}\n\n/** Render a JWK from a Node private KeyObject. */\nexport function jwkFromPrivateKey(uri: string, key: KeyObject): Jwk {\n const pub = publicKeyBytes(key);\n return {\n kty: \"OKP\",\n crv: \"Ed25519\",\n kid: createHash(\"sha256\").update(uri).digest(\"hex\").slice(0, 16),\n use: \"sig\",\n alg: \"EdDSA\",\n x: b64urlNoPad(pub),\n };\n}\n\n/** Sign canonical bytes; return ``ed25519:<kid>:<base64>``. */\nexport function signEnvelope(canonical: Buffer, privateKey: KeyObject, kid: string): string {\n const sig = nodeSign(null, canonical, privateKey);\n return `ed25519:${kid}:${sig.toString(\"base64\")}`;\n}\n\n/** Verify a CHAP sig string against canonical bytes and a public key. */\nexport function verifyEnvelope(canonical: Buffer, sigTag: string, publicKey: KeyObject): boolean {\n if (!sigTag.startsWith(\"ed25519:\")) return false;\n const parts = sigTag.split(\":\");\n if (parts.length < 2) return false;\n const sigB64 = parts[parts.length - 1];\n try {\n const sig = Buffer.from(sigB64, \"base64\");\n return nodeVerify(null, canonical, publicKey, sig);\n } catch {\n return false;\n }\n}\n\n/** Parse a JWK x (base64url) into a Node public KeyObject. */\nexport function publicKeyFromJwk(jwk: Jwk): KeyObject {\n return publicKeyFromRaw(b64urlDecode(jwk.x));\n}\n\n/** Demo helper: build a deterministic keypair + JWK for a URI. */\nexport function deriveKeypair(uri: string): { privateKey: KeyObject; jwk: Jwk } {\n const seed = deriveSeed(uri);\n const privateKey = privateKeyFromSeed(seed);\n return { privateKey, jwk: jwkFromPrivateKey(uri, privateKey) };\n}\n\nexport { b64urlNoPad, b64urlDecode };\n","/**\n * @brightbeamai/chap-coordinator/ids\n *\n * ULID-format identifier generation. Supports a deterministic mode\n * for tests/demos so byte-for-byte replay works.\n */\n\nconst ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\"; // Crockford\n\nfunction encode(value: bigint, length: number): string {\n let out = \"\";\n for (let i = 0; i < length; i++) {\n const idx = Number(value & 31n);\n out = ALPHABET[idx] + out;\n value >>= 5n;\n }\n return out;\n}\n\nexport class IdFactory {\n private counter: bigint;\n private clockMs: number;\n\n constructor(\n public readonly deterministic: boolean = false,\n seed: bigint = 0n,\n startMs: number = 1_700_000_000_000,\n ) {\n this.counter = seed;\n this.clockMs = startMs;\n }\n\n nowMs(): number {\n if (this.deterministic) {\n this.clockMs += 1;\n return this.clockMs;\n }\n return Date.now();\n }\n\n private randomness(): bigint {\n if (this.deterministic) {\n this.counter += 1n;\n return (this.counter * 0x9E3779B97F4A7C15n) & ((1n << 80n) - 1n);\n }\n // 80 bits of randomness. `globalThis.crypto` is standard from Node 19\n // and present in every other supported runtime, so there is no fallback\n // path: the previous one called `require`, which does not exist in an\n // ES module and so threw on any runtime without the global.\n const buf = new Uint8Array(10);\n crypto.getRandomValues(buf);\n let n = 0n;\n for (const b of buf) n = (n << 8n) | BigInt(b);\n return n;\n }\n\n ulid(): string {\n const ts = BigInt(this.nowMs()) & ((1n << 48n) - 1n);\n const rand = this.randomness();\n return encode(ts, 10) + encode(rand, 16);\n }\n\n envelopeId(): string { return this.ulid(); }\n taskId(): string { return \"tsk_\" + this.ulid(); }\n artefactId(): string { return \"art_\" + this.ulid(); }\n logicalId(): string { return \"lgl_\" + this.ulid(); }\n workspaceId(): string { return \"wsp_\" + this.ulid(); }\n deliberationId(): string { return \"dlb_\" + this.ulid(); }\n handoffId(): string { return \"hnd_\" + this.ulid(); }\n snapshotId(): string { return \"snp_\" + this.ulid(); }\n}\n","/**\n * @brightbeamai/chap-coordinator/jsonrpc\n *\n * Error codes (JSON-RPC standard + CHAP private range) and helpers.\n *\n * Error code allocations come directly from each profile spec. See\n * profiles/*.md for the authoritative definitions.\n */\n\nexport const E = {\n // JSON-RPC 2.0 standard\n PARSE: -32700,\n REQUEST: -32600,\n METHOD: -32601,\n PARAMS: -32602,\n INTERNAL: -32603,\n\n // review/1.0 profile\n NOT_REVIEWABLE: -32010,\n NOT_AUTHORISED: -32011,\n PATCH_FAILED: -32012,\n REVIEW_LAPSED: -32013,\n REVIEW_ALREADY_OPEN: -32014,\n\n // whisper/1.0 profile (profiles/whisper.md S6)\n WHISPER_ALREADY_ANSWERED: -32020,\n WHISPER_LAPSED: -32021,\n WHISPER_OPTION_NOT_IN_SET: -32022,\n\n // deliberation/1.0 profile (profiles/deliberation.md S5)\n DELIB_VOTER_NOT_IN_LIST: -32030,\n DELIB_ALREADY_VOTED: -32031,\n DELIB_CLOSED_OR_LAPSED: -32032,\n DELIB_UNKNOWN_RULE: -32033,\n\n // modes/1.0 profile (profiles/modes.md S6)\n MODE_CEILING_EXCEEDED: -32040,\n MODE_STEP_UP_REQUIRED: -32041,\n\n // handoff/1.0 profile (profiles/handoff.md S6)\n HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER: -32050,\n HANDOFF_ALREADY_RESOLVED: -32051,\n HANDOFF_RECIPIENT_NOT_MEMBER: -32052,\n\n // control/1.0 profile (profiles/control.md S6)\n CONTROL_STEP_UP_REQUIRED: -32060,\n CONTROL_NOT_AUTHORISED: -32061,\n CONTROL_SNAPSHOT_NOT_FOUND: -32062,\n CONTROL_WORKSPACE_PAUSED: -32063,\n\n // security-signed/1.0 profile (profiles/security-signed.md S7)\n SIG_VERIFY_FAILED: -32070,\n SIG_KEY_NOT_FOUND: -32071,\n SIG_KEY_REVOKED: -32072,\n SIG_ROTATION_KEY_MISMATCH: -32073,\n SIG_ARTEFACT_DIGEST_MISMATCH: -32074,\n\n // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)\n SCITT_UNREACHABLE: -32080,\n SCITT_STATEMENT_REJECTED: -32081,\n SCITT_RECEIPT_INVALID: -32082,\n\n // identity-oidc/1.0 profile (profiles/identity-oidc.md S8)\n OIDC_STEP_UP_REQUIRED: -32402,\n OIDC_TOKEN_INVALID: -32403,\n OIDC_CNF_MISMATCH: -32404,\n OIDC_SCOPE_MISSING: -32405,\n\n // identity-vc/1.0 profile (profiles/identity-vc.md S8)\n VC_VP_INVALID: -32410,\n VC_HOLDER_BINDING_INVALID: -32411,\n VC_CREDENTIAL_REVOKED: -32412,\n VC_SCHEMA_UNKNOWN: -32413,\n\n // routing/1.0 profile (profiles/routing.md S3-S5)\n ROUTING_NO_ELIGIBLE_ASSIGNEE: -32510,\n ROUTING_POLICY_VIOLATION: -32511,\n ROUTING_AUTO_ESCALATION_TRIGGERED: -32512,\n ROUTING_CANDIDATES_EMPTY: -32513,\n ROUTING_DEPTH_NOT_APPLICABLE: -32514,\n ROUTING_POLICY_UNREACHABLE: -32515,\n ROUTING_ESC_TARGET_UNAVAILABLE: -32516,\n} as const;\n\nexport function rpcError(code: number, message: string, data?: unknown) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\nexport function isValidEnvelope(env: unknown): boolean {\n if (typeof env !== \"object\" || env === null) return false;\n const e = env as Record<string, unknown>;\n return e.jsonrpc === \"2.0\";\n}\n","/**\n * @brightbeamai/chap-coordinator/patch\n *\n * RFC 6902 JSON Patch implementation, plus a small diff computer that\n * produces a patch from two values. Used by the Coordinator for\n * `decide.override` apply and by the playground UI (in the browser) to\n * compute the patch from a textarea edit.\n *\n * Implements all six RFC 6902 operations (add, remove, replace, move,\n * copy, test) with semantics identical to the Python reference. Path\n * segments that enable prototype pollution in a JavaScript runtime\n * (`__proto__`, `constructor`, `prototype`) are rejected, so the two\n * references accept and reject exactly the same patches.\n */\n\nimport type { JsonPatchOp } from \"./types.js\";\n\nexport class PatchError extends Error {}\n\n// Rejected in every JSON Pointer segment: these enable prototype pollution.\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction unescape(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction splitPath(path: string): string[] {\n if (path === \"\") return [];\n if (!path.startsWith(\"/\")) {\n throw new PatchError(`JSON Pointer must start with '/': ${JSON.stringify(path)}`);\n }\n const segments = path.slice(1).split(\"/\").map(unescape);\n for (const seg of segments) {\n if (DANGEROUS_KEYS.has(seg)) {\n throw new PatchError(`Refusing unsafe path segment ${JSON.stringify(seg)}`);\n }\n }\n return segments;\n}\n\n/** Navigate to the parent of the target; return [parent, lastKey]. */\nfunction navigate(doc: any, parts: string[]): [any, string | number] {\n if (parts.length === 0) {\n throw new PatchError(\"Cannot operate on root with this helper.\");\n }\n let parent = doc;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (Array.isArray(parent)) {\n const idx = Number(part);\n if (!Number.isInteger(idx) || idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[idx];\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, part)) {\n throw new PatchError(`Path not found: /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[part];\n } else {\n throw new PatchError(`Cannot traverse into ${typeof parent} at ${JSON.stringify(part)}`);\n }\n }\n const last = parts[parts.length - 1];\n if (Array.isArray(parent)) {\n if (last === \"-\") return [parent, \"-\"];\n const idx = Number(last);\n if (!Number.isInteger(idx)) {\n throw new PatchError(`Array index expected at ${JSON.stringify(last)}`);\n }\n return [parent, idx];\n }\n return [parent, last];\n}\n\nfunction getAt(doc: any, path: string): any {\n const parts = splitPath(path);\n if (parts.length === 0) return doc;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") throw new PatchError(\"Cannot read '-' position.\");\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) throw new PatchError(`Index out of range: ${path}`);\n return parent[idx];\n }\n if (\n parent === null ||\n typeof parent !== \"object\" ||\n !Object.prototype.hasOwnProperty.call(parent, key)\n ) {\n throw new PatchError(`Path not found: ${path}`);\n }\n return parent[key as string];\n}\n\nfunction clone<T>(v: T): T {\n return v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T);\n}\n\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;\n return true;\n }\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (!deepEqual(a[k], b[k])) return false;\n }\n return true;\n}\n\nfunction applyOne(doc: any, op: JsonPatchOp): any {\n const kind = op.op;\n const path = op.path ?? \"\";\n\n if (kind === \"add\") {\n if (!(\"value\" in op)) throw new PatchError(\"'add' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value; // replace whole document\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") {\n parent.push(op.value);\n } else {\n const idx = key as number;\n if (idx < 0 || idx > parent.length) {\n throw new PatchError(`Index out of range for add: ${path}`);\n }\n parent.splice(idx, 0, op.value);\n }\n } else if (parent !== null && typeof parent === \"object\") {\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot add into ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"replace\") {\n if (!(\"value\" in op)) throw new PatchError(\"'replace' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[idx] = op.value;\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot replace in ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"remove\") {\n const parts = splitPath(path);\n if (parts.length === 0) throw new PatchError(\"Cannot remove root.\");\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range for remove: ${path}`);\n }\n parent.splice(idx, 1);\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for remove: ${path}`);\n }\n delete parent[key as string];\n } else {\n throw new PatchError(`Cannot remove from ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"copy\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'copy' requires 'from'\");\n const value = clone(getAt(doc, src));\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"move\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'move' requires 'from'\");\n // RFC 6902 4.4: 'from' MUST NOT be a proper prefix of 'path'.\n if (path.startsWith(src + \"/\")) {\n throw new PatchError(\"'move' cannot move a location into its own child.\");\n }\n const value = clone(getAt(doc, src));\n doc = applyOne(doc, { op: \"remove\", path: src });\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"test\") {\n if (!(\"value\" in op)) throw new PatchError(\"'test' requires 'value'\");\n const actual = getAt(doc, path);\n if (!deepEqual(actual, op.value)) throw new PatchError(`'test' failed at ${path}`);\n return doc;\n }\n\n throw new PatchError(`Unsupported op: ${JSON.stringify(kind)}`);\n}\n\nconst MAX_PATCH_OPS = 1000;\nconst MAX_DOCUMENT_NODES = 100_000;\n\nfunction nodeCount(value: unknown): number {\n if (Array.isArray(value)) {\n let n = 1;\n for (const v of value) n += nodeCount(v);\n return n;\n }\n if (value !== null && typeof value === \"object\") {\n let n = 1;\n for (const v of Object.values(value as Record<string, unknown>)) n += nodeCount(v);\n return n;\n }\n return 1;\n}\n\nexport function applyJsonPatch(doc: unknown, ops: JsonPatchOp[]): unknown {\n if (ops.length > MAX_PATCH_OPS) {\n throw new PatchError(`Patch has too many operations (${ops.length} > ${MAX_PATCH_OPS})`);\n }\n let out: any = JSON.parse(JSON.stringify(doc));\n for (const op of ops) {\n out = applyOne(out, op);\n if (nodeCount(out) > MAX_DOCUMENT_NODES) {\n throw new PatchError(`Patched document exceeds the node limit (${MAX_DOCUMENT_NODES})`);\n }\n }\n return out;\n}\n\n// ============================================================\n// diff: produce a patch that transforms `from` into `to`\n// ============================================================\n\n/**\n * Compute an RFC 6902 patch that, when applied to `from`, produces\n * `to`. Walks objects key-by-key; arrays use a shallow whole-array\n * replace if any element differs. Sufficient for the playground's\n * draft-edit use case where drafts are small JSON objects.\n */\nexport function diffJsonPatch(from: unknown, to: unknown, basePath = \"\"): JsonPatchOp[] {\n const ops: JsonPatchOp[] = [];\n\n if (typeof from !== typeof to || Array.isArray(from) !== Array.isArray(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n return ops;\n }\n\n if (from === null || to === null || typeof from !== \"object\") {\n if (from !== to) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n if (Array.isArray(from) && Array.isArray(to)) {\n if (JSON.stringify(from) !== JSON.stringify(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n const fromObj = from as Record<string, unknown>;\n const toObj = to as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(fromObj), ...Object.keys(toObj)]);\n\n for (const key of allKeys) {\n const escaped = key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n const path = `${basePath}/${escaped}`;\n if (!(key in fromObj)) {\n ops.push({ op: \"add\", path, value: toObj[key] });\n } else if (!(key in toObj)) {\n ops.push({ op: \"remove\", path });\n } else {\n ops.push(...diffJsonPatch(fromObj[key], toObj[key], path));\n }\n }\n\n return ops;\n}\n","/**\n * Pluggable persistence for the Coordinator.\n *\n * A Store persists workspace state between process restarts. Coordinators\n * call `store.save(workspaceId, snapshot)` after every mutation that\n * appends to the audit chain, and `store.load()` on startup to restore.\n *\n * Two implementations ship in-tree:\n * - MemoryStore (default, no persistence; existing behaviour)\n * - SqliteStore (real SQLite via better-sqlite3, opt-in)\n *\n * Third-party stores (Postgres, Redis, etc.) implement this interface.\n *\n * Concurrency model\n * -----------------\n *\n * A Coordinator is a **single-writer** component: dispatch is serial, workspace\n * state is held in memory, and each chain link is computed from the head the\n * instance holds. This interface is a persistence mechanism, not a\n * concurrency-control one. `save` is an unconditional write and no\n * implementation rejects a stale record.\n *\n * Running two or more Coordinator instances against one shared store is\n * therefore not supported. A stale instance's write replaces a newer one\n * wholesale: entries written by the other instance are lost, the chain is\n * re-linked from the surviving head, and `audit.verify_chain` still reports\n * `ok`, because the surviving chain is internally consistent. The loss is\n * silent and CHAP's own verification will not reveal it.\n *\n * If you need more than one instance, serialise writes above the Coordinator by\n * partitioning workspaces so no workspace is ever written by two, or by holding\n * an external lock. See SPECIFICATION.md section 10.3.\n *\n * Stores hold per-workspace JSON snapshots, not a decomposed relational\n * model. The Coordinator's snapshot/restore methods produce JSON-safe\n * payloads; this is fast for workspaces in the low-thousands of audit\n * entries and trades query flexibility for simplicity. Production\n * deployments needing rich query semantics should project the audit log\n * into their own analytics store via the `onAudit` listener.\n */\n\nexport interface WorkspaceRecord {\n /** Workspace identifier. */\n id: string;\n /** JSON-serialisable payload produced by `Coordinator.snapshot()`. */\n data: unknown;\n /**\n * Incremented on each save. Recorded for diagnostics and for stores that\n * want it; it is NOT enforced. Nothing here performs a compare-and-swap,\n * so this field does not give you optimistic concurrency. See the\n * concurrency model in this module's header.\n */\n version: number;\n /** Wall-clock timestamp of the last write, ISO-8601. */\n updated_at: string;\n}\n\nexport interface Store {\n /** Load all workspace records into memory. Called once on coordinator start. */\n load(): Promise<WorkspaceRecord[]> | WorkspaceRecord[];\n\n /** Persist one workspace record. Called after every mutation. */\n save(record: WorkspaceRecord): Promise<void> | void;\n\n /** Remove one workspace. Used by `workspace.delete` semantics (not in v0.2). */\n delete(id: string): Promise<void> | void;\n\n /** Release resources. Idempotent. */\n close?(): Promise<void> | void;\n}\n\n/**\n * In-memory store. Default behaviour: no persistence, fast tests.\n * State lives in a Map; closing it discards everything.\n */\nexport class MemoryStore implements Store {\n private records = new Map<string, WorkspaceRecord>();\n\n load(): WorkspaceRecord[] {\n return Array.from(this.records.values());\n }\n\n save(record: WorkspaceRecord): void {\n this.records.set(record.id, record);\n }\n\n delete(id: string): void {\n this.records.delete(id);\n }\n\n close(): void {\n this.records.clear();\n }\n}\n","/**\n * Typed method facade for the Coordinator.\n *\n * Replaces the verbose dispatch pattern:\n *\n * const env = await coord.dispatch({\n * jsonrpc: \"2.0\", id: \"x\",\n * method: \"task.create\",\n * params: { workspace, from, kind, input }\n * });\n * const taskId = env.result.task_id;\n *\n * with namespace-grouped calls that autocomplete and type-check:\n *\n * const { task_id } = coord.api.task.create({ workspace, from, kind, input });\n *\n * Every method on the facade calls `dispatch(envelope)` internally with\n * an auto-generated envelope id, so the audit chain semantics, profile\n * gates, and signature checks all run identically.\n *\n * On dispatch error, the facade throws a `CoordinatorError` carrying the\n * JSON-RPC error code and message. Callers expecting `error` objects on\n * the wire can still use `dispatch()` directly.\n */\n\nimport type { Coordinator } from \"./coordinator.js\";\nimport type { Envelope } from \"./types.js\";\nimport type {\n MethodName, MethodParams, MethodResult,\n} from \"./methods.js\";\n\nexport class CoordinatorError extends Error {\n readonly code: number;\n readonly data?: unknown;\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.name = \"CoordinatorError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/**\n * Single-call helper. Type-safe wrapper around `coord.dispatch()`.\n * Throws CoordinatorError if dispatch returns an error response.\n */\nexport function call<M extends MethodName>(\n coord: Coordinator,\n method: M,\n params: MethodParams<M>,\n): MethodResult<M> {\n const envelope: Envelope = {\n jsonrpc: \"2.0\",\n id: coord.ids.envelopeId(),\n method,\n params: params as unknown as Record<string, unknown>,\n };\n const out = coord.dispatch(envelope);\n if (out.error) {\n throw new CoordinatorError(out.error.code, out.error.message, out.error.data);\n }\n return out.result as MethodResult<M>;\n}\n\n// ============================================================\n// Namespace-grouped facades\n// ============================================================\n//\n// Each namespace facade is a small object exposing one method per\n// CHAP verb. Implementations are one-liners that delegate to call().\n// The pattern is verbose but autocompletes well and type-checks\n// param shape and result shape from one declaration in methods.ts.\n\nexport function makeApi(coord: Coordinator) {\n const c = <M extends MethodName>(m: M, p: MethodParams<M>) => call(coord, m, p);\n\n return {\n workspace: {\n create: (p: MethodParams<\"workspace.create\">) => c(\"workspace.create\", p),\n describe: (p: MethodParams<\"workspace.describe\">) => c(\"workspace.describe\", p),\n set_profiles: (p: MethodParams<\"workspace.set_profiles\">) => c(\"workspace.set_profiles\", p),\n },\n participant: {\n join: (p: MethodParams<\"participant.join\">) => c(\"participant.join\", p),\n leave: (p: MethodParams<\"participant.leave\">) => c(\"participant.leave\", p),\n rotate_key: (p: MethodParams<\"participant.rotate_key\">) => c(\"participant.rotate_key\", p),\n revoke_key: (p: MethodParams<\"participant.revoke_key\">) => c(\"participant.revoke_key\", p),\n },\n task: {\n create: (p: MethodParams<\"task.create\">) => c(\"task.create\", p),\n update: (p: MethodParams<\"task.update\">) => c(\"task.update\", p),\n complete: (p: MethodParams<\"task.complete\">) => c(\"task.complete\", p),\n route: (p: MethodParams<\"task.route\">) => c(\"task.route\", p),\n },\n review: {\n request: (p: MethodParams<\"review.request\">) => c(\"review.request\", p),\n depth: (p: MethodParams<\"review.depth\">) => c(\"review.depth\", p),\n },\n decide: {\n approve: (p: MethodParams<\"decide.approve\">) => c(\"decide.approve\", p),\n reject: (p: MethodParams<\"decide.reject\">) => c(\"decide.reject\", p),\n override: (p: MethodParams<\"decide.override\">) => c(\"decide.override\", p),\n },\n abstain: {\n declare: (p: MethodParams<\"abstain.declare\">) => c(\"abstain.declare\", p),\n },\n escalate: {\n raise: (p: MethodParams<\"escalate.raise\">) => c(\"escalate.raise\", p),\n auto: (p: MethodParams<\"escalate.auto\">) => c(\"escalate.auto\", p),\n },\n whisper: {\n ask: (p: MethodParams<\"whisper.ask\">) => c(\"whisper.ask\", p),\n answer: (p: MethodParams<\"whisper.answer\">) => c(\"whisper.answer\", p),\n },\n deliberate: {\n open: (p: MethodParams<\"deliberate.open\">) => c(\"deliberate.open\", p),\n comment: (p: MethodParams<\"deliberate.comment\">) => c(\"deliberate.comment\", p),\n vote: (p: MethodParams<\"deliberate.vote\">) => c(\"deliberate.vote\", p),\n close: (p: MethodParams<\"deliberate.close\">) => c(\"deliberate.close\", p),\n },\n handoff: {\n propose: (p: MethodParams<\"handoff.propose\">) => c(\"handoff.propose\", p),\n accept: (p: MethodParams<\"handoff.accept\">) => c(\"handoff.accept\", p),\n decline: (p: MethodParams<\"handoff.decline\">) => c(\"handoff.decline\", p),\n },\n control: {\n pause: (p: MethodParams<\"control.pause\">) => c(\"control.pause\", p),\n resume: (p: MethodParams<\"control.resume\">) => c(\"control.resume\", p),\n cancel: (p: MethodParams<\"control.cancel\">) => c(\"control.cancel\", p),\n supersede: (p: MethodParams<\"control.supersede\">) => c(\"control.supersede\", p),\n snapshot: (p: MethodParams<\"control.snapshot\">) => c(\"control.snapshot\", p),\n rollback: (p: MethodParams<\"control.rollback\">) => c(\"control.rollback\", p),\n set_mode_ceiling: (p: MethodParams<\"control.set_mode_ceiling\">) => c(\"control.set_mode_ceiling\", p),\n },\n audit: {\n read: (p: MethodParams<\"audit.read\">) => c(\"audit.read\", p),\n submit_to_scitt: (p: MethodParams<\"audit.submit_to_scitt\">) => c(\"audit.submit_to_scitt\", p),\n verify_receipt: (p: MethodParams<\"audit.verify_receipt\">) => c(\"audit.verify_receipt\", p),\n verify_chain: (p: MethodParams<\"audit.verify_chain\">) => c(\"audit.verify_chain\", p),\n },\n };\n}\n\nexport type CoordinatorApi = ReturnType<typeof makeApi>;\n","/**\n * @brightbeamai/chap-coordinator. type vocabulary\n *\n * Wire-shape and in-memory types for the Coordinator. The schemas at\n * schemas/ are the normative wire types; these mirror them in\n * TypeScript for in-process use.\n */\n\nexport type ParticipantUri = string;\nexport type WorkspaceId = string;\nexport type TaskId = string;\nexport type ArtefactId = string;\n\nexport type ParticipantType = \"human\" | \"agent\" | \"service\" | \"group\" | \"workspace\";\n\nexport interface Envelope {\n jsonrpc: \"2.0\";\n id?: string | number;\n method?: string;\n params?: Record<string, unknown>;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n /** security-signed/1.0: top-level signature, signed over JCS of the\n * envelope with this field removed. Form: ``ed25519:<kid>:<b64>``. */\n sig?: string;\n}\n\nexport type Mode = \"shadow\" | \"trial\" | \"production\";\nexport type WorkspaceState = \"active\" | \"paused\" | \"closed\";\nexport type PauseScope = \"task\" | \"participant\" | \"workspace\";\n\nexport type TaskState =\n | \"created\"\n | \"in_progress\"\n | \"review_requested\"\n | \"completed\"\n | \"declined\"\n | \"abstained\"\n | \"escalated\"\n | \"superseded\"\n | \"paused\"\n | \"cancelled\";\n\n// ============================================================\n// Key records (security-signed/1.0)\n// ============================================================\n\nexport interface Jwk {\n kty: \"OKP\";\n crv: \"Ed25519\";\n kid: string;\n x: string;\n use?: string;\n alg?: string;\n}\n\n/** A participant's JWK plus the validity window. Lookup by\n * (participant, kid, ts) so historical envelopes verify across\n * rotation per security-signed/1.0 S3-S5. */\nexport interface KeyRecord {\n jwk: Jwk;\n kid: string;\n valid_from: string; // ISO timestamp; inclusive\n valid_until?: string; // ISO timestamp; exclusive; absent = unbounded\n revoked_at?: string;\n revoked_reason?: string;\n}\n\n// ============================================================\n// Participants\n// ============================================================\n\nexport interface Member {\n uri: ParticipantUri;\n type: ParticipantType;\n role: string;\n joined: string;\n display_name?: string;\n capabilities?: Record<string, unknown>;\n scopes?: string[];\n keys: KeyRecord[];\n paused: boolean; // control.pause scope=participant\n oidc_sub?: string;\n oidc_auth_time?: number; // unix seconds\n oidc_acr?: string;\n vc_holder?: string;\n}\n\n// ============================================================\n// Routing hints\n// ============================================================\n\nexport interface TaskRoutingHints {\n criticality?: \"low\" | \"medium\" | \"high\" | \"critical\";\n deadline?: string;\n max_cost_usd?: number;\n risk_tier?: string;\n [extra: string]: unknown;\n}\n\nexport interface ArtefactRoutingHints {\n confidence?: number | string;\n model_id?: string;\n cost_consumed_usd?: number;\n latency_ms?: number;\n [extra: string]: unknown;\n}\n\n// ============================================================\n// JSON Patch (RFC 6902)\n// ============================================================\n\nexport interface JsonPatchOp {\n op: \"add\" | \"replace\" | \"remove\" | \"copy\" | \"move\" | \"test\";\n path: string;\n value?: unknown;\n from?: string;\n}\n\n// ============================================================\n// Override artefact (review/1.0)\n// ============================================================\n\nexport interface OverrideArtefact {\n id: ArtefactId;\n task_id: TaskId;\n reviewer: ParticipantUri;\n based_on_artefact: unknown;\n diff: JsonPatchOp[];\n result: unknown;\n rationale: string;\n tags: string[];\n policy_refs: string[];\n ts: string;\n logical_id?: string;\n instance_id?: string;\n intent_preserved?: boolean;\n}\n\n// ============================================================\n// Route decision artefact (routing/1.0)\n// ============================================================\n\nexport interface RouteDecisionArtefact {\n id: ArtefactId;\n kind: \"route_decision\";\n decision_type: \"task.route\" | \"review.depth\" | \"escalate.auto\";\n outcome: unknown;\n produced_by: ParticipantUri;\n produced_at: string;\n task?: TaskId;\n policy_id?: string;\n hints_observed: Record<string, unknown>;\n rationale: string;\n // Auxiliary fields per decision_type:\n // task.route: alternatives_considered\n // review.depth: sampling_probability\n // escalate.auto: escalation_target\n [extra: string]: unknown;\n}\n\n// ============================================================\n// Snapshot artefact (control/1.0)\n// ============================================================\n\nexport interface SnapshotArtefact {\n id: ArtefactId;\n kind: \"snapshot\";\n ts: string;\n by: ParticipantUri;\n workspace: WorkspaceId;\n audit_seq: number;\n label?: string;\n include: string[];\n state: Record<string, unknown>;\n}\n\n// ============================================================\n// Whisper (whisper/1.0)\n// ============================================================\n\nexport interface WhisperPrompt {\n id: ArtefactId;\n task_id: TaskId;\n asker: ParticipantUri;\n askee: ParticipantUri[];\n question: string;\n options?: Array<{ id: string; label?: string }>;\n asked_at: string;\n deadline_ms: number;\n default_if_lapsed: unknown;\n urgency: \"low\" | \"medium\" | \"high\";\n state: \"pending\" | \"answered\" | \"lapsed\";\n answered_at?: string;\n answered_by?: ParticipantUri;\n answer_option?: string;\n answer_text?: string;\n comment?: string;\n default_applied?: unknown;\n}\n\n// ============================================================\n// Deliberation (deliberation/1.0)\n// ============================================================\n\nexport interface DeliberationVote {\n ts: string;\n voter: ParticipantUri;\n vote: \"yea\" | \"nay\" | \"abstain\";\n weight?: number;\n comment?: string;\n veto_invoked?: boolean;\n}\n\nexport interface Deliberation {\n id: string;\n task_id?: TaskId;\n opener: ParticipantUri;\n participants: ParticipantUri[];\n rule: string; // raw rule string\n question?: string;\n weights?: Record<ParticipantUri, number>;\n veto?: Record<ParticipantUri, boolean>;\n deadline?: string;\n state: \"open\" | \"closed\" | \"lapsed\";\n comments: { ts: string; from: ParticipantUri; text: string }[];\n votes: DeliberationVote[];\n outcome?: {\n outcome: \"approved\" | \"rejected\" | \"error\";\n rule: string;\n tally?: { yea: number; nay: number };\n vetoes?: ParticipantUri[];\n reason?: string;\n };\n opened_at: string;\n}\n\n// ============================================================\n// Handoff (handoff/1.0)\n// ============================================================\n\nexport interface HandoffTaskItem {\n task_id: TaskId;\n title?: string;\n status_summary?: string;\n next_action?: string;\n blockers?: string[];\n}\n\nexport interface Handoff {\n id: string;\n proposer: ParticipantUri;\n recipient: ParticipantUri; // single URI or \"group:...\"\n proposed_at: string;\n tasks: HandoffTaskItem[];\n summary?: string;\n context_links: string[];\n state: \"proposed\" | \"accepted\" | \"declined\";\n resolved_at?: string;\n accepted_by?: ParticipantUri;\n accepted_task_ids?: TaskId[];\n accept_comment?: string;\n decline_reason?: string;\n decline_suggested_target?: ParticipantUri;\n}\n\n// ============================================================\n// Review decision (review/1.0)\n// ============================================================\n\nexport interface ReviewDecision {\n reviewer: ParticipantUri;\n kind: \"approve\" | \"reject\" | \"override\" | \"abstain\";\n ts: string;\n comment?: string;\n tags?: string[];\n override_artefact_id?: ArtefactId;\n abstain_category?: string;\n}\n\n// ============================================================\n// Task\n// ============================================================\n\nexport interface Task {\n id: TaskId;\n kind: string;\n state: TaskState;\n assignee: ParticipantUri;\n delegator: ParticipantUri;\n input: Record<string, unknown>;\n output?: unknown;\n confidence?: number | string;\n deadline?: string;\n created_at: string;\n updated_at: string;\n mode: Mode;\n review_required?: boolean;\n routing_hints?: TaskRoutingHints;\n artefact_routing_hints?: ArtefactRoutingHints;\n review?: {\n requested_at: string;\n requested_to: ParticipantUri[];\n rule: string;\n deadline?: string;\n decisions: ReviewDecision[];\n };\n history: { ts: string; from: ParticipantUri; state: TaskState; note?: string }[];\n supersedes?: TaskId;\n superseded_by?: TaskId;\n parent?: TaskId;\n paused: boolean;\n /** Transient: holds the artefact passed to review.request so\n * decide.override can use it as the patch base. */\n pending_artefact?: unknown;\n}\n\n// ============================================================\n// Audit\n// ============================================================\n\nexport interface AuditEntry {\n seq: number;\n arrived: string;\n envelope: Envelope;\n prev_hash?: string;\n}\n\n// ============================================================\n// Workspace\n// ============================================================\n\nexport interface Workspace {\n id: WorkspaceId;\n created: string;\n state: WorkspaceState;\n profiles: string[];\n mode: Mode;\n mode_ceiling: Mode;\n routing_policy_uri?: string;\n step_up_window_sec: number;\n min_acr?: string;\n members: Map<ParticipantUri, Member>;\n tasks: Map<TaskId, Task>;\n overrides: Map<ArtefactId, OverrideArtefact>;\n whispers: Map<string, WhisperPrompt>;\n deliberations: Map<string, Deliberation>;\n handoffs: Map<string, Handoff>;\n snapshots: Map<ArtefactId, SnapshotArtefact>;\n route_decisions: Map<ArtefactId, RouteDecisionArtefact>;\n // task.create idempotency: caller-supplied key -> task_id.\n idempotency_keys: Record<string, TaskId>;\n audit: AuditEntry[];\n chain_head?: string;\n chain_enabled: boolean;\n}\n\n/**\n * Listener callback invoked synchronously when an envelope is appended\n * to the workspace audit log.\n */\nexport type AuditListener = (workspace: Workspace, entry: AuditEntry) => void;\n\n/** True iff mode `a` is <= ceiling. */\nexport function modeLE(a: Mode, ceiling: Mode): boolean {\n const order: Record<Mode, number> = { shadow: 0, trial: 1, production: 2 };\n return order[a] <= order[ceiling];\n}\n","/**\n * audit-scitt/1.0 profile (profiles/audit-scitt.md).\n *\n * Methods:\n * - audit.submit_to_scitt -> build COSE_Sign1-shaped statements, pass to submitter\n * - audit.verify_receipt -> delegate to deployment hook\n * - audit.verify_chain -> replay local prev_hash chain\n *\n * External SCITT integration is the deployment's job; the Coordinator\n * builds the statement shape and routes through CoordinatorOptions.scittSubmitter.\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { canonicalize, sha256Hex, ZERO_HASH } from \"../canonical.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { Envelope } from \"../types.js\";\n\nfunction buildStatement(workspaceId: string, envelope: Envelope, issuer: string): Record<string, unknown> {\n return {\n protected: {\n alg: -8, // Ed25519 per COSE\n iss: issuer,\n kid: \"scitt-issuer\",\n cwt_claims: { sub: workspaceId, iat: null },\n \"content-type\": \"application/chap+json;version=0.2\",\n },\n payload: canonicalize(envelope).toString(\"utf-8\"),\n signature: \"<deployment-supplied>\",\n };\n}\n\nexport function registerAuditScitt(coord: Coordinator): void {\n coord.handlers.set(\"audit.submit_to_scitt\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const range = (p.range as { from_seq?: number; to_seq?: number } | undefined) ?? {};\n const fromSeq = range.from_seq ?? 0;\n const toSeq = range.to_seq ?? ws.audit.length;\n const issuer = (p.issuer as string) ?? \"service:coordinator\";\n\n if (!coord.options.scittSubmitter) {\n const statements = ws.audit.slice(fromSeq, toSeq).map(e =>\n buildStatement(ws.id, e.envelope, issuer));\n return { result: {\n statements,\n note: \"No scittSubmitter configured; submit these out-of-band\",\n }};\n }\n const receipts: unknown[] = [];\n for (const entry of ws.audit.slice(fromSeq, toSeq)) {\n const statement = buildStatement(ws.id, entry.envelope, issuer);\n let receipt: Record<string, unknown> | null;\n try {\n receipt = coord.options.scittSubmitter(statement);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.SCITT_UNREACHABLE, `SCITT submission error: ${msg}`) };\n }\n if (receipt === null) {\n return { error: rpcError(E.SCITT_STATEMENT_REJECTED,\n `Statement rejected at seq ${entry.seq}`) };\n }\n receipts.push({ seq: entry.seq, receipt });\n }\n return { result: { receipts } };\n });\n\n coord.handlers.set(\"audit.verify_receipt\", (p) => {\n const receipt = p.receipt;\n if (typeof receipt !== \"object\" || receipt === null) {\n return { error: rpcError(E.PARAMS, \"receipt must be an object\") };\n }\n if (coord.options.verifyScittReceipt) {\n let ok: boolean;\n try { ok = !!coord.options.verifyScittReceipt(receipt as Record<string, unknown>); }\n catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.SCITT_RECEIPT_INVALID, `verify error: ${msg}`) };\n }\n if (!ok) return { error: rpcError(E.SCITT_RECEIPT_INVALID, \"Receipt did not verify\") };\n return { result: { verified: true } };\n }\n return { error: rpcError(E.SCITT_RECEIPT_INVALID, \"No verifyScittReceipt hook configured; receipt not verified\") };\n });\n\n coord.handlers.set(\"audit.verify_chain\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n if (!(ws.chain_enabled || coord.options.enableChain)) {\n return { error: rpcError(E.PARAMS, \"Chain not enabled for this workspace\") };\n }\n // Range verification is not implemented. Accepting the parameters and\n // replaying the whole log anyway would answer a wider question than the\n // caller asked while reporting counts scoped to the whole log, which is\n // the failure this method was just fixed to stop making.\n if (p.from_seq !== undefined || p.to_seq !== undefined) {\n return { error: rpcError(\n E.PARAMS,\n \"Range verification is not implemented; omit from_seq and to_seq to \" +\n \"verify the whole log.\",\n ) };\n }\n // Coverage begins at the first entry carrying a prev_hash. A workspace\n // may enable chaining part-way through its life, in which case every\n // earlier entry is outside the chain and cannot be evaluated against\n // anything. Those entries are not evidence of tampering and not\n // evidence of integrity: they were never checked, and the verdict\n // below has to say so rather than pass over them.\n let start = ws.audit.findIndex(e => e.prev_hash != null);\n if (start < 0) start = ws.audit.length;\n const errors: string[] = [];\n let prev = ZERO_HASH;\n for (const e of ws.audit.slice(start)) {\n const expectedPrev = prev;\n // A chain-enabled workspace must have prev_hash on every entry; a\n // missing value is a defect, not a reason to skip the check.\n if (e.prev_hash !== expectedPrev) {\n errors.push(`seq ${e.seq}: prev_hash mismatch`);\n }\n prev = sha256Hex(Buffer.concat([canonicalize(e.envelope), Buffer.from(expectedPrev, \"utf-8\")]));\n }\n // The recomputed head must match the stored head; this is what makes\n // the final entry tamper-evident.\n // Explicit null/undefined check, matching Python. A falsy-but-present\n // head must not be silently replaced with ZERO_HASH, or the two\n // implementations return different verdicts for the same state.\n const storedHead = (ws.chain_head === undefined || ws.chain_head === null)\n ? ZERO_HASH : ws.chain_head;\n if (prev !== storedHead) {\n errors.push(\"chain_head mismatch: replay does not match stored head\");\n }\n if (errors.length) {\n return { error: rpcError(E.PARAMS, errors.join(\"; \")) };\n }\n const entriesTotal = ws.audit.length;\n const entriesChecked = entriesTotal - start;\n const entriesUnchecked = start;\n // Three terminal verdicts, mutually exclusive: a broken chain returned\n // above as an error, an unevaluated range here, and a pass only when\n // coverage is complete. `not_evaluated` never rides alongside ok:true;\n // a reader that looks at ok alone fails closed rather than reading a\n // pass over entries nothing was checked against.\n if (entriesUnchecked > 0) {\n return { result: {\n status: \"not_evaluated\",\n ok: false,\n reason: \"unchained_prefix\",\n entries_total: entriesTotal,\n entries_checked: entriesChecked,\n entries_unchecked: entriesUnchecked,\n checked_from_seq: entriesChecked > 0 ? ws.audit[start].seq : null,\n chain_head: storedHead,\n }};\n }\n return { result: {\n status: \"verified\",\n ok: true,\n entries_total: entriesTotal,\n entries_checked: entriesChecked,\n entries_unchecked: 0,\n checked_from_seq: entriesChecked > 0 ? ws.audit[start].seq : null,\n chain_head: storedHead,\n }};\n });\n}\n","/**\n * control/1.0 profile (profiles/control.md).\n *\n * Methods:\n * - control.pause / control.resume (scope: task|participant|workspace)\n * - control.cancel\n * - control.snapshot (returns art_... id)\n * - control.rollback (to_snapshot_artefact_id + what_to_restore)\n * - control.supersede (creates successor in one shot)\n * - control.set_mode_ceiling\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { Mode, SnapshotArtefact, Task } from \"../types.js\";\n\nconst VALID_MODES = new Set<Mode>([\"shadow\", \"trial\", \"production\"]);\nconst VALID_SCOPES = new Set([\"task\", \"participant\", \"workspace\"]);\n\nexport function registerControl(coord: Coordinator): void {\n coord.handlers.set(\"control.pause\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const scope = (p.scope as string) || \"task\";\n if (!VALID_SCOPES.has(scope)) {\n return { error: rpcError(E.PARAMS, `scope must be task/participant/workspace`) };\n }\n if (scope === \"task\") {\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state === \"completed\" || task.state === \"declined\" || task.state === \"cancelled\") {\n return { error: rpcError(E.CONTROL_NOT_AUTHORISED, `Cannot pause ${task.state} task`) };\n }\n task.paused = true;\n const prior = task.state;\n task.state = \"paused\";\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: \"paused\", note: `was ${prior}` });\n return { result: { scope: \"task\", task_id: task.id, state: \"paused\" } };\n }\n if (scope === \"participant\") {\n const uri = (p.participant_uri as string) || (p.uri as string);\n if (!uri || !ws.members.has(uri)) return { error: rpcError(E.PARAMS, `Unknown participant: ${uri}`) };\n ws.members.get(uri)!.paused = true;\n return { result: {\n scope: \"participant\", participant_uri: uri, paused: true,\n in_flight_policy: (p.in_flight_policy as string) || \"allow_to_complete\",\n }};\n }\n // workspace\n ws.state = \"paused\";\n return { result: { scope: \"workspace\", workspace: ws.id, state: \"paused\" } };\n });\n\n coord.handlers.set(\"control.resume\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const scope = (p.scope as string) || \"task\";\n if (!VALID_SCOPES.has(scope)) {\n return { error: rpcError(E.PARAMS, `scope must be task/participant/workspace`) };\n }\n if (scope === \"task\") {\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"paused\") {\n return { error: rpcError(E.CONTROL_NOT_AUTHORISED, `Cannot resume ${task.state} task`) };\n }\n task.paused = false;\n task.state = \"in_progress\";\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: \"in_progress\" });\n return { result: { scope: \"task\", task_id: task.id, state: \"in_progress\" } };\n }\n if (scope === \"participant\") {\n const uri = (p.participant_uri as string) || (p.uri as string);\n if (!uri || !ws.members.has(uri)) return { error: rpcError(E.PARAMS, `Unknown participant: ${uri}`) };\n ws.members.get(uri)!.paused = false;\n return { result: { scope: \"participant\", participant_uri: uri, paused: false } };\n }\n ws.state = \"active\";\n return { result: { scope: \"workspace\", workspace: ws.id, state: \"active\" } };\n });\n\n coord.handlers.set(\"control.cancel\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state === \"completed\" || task.state === \"declined\" || task.state === \"cancelled\") {\n return { error: rpcError(E.CONTROL_NOT_AUTHORISED, `Cannot cancel ${task.state} task`) };\n }\n task.state = \"cancelled\";\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: \"cancelled\", note: p.reason as string | undefined });\n return { result: { state: \"cancelled\" } };\n });\n\n coord.handlers.set(\"control.snapshot\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const include: string[] = (p.include as string[]) ?? [\"members\", \"open_tasks\", \"mode_ceiling\"];\n const state: Record<string, unknown> = {};\n if (include.includes(\"members\")) {\n state.members = Array.from(ws.members.values()).map(m => ({\n uri: m.uri, type: m.type, role: m.role, scopes: m.scopes,\n }));\n }\n if (include.includes(\"open_tasks\")) {\n state.open_tasks = Array.from(ws.tasks.values())\n .filter(t => t.state !== \"completed\" && t.state !== \"declined\" && t.state !== \"cancelled\")\n .map(t => ({ id: t.id, kind: t.kind, state: t.state, assignee: t.assignee }));\n }\n if (include.includes(\"mode_ceiling\")) state.mode_ceiling = ws.mode_ceiling;\n if (include.includes(\"policy\")) state.routing_policy_uri = ws.routing_policy_uri;\n if (include.includes(\"audit\") || include.includes(\"all\")) state.audit_seq = ws.audit.length;\n\n const snapId = coord.ids.artefactId();\n const snap: SnapshotArtefact = {\n id: snapId,\n kind: \"snapshot\",\n ts: coord.now(),\n by: p.from as string,\n workspace: ws.id,\n audit_seq: ws.audit.length,\n label: p.label as string | undefined,\n include,\n state,\n };\n ws.snapshots.set(snapId, snap);\n return { result: { snapshot_artefact_id: snapId, audit_seq: snap.audit_seq, artefact: snap } };\n });\n\n coord.handlers.set(\"control.rollback\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const snapId = (p.to_snapshot_artefact_id as string)\n || (p.snapshot_artefact_id as string)\n || (p.snapshot_id as string);\n if (!snapId) return { error: rpcError(E.PARAMS, \"to_snapshot_artefact_id is required\") };\n const snap = ws.snapshots.get(snapId);\n if (!snap) return { error: rpcError(E.CONTROL_SNAPSHOT_NOT_FOUND, `Unknown snapshot: ${snapId}`) };\n const what: string[] = (p.what_to_restore as string[]) ?? snap.include;\n const restored: string[] = [];\n if (what.includes(\"mode_ceiling\") && snap.state.mode_ceiling) {\n ws.mode_ceiling = snap.state.mode_ceiling as Mode;\n restored.push(\"mode_ceiling\");\n }\n if (what.includes(\"members\") && Array.isArray(snap.state.members)) {\n const snapByUri = new Map<string, Record<string, unknown>>();\n for (const m of snap.state.members as Array<Record<string, unknown>>) {\n snapByUri.set(m.uri as string, m);\n }\n for (const [uri, snapM] of snapByUri) {\n if (ws.members.has(uri)) {\n const cur = ws.members.get(uri)!;\n cur.role = (snapM.role as string) ?? cur.role;\n cur.scopes = snapM.scopes as string[] | undefined;\n }\n }\n restored.push(\"members\");\n }\n return { result: {\n rolled_back_to: snapId, audit_seq: snap.audit_seq, restored,\n reason: p.reason as string | undefined,\n }};\n });\n\n coord.handlers.set(\"control.supersede\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const oldId = p.task_id as string;\n const old = ws.tasks.get(oldId);\n if (!old) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const newSpec = (p.successor_task as Record<string, unknown>) ?? {};\n if (!newSpec.kind) {\n return { error: rpcError(E.PARAMS, \"successor_task must include kind\") };\n }\n const assignee = (newSpec.assignee as string) || old.assignee;\n if (!ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"successor assignee not in workspace\") };\n }\n const now = coord.now();\n const newId = coord.ids.taskId();\n const newTask: Task = {\n id: newId,\n kind: newSpec.kind as string,\n state: \"created\",\n assignee,\n delegator: p.from as string,\n input: (newSpec.input as Record<string, unknown>) ?? {},\n created_at: now,\n updated_at: now,\n mode: (newSpec.mode as Mode) ?? old.mode,\n supersedes: old.id,\n history: [{ ts: now, from: p.from as string, state: \"created\",\n note: `supersedes ${old.id}: ${(p.reason as string) || \"\"}` }],\n paused: false,\n };\n ws.tasks.set(newId, newTask);\n old.state = \"superseded\";\n old.superseded_by = newId;\n old.updated_at = now;\n old.history.push({ ts: now, from: p.from as string, state: \"superseded\",\n note: `-> ${newId}: ${(p.reason as string) || \"\"}` });\n return { result: { superseded_task_id: old.id, new_task_id: newId, reason: p.reason as string | undefined } };\n });\n\n coord.handlers.set(\"control.set_mode_ceiling\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const m = (p.new_ceiling as Mode) ?? (p.mode_ceiling as Mode);\n if (!VALID_MODES.has(m)) {\n return { error: rpcError(E.PARAMS, `new_ceiling must be shadow/trial/production`) };\n }\n ws.mode_ceiling = m;\n return { result: { mode_ceiling: ws.mode_ceiling, reason: p.reason as string | undefined } };\n });\n}\n","/**\n * deliberation/1.0 profile (profiles/deliberation.md).\n *\n * Methods:\n * - deliberate.open\n * - deliberate.comment\n * - deliberate.vote\n * - deliberate.close\n *\n * Rules: any_one_approves | all_approve | quorum:N |\n * weighted_vote:T | weighted_vote_with_veto:T\n *\n * Error codes (spec S5):\n * -32030 voter not in participant list\n * -32031 already voted\n * -32032 closed or lapsed\n * -32033 unknown rule\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { Deliberation } from \"../types.js\";\n\nfunction parseRule(rule: string): { kind: string; params: Record<string, number> } {\n if (rule.includes(\":\")) {\n const [kind, arg] = rule.split(\":\", 2);\n if (kind === \"quorum\") return { kind, params: { n: parseInt(arg, 10) } };\n if (kind === \"weighted_vote\" || kind === \"weighted_vote_with_veto\") {\n return { kind, params: { threshold: parseFloat(arg) } };\n }\n }\n if (rule === \"any_one_approves\" || rule === \"all_approve\") return { kind: rule, params: {} };\n throw new Error(`Unknown rule: ${rule}`);\n}\n\nfunction computeOutcome(delib: Deliberation): Deliberation[\"outcome\"] {\n const parsed = parseRule(delib.rule);\n const yea = delib.votes.filter(v => v.vote === \"yea\");\n const nay = delib.votes.filter(v => v.vote === \"nay\");\n const vetoes = delib.votes.filter(v => v.veto_invoked && (delib.veto ?? {})[v.voter]);\n const weights = delib.weights ?? {};\n\n const weighted = (vs: typeof yea) =>\n vs.reduce((s, v) => s + (weights[v.voter] ?? 1.0), 0);\n\n if (parsed.kind === \"any_one_approves\") {\n return {\n outcome: yea.length >= 1 ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length },\n vetoes: vetoes.map(v => v.voter),\n };\n }\n if (parsed.kind === \"all_approve\") {\n const passed = yea.length === delib.participants.length && nay.length === 0;\n return {\n outcome: passed ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length },\n vetoes: vetoes.map(v => v.voter),\n };\n }\n if (parsed.kind === \"quorum\") {\n const n = parsed.params.n;\n const cast = yea.length + nay.length;\n if (cast < n) {\n return {\n outcome: \"rejected\", reason: \"quorum not met\", rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length }, vetoes: [],\n };\n }\n return {\n outcome: yea.length > nay.length ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length },\n vetoes: [],\n };\n }\n if (parsed.kind === \"weighted_vote\") {\n const yeaW = weighted(yea), nayW = weighted(nay);\n return {\n outcome: yeaW >= parsed.params.threshold ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yeaW, nay: nayW }, vetoes: [],\n };\n }\n if (parsed.kind === \"weighted_vote_with_veto\") {\n if (vetoes.length) {\n return {\n outcome: \"rejected\", rule: delib.rule,\n tally: { yea: 0, nay: 0 },\n vetoes: vetoes.map(v => v.voter),\n };\n }\n const yeaW = weighted(yea), nayW = weighted(nay);\n return {\n outcome: yeaW >= parsed.params.threshold ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yeaW, nay: nayW }, vetoes: [],\n };\n }\n return { outcome: \"error\", rule: delib.rule, reason: `unsupported rule ${parsed.kind}` };\n}\n\nexport function registerDeliberation(coord: Coordinator): void {\n coord.handlers.set(\"deliberate.open\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"rule\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const to = p.to ?? p.participants;\n const participants: string[] = Array.isArray(to) ? (to as string[]) : typeof to === \"string\" ? [to] : [];\n if (!participants.length) {\n return { error: rpcError(E.PARAMS, \"deliberate.open needs 'to' (participants list)\") };\n }\n try { parseRule(p.rule as string); }\n catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.DELIB_UNKNOWN_RULE, msg) };\n }\n const id = (p.deliberation_id as string) || coord.ids.deliberationId();\n const delib: Deliberation = {\n id,\n task_id: p.task_id as string | undefined,\n opener: p.from as string,\n participants,\n rule: p.rule as string,\n question: p.question as string | undefined,\n weights: p.weights as Deliberation[\"weights\"],\n veto: p.veto as Deliberation[\"veto\"],\n deadline: p.deadline as string | undefined,\n state: \"open\",\n comments: [],\n votes: [],\n opened_at: coord.now(),\n };\n ws.deliberations.set(id, delib);\n return { result: { deliberation_id: id, state: \"open\" } };\n });\n\n coord.handlers.set(\"deliberate.comment\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const delib = ws.deliberations.get(p.deliberation_id as string);\n if (!delib) return { error: rpcError(E.PARAMS, \"Unknown deliberation\") };\n if (delib.state !== \"open\") {\n return { error: rpcError(E.DELIB_CLOSED_OR_LAPSED, \"Deliberation not open\") };\n }\n delib.comments.push({\n ts: coord.now(),\n from: p.from as string,\n text: (p.comment as string) || (p.text as string) || \"\",\n });\n return { result: { accepted: true } };\n });\n\n coord.handlers.set(\"deliberate.vote\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const delib = ws.deliberations.get(p.deliberation_id as string);\n if (!delib) return { error: rpcError(E.PARAMS, \"Unknown deliberation\") };\n if (delib.state !== \"open\") {\n return { error: rpcError(E.DELIB_CLOSED_OR_LAPSED, \"Deliberation not open\") };\n }\n for (const f of [\"from\", \"vote\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const v = p.vote as string;\n if (v !== \"yea\" && v !== \"nay\" && v !== \"abstain\") {\n return { error: rpcError(E.PARAMS, \"vote must be yea/nay/abstain\") };\n }\n const voter = p.from as string;\n if (!delib.participants.includes(voter)) {\n return { error: rpcError(E.DELIB_VOTER_NOT_IN_LIST,\n `Voter ${voter} not in participant list`) };\n }\n if (delib.votes.some(x => x.voter === voter)) {\n return { error: rpcError(E.DELIB_ALREADY_VOTED, `Voter ${voter} has already voted`) };\n }\n delib.votes.push({\n ts: coord.now(),\n voter,\n vote: v as \"yea\" | \"nay\" | \"abstain\",\n weight: p.weight as number | undefined,\n comment: p.comment as string | undefined,\n veto_invoked: !!p.veto_invoked,\n });\n return { result: { recorded: true } };\n });\n\n coord.handlers.set(\"deliberate.close\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const delib = ws.deliberations.get(p.deliberation_id as string);\n if (!delib) return { error: rpcError(E.PARAMS, \"Unknown deliberation\") };\n if (delib.state === \"closed\") return { result: delib.outcome! };\n delib.state = \"closed\";\n delib.outcome = computeOutcome(delib);\n return { result: delib.outcome };\n });\n}\n","/**\n * handoff/1.0 profile (profiles/handoff.md).\n *\n * Carries multiple tasks. Recipient is a single URI or a group:... URI.\n *\n * Error codes (spec S6):\n * -32050 tasks not assigned to proposer\n * -32051 already resolved\n * -32052 recipient not a workspace member\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { Handoff, HandoffTaskItem } from \"../types.js\";\n\nexport function registerHandoff(coord: Coordinator): void {\n coord.handlers.set(\"handoff.propose\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"to\", \"tasks\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const proposer = p.from as string;\n const recipient = p.to as string;\n if (typeof recipient === \"string\" && !recipient.startsWith(\"group:\")) {\n if (!ws.members.has(recipient)) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n `Recipient ${recipient} is not a member`) };\n }\n }\n const tasksIn = p.tasks;\n if (!Array.isArray(tasksIn) || !tasksIn.length) {\n return { error: rpcError(E.PARAMS, \"tasks must be a non-empty list\") };\n }\n const proposed: HandoffTaskItem[] = [];\n for (const t of tasksIn as Array<Record<string, unknown>>) {\n const tid = t.task_id as string;\n if (!tid || !ws.tasks.has(tid)) {\n return { error: rpcError(E.PARAMS, `Unknown task in handoff: ${tid}`) };\n }\n const task = ws.tasks.get(tid)!;\n if (task.assignee !== proposer) {\n return { error: rpcError(E.HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER,\n `Task ${tid} is not currently assigned to ${proposer}`) };\n }\n proposed.push({\n task_id: tid,\n title: t.title as string | undefined,\n status_summary: t.status_summary as string | undefined,\n next_action: t.next_action as string | undefined,\n blockers: (t.blockers as string[] | undefined) ?? [],\n });\n }\n const id = (p.handoff_id as string) || coord.ids.handoffId();\n const ho: Handoff = {\n id,\n proposer,\n recipient,\n proposed_at: coord.now(),\n tasks: proposed,\n summary: p.summary as string | undefined,\n context_links: (p.context_links as string[] | undefined) ?? [],\n state: \"proposed\",\n };\n ws.handoffs.set(id, ho);\n return { result: { handoff_id: id, state: \"proposed\", task_ids: proposed.map(t => t.task_id) } };\n });\n\n coord.handlers.set(\"handoff.accept\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"handoff_id\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const ho = ws.handoffs.get(p.handoff_id as string);\n if (!ho) return { error: rpcError(E.PARAMS, \"Unknown handoff\") };\n if (ho.state !== \"proposed\") {\n return { error: rpcError(E.HANDOFF_ALREADY_RESOLVED, `Handoff already ${ho.state}`) };\n }\n const acceptor = p.from as string;\n if (ho.recipient.startsWith(\"group:\")) {\n if (!ws.members.has(acceptor)) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n \"Acceptor is not a workspace member\") };\n }\n } else {\n if (acceptor !== ho.recipient) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n \"Acceptor is not the named recipient\") };\n }\n if (!ws.members.has(acceptor)) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n \"Acceptor is not a workspace member\") };\n }\n }\n const validIds = new Set(ho.tasks.map(t => t.task_id));\n const acceptedIds: string[] = Array.isArray(p.accepted_task_ids)\n ? (p.accepted_task_ids as string[])\n : ho.tasks.map(t => t.task_id);\n for (const tid of acceptedIds) {\n if (!validIds.has(tid)) {\n return { error: rpcError(E.PARAMS, `Task ${tid} not in this handoff`) };\n }\n }\n const now = coord.now();\n for (const tid of acceptedIds) {\n const task = ws.tasks.get(tid)!;\n task.assignee = acceptor;\n task.updated_at = now;\n task.history.push({\n ts: now, from: acceptor, state: task.state,\n note: `handoff accepted from ${ho.proposer}`,\n });\n }\n ho.state = \"accepted\";\n ho.accepted_by = acceptor;\n ho.accepted_task_ids = [...acceptedIds];\n ho.accept_comment = p.comment as string | undefined;\n ho.resolved_at = now;\n return { result: { accepted: true, task_ids: [...acceptedIds], assignee: acceptor } };\n });\n\n coord.handlers.set(\"handoff.decline\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"handoff_id\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const ho = ws.handoffs.get(p.handoff_id as string);\n if (!ho) return { error: rpcError(E.PARAMS, \"Unknown handoff\") };\n if (ho.state !== \"proposed\") {\n return { error: rpcError(E.HANDOFF_ALREADY_RESOLVED, `Handoff already ${ho.state}`) };\n }\n const decliner = p.from as string;\n ho.decline_reason = p.reason as string | undefined;\n ho.decline_suggested_target = p.suggested_target as string | undefined;\n if (!ho.recipient.startsWith(\"group:\") && decliner === ho.recipient) {\n ho.state = \"declined\";\n ho.resolved_at = coord.now();\n }\n return { result: { recorded: true, state: ho.state } };\n });\n}\n","/**\n * routing/1.0 profile (profiles/routing.md).\n *\n * Three methods, each emits a route_decision artefact:\n * - task.route -> pick assignee + update task.assignee\n * - review.depth -> skip / spot_check / full + sampling_probability\n * - escalate.auto -> evaluate auto-escalation\n *\n * Error codes:\n * -32510 no eligible assignee\n * -32513 candidates_empty\n * -32514 depth_not_applicable\n * -32515 policy_unreachable\n * -32516 escalation target unavailable\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { RouteDecisionArtefact, Task } from \"../types.js\";\n\nconst CRIT: Record<string, number> = { low: 0, medium: 1, high: 2, critical: 3 };\n\nfunction defaultDepth(hints: Record<string, unknown>): {\n depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n sampling?: number;\n summary: string;\n} {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n if (r >= 3) return { depth: \"full\", summary: \"criticality=critical: full review\" };\n if (r === 2 && conf < 0.7) return { depth: \"full\", summary: \"criticality=high and confidence<0.7: full review\" };\n if (r === 0 && conf >= 0.95) return { depth: \"skip\", summary: \"very low criticality + very high confidence: skip\" };\n if (r <= 1 && conf >= 0.85) return { depth: \"spot_check\", sampling: 0.10, summary: \"low criticality + high confidence: 10% sample\" };\n return { depth: \"spot_check\", sampling: 0.25, summary: \"default mid-confidence: 25% sample\" };\n}\n\nexport function registerRouting(coord: Coordinator): void {\n coord.handlers.set(\"task.route\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const candidates = (p.candidates as string[]) ?? [];\n if (!candidates.length) {\n return { error: rpcError(E.ROUTING_CANDIDATES_EMPTY, \"candidates array was empty\") };\n }\n let selected: string;\n let rationale: Record<string, unknown>;\n if (coord.options.routingPolicy) {\n try {\n const d = coord.options.routingPolicy(task, [...candidates]);\n selected = d.selected;\n rationale = d.rationale;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.ROUTING_POLICY_UNREACHABLE, `routing policy error: ${msg}`) };\n }\n } else {\n const eligible = candidates.filter(c => ws.members.has(c));\n if (!eligible.length) {\n return { error: rpcError(E.ROUTING_NO_ELIGIBLE_ASSIGNEE, \"No candidate is a workspace member\") };\n }\n selected = eligible[0];\n rationale = {\n policy_id: \"default\",\n hints_used: Object.keys(task.routing_hints ?? {}),\n summary: \"default policy: first eligible candidate\",\n alternatives_considered: eligible.slice(1).map(c => ({\n candidate: c, reason_excluded: \"not first eligible\",\n })),\n };\n }\n if (!ws.members.has(selected)) {\n return { error: rpcError(E.ROUTING_NO_ELIGIBLE_ASSIGNEE,\n `Selected ${JSON.stringify(selected)} is not a member`) };\n }\n task.assignee = selected;\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: \"service:coordinator\",\n state: task.state, note: `routed to ${selected}` });\n const artId = coord.ids.artefactId();\n const artefact: RouteDecisionArtefact = {\n id: artId, kind: \"route_decision\",\n decision_type: \"task.route\", outcome: selected,\n produced_by: \"service:coordinator\", produced_at: task.updated_at,\n task: task.id,\n policy_id: rationale.policy_id as string | undefined,\n hints_observed: { ...(task.routing_hints ?? {}) },\n rationale: (rationale.summary as string) ?? \"\",\n alternatives_considered: rationale.alternatives_considered,\n };\n ws.route_decisions.set(artId, artefact);\n return { result: { selected, decision_artefact: artId, rationale } };\n });\n\n coord.handlers.set(\"review.depth\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const hints: Record<string, unknown> = { ...(task.routing_hints ?? {}),\n ...((p.artefact_routing_hints as Record<string, unknown>) ?? {}) };\n if (!Object.keys(hints).length) {\n return { error: rpcError(E.ROUTING_DEPTH_NOT_APPLICABLE, \"No routing_hints to consult\") };\n }\n let depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n let sampling: number | undefined;\n let summary: string;\n let policyId: string;\n if (coord.options.reviewDepthPolicy) {\n try {\n const d = coord.options.reviewDepthPolicy(task, hints);\n depth = d.depth;\n sampling = d.sampling_probability;\n summary = (d.rationale.summary as string) ?? \"operator policy\";\n policyId = (d.rationale.policy_id as string) ?? \"operator\";\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.ROUTING_POLICY_UNREACHABLE, `depth policy error: ${msg}`) };\n }\n } else {\n const d = defaultDepth(hints);\n depth = d.depth; sampling = d.sampling; summary = d.summary;\n policyId = \"default\";\n }\n const artId = coord.ids.artefactId();\n const artefact: RouteDecisionArtefact = {\n id: artId, kind: \"route_decision\",\n decision_type: \"review.depth\", outcome: depth,\n produced_by: \"service:coordinator\", produced_at: coord.now(),\n task: task.id, policy_id: policyId,\n hints_observed: hints, rationale: summary,\n ...(sampling !== undefined ? { sampling_probability: sampling } : {}),\n };\n ws.route_decisions.set(artId, artefact);\n const result: Record<string, unknown> = {\n depth, decision_artefact: artId,\n rationale: { policy_id: policyId, hints_used: Object.keys(hints), summary },\n };\n if (sampling !== undefined) result.sampling_probability = sampling;\n return { result };\n });\n\n coord.handlers.set(\"escalate.auto\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const hints = { ...(task.routing_hints ?? {}) };\n let escalate: boolean, to: string | undefined, rule: Record<string, unknown>;\n if (coord.options.escalationPolicy) {\n try {\n const d = coord.options.escalationPolicy(task, hints);\n escalate = !!d.escalate;\n to = d.to;\n rule = d.triggered_rule ?? {};\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.ROUTING_POLICY_UNREACHABLE, `escalation policy error: ${msg}`) };\n }\n } else {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n escalate = r >= 3 || (r >= 2 && conf < 0.6);\n to = p.default_escalation_target as string | undefined;\n rule = {\n rule_id: \"default-auto-esc\",\n summary: \"criticality=critical OR (criticality>=high AND confidence<0.6)\",\n hints_used: [\"criticality\", \"confidence\"],\n };\n }\n const artId = coord.ids.artefactId();\n const artefact: RouteDecisionArtefact = {\n id: artId, kind: \"route_decision\",\n decision_type: \"escalate.auto\",\n outcome: escalate ? { escalate: true, to } : { escalate: false },\n produced_by: \"service:coordinator\", produced_at: coord.now(),\n task: task.id,\n policy_id: rule.rule_id as string | undefined,\n hints_observed: hints,\n rationale: (rule.summary as string) ?? \"\",\n ...(escalate ? { escalation_target: to } : {}),\n };\n ws.route_decisions.set(artId, artefact);\n if (escalate) {\n if (!to) return { error: rpcError(E.ROUTING_ESC_TARGET_UNAVAILABLE,\n \"Escalation triggered but no target available\") };\n if (!to.startsWith(\"group:\") && !ws.members.has(to)) {\n return { error: rpcError(E.ROUTING_ESC_TARGET_UNAVAILABLE,\n `Escalation target ${to} is not a member or group`) };\n }\n if (coord.options.onAutoEscalate) {\n try { coord.options.onAutoEscalate(task, to); } catch { /* */ }\n }\n return { result: { escalate: true, to, decision_artefact: artId, triggered_rule: rule } };\n }\n return { result: { escalate: false, decision_artefact: artId } };\n });\n}\n","/**\n * security-signed/1.0 profile (profiles/security-signed.md).\n *\n * Top-level `sig` field on every envelope: ed25519:<kid>:<base64>.\n * Verification happens at dispatch (see Coordinator.verifySignature).\n *\n * Methods:\n * - participant.rotate_key\n * - participant.revoke_key\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { KeyRecord } from \"../types.js\";\n\nexport function registerSecuritySigned(coord: Coordinator): void {\n coord.handlers.set(\"participant.rotate_key\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"old_kid\", \"new_jwk\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const member = ws.members.get(p.from as string);\n if (!member) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `Unknown participant: ${p.from}`) };\n const oldKid = p.old_kid as string;\n const oldKey = member.keys.find(k => k.kid === oldKid);\n if (!oldKey) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `No key ${oldKid} for ${p.from}`) };\n if (oldKey.revoked_at) return { error: rpcError(E.SIG_KEY_REVOKED, `Key ${oldKid} is revoked`) };\n\n const newJwk = p.new_jwk as Record<string, unknown>;\n if (!newJwk || typeof newJwk.kid !== \"string\") {\n return { error: rpcError(E.PARAMS, \"new_jwk must include kid\") };\n }\n const now = coord.now();\n oldKey.valid_until = now;\n member.keys.push({\n jwk: newJwk as unknown as KeyRecord[\"jwk\"],\n kid: newJwk.kid as string,\n valid_from: now,\n });\n return { result: { rotated: true, old_kid: oldKid, new_kid: newJwk.kid, valid_from: now } };\n });\n\n coord.handlers.set(\"participant.revoke_key\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"target_uri\", \"kid\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const sender = p.from as string | undefined;\n if (sender !== p.target_uri) {\n const caller = sender ? ws.members.get(sender) : undefined;\n if (!caller || caller.role !== \"admin\") {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"Revoking another member's key requires the admin role\") };\n }\n }\n const member = ws.members.get(p.target_uri as string);\n if (!member) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `Unknown target: ${p.target_uri}`) };\n const key = member.keys.find(k => k.kid === p.kid);\n if (!key) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `No key ${p.kid} for target`) };\n const now = coord.now();\n key.revoked_at = now;\n key.revoked_reason = (p.reason as string) || \"unspecified\";\n return { result: { revoked: true, kid: key.kid, revoked_at: now, reason: key.revoked_reason } };\n });\n}\n","/**\n * whisper/1.0 profile (profiles/whisper.md).\n *\n * Methods:\n * - whisper.ask -> pose a deadline-bound question with options + default\n * - whisper.answer -> answer a whisper\n *\n * Lapse handling: coordinator.checkWhisperLapses(workspaceId, now?) is\n * registered on the Coordinator instance for deployments to call from a\n * scheduler.\n *\n * Error codes (per spec S6):\n * -32020 WHISPER_ALREADY_ANSWERED\n * -32021 WHISPER_LAPSED\n * -32022 WHISPER_OPTION_NOT_IN_SET\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { WhisperPrompt, Envelope } from \"../types.js\";\n\nfunction parseIso(ts: string): number { return new Date(ts).getTime(); }\n\nexport function registerWhisper(coord: Coordinator): void {\n coord.handlers.set(\"whisper.ask\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"to\", \"task_id\", \"question\", \"deadline_ms\", \"default_if_lapsed\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n if (!ws.tasks.has(p.task_id as string)) {\n return { error: rpcError(E.PARAMS, \"Unknown task\") };\n }\n const to = p.to;\n const askee: string[] = Array.isArray(to) ? (to as string[]) : [to as string];\n const id = (p.whisper_id as string) || coord.ids.artefactId();\n const prompt: WhisperPrompt = {\n id,\n task_id: p.task_id as string,\n asker: p.from as string,\n askee,\n question: p.question as string,\n options: p.options as WhisperPrompt[\"options\"],\n asked_at: coord.now(),\n deadline_ms: Number(p.deadline_ms),\n default_if_lapsed: p.default_if_lapsed,\n urgency: (p.urgency as WhisperPrompt[\"urgency\"]) || \"low\",\n state: \"pending\",\n };\n ws.whispers.set(id, prompt);\n return { result: { whisper_id: id, deadline_ms: prompt.deadline_ms } };\n });\n\n coord.handlers.set(\"whisper.answer\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"whisper_id\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const prompt = ws.whispers.get(p.whisper_id as string);\n if (!prompt) return { error: rpcError(E.PARAMS, \"Unknown whisper id\") };\n // Only a participant the whisper was addressed to may answer it. A\n // broadcast scope (workspace:/group:) is satisfied by any member; the\n // coordinator does not model group membership (see SPECIFICATION.md).\n const answerer = p.from as string;\n const broadcast = prompt.askee.some((a) => typeof a === \"string\" && (a.startsWith(\"workspace:\") || a.startsWith(\"group:\")));\n if (broadcast) {\n if (!ws.members.has(answerer)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not a workspace member: ${answerer}`) };\n }\n } else if (!prompt.askee.includes(answerer)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Whisper was not addressed to ${answerer}`) };\n }\n if (prompt.state === \"answered\") {\n return { error: rpcError(E.WHISPER_ALREADY_ANSWERED, \"Whisper already answered\") };\n }\n if (prompt.state === \"lapsed\") {\n return { error: rpcError(E.WHISPER_LAPSED, \"Whisper already lapsed\") };\n }\n\n const answerOption = p.answer_option as string | undefined;\n const answerText = (p.answer as string | undefined) ?? (p.answer_text as string | undefined);\n if (prompt.options && prompt.options.length) {\n if (answerOption === undefined) {\n return { error: rpcError(E.PARAMS, \"answer_option is required when options are defined\") };\n }\n const valid = new Set(prompt.options.map(o => o.id));\n if (!valid.has(answerOption)) {\n return { error: rpcError(E.WHISPER_OPTION_NOT_IN_SET,\n `Answer option ${JSON.stringify(answerOption)} not in option set`) };\n }\n } else {\n if (answerText === undefined && answerOption === undefined) {\n return { error: rpcError(E.PARAMS, \"answer or answer_option required\") };\n }\n }\n\n prompt.state = \"answered\";\n prompt.answered_at = coord.now();\n prompt.answered_by = p.from as string;\n prompt.answer_option = answerOption;\n prompt.answer_text = answerText;\n prompt.comment = p.comment as string | undefined;\n // Echo the whisper's task_id onto the recorded envelope so a\n // task-filtered audit.read returns the answer alongside the ask. The\n // value comes from the stored whisper, not the caller, so an answer\n // cannot be filed against a different task.\n p.task_id = prompt.task_id;\n return { result: { answered: true, whisper_id: prompt.id, task_id: prompt.task_id } };\n });\n\n // Expose the lapse-check function on the coordinator instance.\n coord.checkWhisperLapses = (workspaceId: string, now?: string): Envelope[] => {\n const ws = coord.workspaces.get(workspaceId);\n if (!ws) return [];\n const cutoff = parseIso(now ?? coord.now());\n const emitted: Envelope[] = [];\n for (const prompt of ws.whispers.values()) {\n if (prompt.state !== \"pending\") continue;\n const asked = parseIso(prompt.asked_at);\n const deadline = asked + prompt.deadline_ms;\n if (cutoff < deadline) continue;\n prompt.state = \"lapsed\";\n prompt.default_applied = prompt.default_if_lapsed;\n const notify: Envelope = {\n jsonrpc: \"2.0\",\n method: \"notify.message\",\n params: {\n workspace: ws.id,\n from: \"service:coordinator\",\n to: [prompt.asker, ...prompt.askee],\n ts: coord.now(),\n kind: \"whisper_lapsed\",\n whisper_id: prompt.id,\n // Carry the task so a task-filtered audit.read surfaces the\n // lapse. A lapsed whisper applies its default with no human\n // input, so it is the case most in need of being visible on\n // the task's thread.\n task_id: prompt.task_id,\n default_applied: prompt.default_if_lapsed,\n },\n };\n coord.recordAudit(ws, notify);\n emitted.push(notify);\n }\n return emitted;\n };\n}\n","/**\n * @brightbeamai/chap-coordinator/coordinator\n *\n * The Coordinator class. CHAP protocol logic, packaged as a library\n * rather than a CLI server. Applications instantiate one, call\n * `dispatch(envelope)`, subscribe to audit events, and persist via\n * the provided hooks.\n *\n * Coverage:\n * - Core (9 methods)\n * - review/1.0 (6 methods)\n * - whisper/1.0 (2 methods + lapse handling)\n * - deliberation/1.0 (4 methods)\n * - modes/1.0 (mode handling at task.create; trial forces review)\n * - handoff/1.0 (3 methods with multi-task and group support)\n * - control/1.0 (7 methods with task/participant/workspace scopes)\n * - routing/1.0 (3 methods producing route_decision artefacts)\n * - security-signed/1.0 (top-level `sig` field; key history)\n * - audit-scitt/1.0 (statement assembly + local chain linkage)\n * - identity-oidc/1.0 + identity-vc/1.0 (binding hooks at join)\n */\n\nimport { canonicalize, contentHash, sha256Hex, ZERO_HASH } from \"./canonical.js\";\nimport { publicKeyFromJwk, verifyEnvelope } from \"./crypto.js\";\nimport { IdFactory } from \"./ids.js\";\nimport { E, isValidEnvelope, rpcError } from \"./jsonrpc.js\";\nimport { applyJsonPatch } from \"./patch.js\";\nimport type { Store, WorkspaceRecord } from \"./storage/store.js\";\nimport { MemoryStore } from \"./storage/store.js\";\nimport { makeApi, type CoordinatorApi } from \"./api.js\";\nimport type {\n ArtefactId,\n AuditEntry,\n AuditListener,\n Envelope,\n KeyRecord,\n Member,\n Mode,\n OverrideArtefact,\n ParticipantUri,\n Task,\n TaskId,\n Workspace,\n WorkspaceId,\n} from \"./types.js\";\nimport { modeLE } from \"./types.js\";\nimport { registerAuditScitt } from \"./profiles/audit_scitt.js\";\nimport { registerControl } from \"./profiles/control.js\";\nimport { registerDeliberation } from \"./profiles/deliberation.js\";\nimport { registerHandoff } from \"./profiles/handoff.js\";\nimport { registerRouting } from \"./profiles/routing.js\";\nimport { registerSecuritySigned } from \"./profiles/security_signed.js\";\nimport { registerWhisper } from \"./profiles/whisper.js\";\n\n// ============================================================\n// Options\n// ============================================================\n\nexport type TokenVerifier = (token: string) => Record<string, unknown> | null;\nexport type CredentialVerifier = (presentation: Record<string, unknown>) => Record<string, unknown> | null;\nexport type ScittSubmitter = (statement: Record<string, unknown>) => Record<string, unknown> | null;\nexport type ScittReceiptVerifier = (receipt: Record<string, unknown>) => boolean;\nexport type RoutingPolicyFn = (task: Task, candidates: ParticipantUri[]) => {\n selected: ParticipantUri;\n rationale: Record<string, unknown>;\n};\nexport type ReviewDepthPolicyFn = (task: Task, hints: Record<string, unknown>) => {\n depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n sampling_probability?: number;\n rationale: Record<string, unknown>;\n};\nexport type EscalationPolicyFn = (task: Task, hints: Record<string, unknown>) => {\n escalate: boolean;\n to?: ParticipantUri;\n triggered_rule?: Record<string, unknown>;\n};\n\n/** Methods classified as privileged for step-up auth. */\nexport const PRIVILEGED_METHODS = new Set<string>([\n \"control.pause\", \"control.resume\", \"control.cancel\", \"control.supersede\",\n \"control.snapshot\", \"control.rollback\", \"control.set_mode_ceiling\",\n \"workspace.set_profiles\",\n \"participant.rotate_key\", \"participant.revoke_key\",\n]);\n\n// Read-only methods return workspace state but do not mutate it, so they are not\n// recorded in the audit chain -- recording a read would grow and re-link it.\nconst READ_ONLY_METHODS = new Set<string>([\n \"workspace.describe\", \"audit.read\", \"audit.verify_chain\", \"audit.verify_receipt\",\n]);\n\nexport interface CoordinatorOptions {\n deterministicIds?: boolean;\n deterministicClock?: boolean;\n enableChain?: boolean;\n requireSignatures?: boolean;\n enforceStepUp?: boolean;\n requireReadMembership?: boolean;\n onAudit?: AuditListener;\n onAutoEscalate?: (task: Task, to: ParticipantUri) => void;\n verifyOidcToken?: TokenVerifier;\n verifyVc?: CredentialVerifier;\n scittSubmitter?: ScittSubmitter;\n verifyScittReceipt?: ScittReceiptVerifier;\n routingPolicy?: RoutingPolicyFn;\n reviewDepthPolicy?: ReviewDepthPolicyFn;\n escalationPolicy?: EscalationPolicyFn;\n defaultProfiles?: string[];\n /**\n * Persistence backend. Defaults to MemoryStore (no persistence).\n * Pass SqliteStore or any other Store implementation to persist\n * workspaces between process restarts. The Coordinator calls\n * `store.load()` once during `start()` and `store.save()` after\n * every successful mutation.\n */\n store?: Store;\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\nfunction nowIso(clockMs?: number): string {\n const d = clockMs === undefined ? new Date() : new Date(clockMs);\n return d.toISOString().replace(/\\.(\\d{3})Z$/, \".$1Z\");\n}\n\nfunction missing(params: Record<string, unknown>, fields: string[]): string | null {\n for (const f of fields) if (!(f in params)) return f;\n return null;\n}\n\nfunction tagsError(p: Record<string, unknown>): { error: ReturnType<typeof rpcError> } | null {\n const tags = p.tags;\n if (tags !== undefined && (!Array.isArray(tags) || !tags.every((t) => typeof t === \"string\"))) {\n return { error: rpcError(E.PARAMS, \"tags must be a list of strings\") };\n }\n return null;\n}\n\nfunction linkHash(envelope: Envelope, prev: string): string {\n return sha256Hex(Buffer.concat([canonicalize(envelope), Buffer.from(prev, \"utf-8\")]));\n}\n\nfunction reply(env: Envelope, body: { result?: unknown; error?: { code: number; message: string; data?: unknown } }): Envelope {\n const out: Envelope = { jsonrpc: \"2.0\", id: env.id };\n if (body.error !== undefined) out.error = body.error;\n else out.result = body.result;\n return out;\n}\n\n// ============================================================\n// Handler type for profile modules\n// ============================================================\n\nexport type Handler = (params: Record<string, unknown>) => { result?: unknown; error?: { code: number; message: string; data?: unknown } };\n\n// ============================================================\n// Coordinator\n// ============================================================\n\nexport class Coordinator {\n readonly workspaces = new Map<WorkspaceId, Workspace>();\n readonly options: CoordinatorOptions;\n readonly ids: IdFactory;\n readonly store: Store;\n private wsVersions = new Map<WorkspaceId, number>();\n private clockMs?: number;\n private auditListeners: AuditListener[] = [];\n /** Method handler registry; profiles plug into this. */\n readonly handlers = new Map<string, Handler>();\n /** Custom lapse-check function (whisper/1.0). Set by the whisper profile. */\n checkWhisperLapses?: (workspaceId: string, now?: string) => Envelope[];\n /** Typed method facade. Defined via getter in the constructor. */\n readonly api!: CoordinatorApi;\n /** @internal cached facade instance */\n private _api?: CoordinatorApi;\n\n constructor(options: CoordinatorOptions = {}) {\n this.options = options;\n this.store = options.store ?? new MemoryStore();\n this.ids = new IdFactory(!!options.deterministicIds, 0n, 1_700_000_000_000);\n if (options.deterministicClock) this.clockMs = 1_700_000_000_000;\n if (options.onAudit) this.auditListeners.push(options.onAudit);\n\n this.registerCoreHandlers();\n this.registerProfileHandlers();\n\n // Lazily-initialised typed facade. Constructed on first access so\n // tests that don't use it pay nothing.\n Object.defineProperty(this, \"api\", {\n get: () => {\n if (!this._api) this._api = makeApi(this);\n return this._api;\n },\n enumerable: false,\n configurable: true,\n });\n\n // Rehydrate any persisted state synchronously. Async stores can\n // call `start()` instead; this fallback covers the common\n // synchronous Memory/Sqlite path with no async setup needed.\n try {\n const loaded = this.store.load();\n if (!(loaded instanceof Promise)) {\n this.applyRecords(loaded);\n }\n } catch {\n /* fall through; caller must invoke start() */\n }\n }\n\n /**\n * Asynchronously hydrate workspaces from the store. Required only for\n * stores whose `load()` returns a Promise. Idempotent.\n */\n async start(): Promise<void> {\n const records = await this.store.load();\n this.applyRecords(records);\n }\n\n private applyRecords(records: WorkspaceRecord[]): void {\n this.workspaces.clear();\n this.wsVersions.clear();\n for (const r of records) {\n this.restore([r.data]);\n this.wsVersions.set(r.id, r.version);\n }\n }\n\n /** Persist the current snapshot of one workspace to the store. */\n private persist(ws: Workspace): void {\n const next = (this.wsVersions.get(ws.id) ?? 0) + 1;\n this.wsVersions.set(ws.id, next);\n try {\n // snapshot() returns an array of all workspaces; we only need\n // this one, so slice it. Stores are per-workspace.\n const all = this.snapshot() as Array<Record<string, unknown>>;\n const data = all.find(w => w.id === ws.id);\n if (!data) return;\n const result = this.store.save({\n id: ws.id,\n data,\n version: next,\n updated_at: this.now(),\n });\n // Async stores: fire-and-forget; failures surface via process unhandled-rejection.\n // Sync stores: nothing to do.\n if (result instanceof Promise) {\n result.catch(() => { /* deliberately swallowed; stores should log */ });\n }\n } catch {\n // Persistence failures must not break dispatch. Audit listeners\n // can mirror the audit stream to a second sink for durability.\n }\n }\n\n // -- lifecycle -----------------------------------------------------\n\n now(): string {\n if (this.clockMs !== undefined) {\n this.clockMs += 1000;\n return nowIso(this.clockMs);\n }\n return nowIso();\n }\n\n onAudit(listener: AuditListener): () => void {\n this.auditListeners.push(listener);\n return () => {\n const i = this.auditListeners.indexOf(listener);\n if (i >= 0) this.auditListeners.splice(i, 1);\n };\n }\n\n /** Convenience: get a workspace by id, or undefined. */\n getWorkspace(id: WorkspaceId): Workspace | undefined {\n return this.workspaces.get(id);\n }\n\n // ----- authorisation preconditions -----\n\n /**\n * Assert that `sender` is a joined member of `ws`. Returns an error\n * fragment if not, else null. Every actor-action method runs this on\n * its `from` so a decision, completion, or review request can never\n * be attributed to a participant who never joined. See\n * SPECIFICATION.md S6.3 and the `unknown_participant` condition in\n * S13.3. (The published spec assigns -32403; the reference\n * implementations use NOT_AUTHORISED -32011 because -32403 already\n * denotes OIDC_TOKEN_INVALID in their private range. The spec/impl\n * error-table divergence is tracked separately.)\n */\n private requireMember(ws: Workspace, sender: unknown): { error: ReturnType<typeof rpcError> } | null {\n if (typeof sender !== \"string\" || !ws.members.has(sender)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not a workspace member: ${String(sender)}`) };\n }\n return null;\n }\n\n /**\n * Assert that `sender` was addressed in the task's review. Applied to\n * review-decision methods (decide.* and abstain.declare): to act on a\n * review you must be one of the reviewers it was addressed to (the\n * `to` set on review.request). Membership is the floor; this is the\n * eligibility ceiling for decisions. Returns an error fragment if not\n * eligible, else null.\n */\n private requireReviewer(task: Task, sender: unknown): { error: ReturnType<typeof rpcError> } | null {\n const review = task.review;\n if (!review || !review.requested_to || review.requested_to.length === 0) {\n // No recorded reviewer set: fall back to the membership floor,\n // which the caller has already enforced.\n return null;\n }\n // A broadcast-scoped reviewer (workspace:/group: URI) is satisfied by\n // any workspace member; the membership floor already passed. Note the\n // coordinator does not model group membership: a group: target means\n // \"any member\", not \"any member of that group\" (deployments needing\n // true group restriction enforce it externally). Keeps the documented\n // `to: workspace:<id>` broadcast pattern working.\n if (review.requested_to.some((r) => typeof r === \"string\" && (r.startsWith(\"workspace:\") || r.startsWith(\"group:\")))) {\n return null;\n }\n if (typeof sender !== \"string\" || !review.requested_to.includes(sender as ParticipantUri)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not an addressed reviewer for this task: ${String(sender)}`) };\n }\n return null;\n }\n\n /** Serialise all workspaces to a JSON-safe structure for persistence. */\n snapshot(): unknown {\n const out: Array<Record<string, unknown>> = [];\n for (const ws of this.workspaces.values()) {\n out.push({\n id: ws.id,\n created: ws.created,\n state: ws.state,\n profiles: ws.profiles,\n mode: ws.mode,\n mode_ceiling: ws.mode_ceiling,\n routing_policy_uri: ws.routing_policy_uri,\n step_up_window_sec: ws.step_up_window_sec,\n min_acr: ws.min_acr,\n members: Array.from(ws.members.values()),\n tasks: Array.from(ws.tasks.values()),\n overrides: Array.from(ws.overrides.values()),\n whispers: Array.from(ws.whispers.values()),\n deliberations: Array.from(ws.deliberations.values()),\n handoffs: Array.from(ws.handoffs.values()),\n snapshots: Array.from(ws.snapshots.values()),\n route_decisions: Array.from(ws.route_decisions.values()),\n idempotency_keys: ws.idempotency_keys,\n audit: ws.audit,\n chain_head: ws.chain_head,\n chain_enabled: ws.chain_enabled,\n });\n }\n return out;\n }\n\n /** Restore from a snapshot produced by ``snapshot()``. Replaces\n * any existing in-memory workspaces. */\n restore(data: unknown): void {\n this.workspaces.clear();\n if (!Array.isArray(data)) return;\n for (const w of data as Array<Record<string, unknown>>) {\n const ws: Workspace = {\n id: w.id as WorkspaceId,\n created: w.created as string,\n state: (w.state as Workspace[\"state\"]) ?? \"active\",\n profiles: (w.profiles as string[]) ?? [],\n mode: (w.mode as Mode) ?? \"trial\",\n mode_ceiling: (w.mode_ceiling as Mode) ?? \"production\",\n routing_policy_uri: w.routing_policy_uri as string | undefined,\n step_up_window_sec: (w.step_up_window_sec as number) ?? 300,\n min_acr: w.min_acr as string | undefined,\n members: new Map(),\n tasks: new Map(),\n overrides: new Map(),\n whispers: new Map(),\n deliberations: new Map(),\n handoffs: new Map(),\n snapshots: new Map(),\n route_decisions: new Map(),\n idempotency_keys: (w.idempotency_keys as Record<string, string>) ?? {},\n audit: (w.audit as AuditEntry[]) ?? [],\n chain_head: w.chain_head as string | undefined,\n chain_enabled: !!w.chain_enabled,\n };\n for (const m of (w.members as Member[]) ?? []) {\n // Defensive: ensure required collections exist even on older snapshots.\n if (!Array.isArray(m.keys)) m.keys = [];\n if (m.paused === undefined) m.paused = false;\n ws.members.set(m.uri, m);\n }\n for (const t of (w.tasks as Task[]) ?? []) ws.tasks.set(t.id, t);\n for (const o of (w.overrides as OverrideArtefact[]) ?? []) ws.overrides.set(o.id, o);\n // The dynamic profile collections may not be present on legacy snapshots.\n for (const x of (w.whispers as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.whispers.set(x.id, x as never);\n for (const x of (w.deliberations as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.deliberations.set(x.id, x as never);\n for (const x of (w.handoffs as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.handoffs.set(x.id, x as never);\n for (const x of (w.snapshots as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.snapshots.set(x.id, x as never);\n for (const x of (w.route_decisions as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.route_decisions.set(x.id, x as never);\n this.workspaces.set(ws.id, ws);\n }\n }\n\n // -- dispatch ------------------------------------------------------\n\n dispatch(envelope: Envelope): Envelope {\n if (!isValidEnvelope(envelope) || !envelope.method) {\n return reply(envelope, { error: rpcError(E.REQUEST, \"Invalid JSON-RPC 2.0 request\") });\n }\n const method = envelope.method;\n // JSON-RPC params, when present, must be a structured value (object).\n // CHAP methods use by-name params; reject non-object params cleanly as\n // Invalid params for parity with the Python reference.\n const rawParams = envelope.params;\n if (\n rawParams !== undefined &&\n rawParams !== null &&\n (typeof rawParams !== \"object\" || Array.isArray(rawParams))\n ) {\n return reply(envelope, { error: rpcError(E.PARAMS, \"Invalid params: expected an object\") });\n }\n const params = (rawParams ?? {}) as Record<string, unknown>;\n\n // security-signed/1.0: verify top-level sig if required.\n // participant.join and workspace.create are bootstrap operations that\n // run before any signing key is registered for the actor, so they cannot\n // be signature-verified; every other method must verify.\n if (this.options.requireSignatures && method !== \"participant.join\" && method !== \"workspace.create\") {\n const sigErr = this.verifySignature(envelope);\n if (sigErr) return reply(envelope, { error: sigErr });\n if (method === \"participant.rotate_key\") {\n const signingKid = (envelope.sig as string).split(\":\")[1];\n const oldKid = params.old_kid as string | undefined;\n if (oldKid !== undefined && signingKid !== oldKid) {\n return reply(envelope, { error: rpcError(E.SIG_ROTATION_KEY_MISMATCH,\n \"Rotation must be signed with the old key\") });\n }\n }\n }\n\n // identity-oidc/1.0: step-up freshness on privileged methods.\n if (this.options.enforceStepUp && PRIVILEGED_METHODS.has(method)) {\n const stale = this.checkStepUp(params);\n if (stale) return reply(envelope, { error: stale });\n }\n\n // control/1.0 and deliberation/1.0: these operations are privileged and\n // MUST be performed by a workspace member. Control is the governance\n // \"emergency brake\"; deliberation open/close set the vote parameters and\n // finalize the tally. Without this floor a non-member could resume a\n // paused workspace, raise the mode ceiling, or open and close a\n // deliberation to finalize an outcome early. (The per-voter eligibility\n // check in deliberate.vote is separate and still applies. A stricter role\n // gate than membership is layered on top via an identity-* profile.)\n if (method.startsWith(\"control.\") || method.startsWith(\"deliberate.\") || method.startsWith(\"handoff.\")) {\n const wsId = params.workspace as string | undefined;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n if (ws) {\n const notMember = this.requireMember(ws, params.from);\n if (notMember) return reply(envelope, { error: notMember.error });\n }\n }\n\n // control/1.0 workspace-paused gate (S6 -32063).\n const exempt = new Set([\"workspace.create\", \"workspace.describe\",\n \"control.resume\", \"audit.read\",\n \"participant.join\", \"participant.leave\"]);\n if (!exempt.has(method)) {\n const wsId = params.workspace as string | undefined;\n if (typeof wsId === \"string\") {\n const ws = this.workspaces.get(wsId);\n if (ws && ws.state === \"paused\") {\n return reply(envelope, { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Workspace ${wsId} is paused`) });\n }\n }\n }\n\n // task.create idempotency: a repeat carrying a seen idempotency_key returns\n // the original task rather than creating (or recording) a duplicate -- safe\n // for at-least-once redelivery.\n if (method === \"task.create\") {\n const wsId = params.workspace;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n const key = params.idempotency_key;\n if (ws && typeof key === \"string\") {\n const existingId = ws.idempotency_keys[key];\n const task = existingId ? ws.tasks.get(existingId) : undefined;\n if (task) return reply(envelope, { result: { task_id: existingId, state: task.state } });\n }\n }\n\n const handler = this.handlers.get(method);\n if (!handler) {\n return reply(envelope, { error: rpcError(E.METHOD, `Unknown method: ${method}`) });\n }\n\n try {\n canonicalize(envelope);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return reply(envelope, { error: rpcError(E.PARAMS, msg) });\n }\n\n let out: { result?: unknown; error?: { code: number; message: string; data?: unknown } };\n try {\n out = handler(params);\n } catch (e) {\n // Keep the wire message generic; a handler exception may carry internal\n // detail that should not be disclosed to callers. Specifics stay in the\n // data field for operators.\n const msg = e instanceof Error ? e.message : String(e);\n return reply(envelope, { error: rpcError(E.INTERNAL, \"Internal error\", { detail: msg }) });\n }\n if (out.error) return reply(envelope, { error: out.error });\n\n // Record audit on success\n const wsId = params.workspace as string | undefined;\n if (typeof wsId === \"string\" && !READ_ONLY_METHODS.has(method)) {\n const ws = this.workspaces.get(wsId);\n if (ws) this.recordAudit(ws, envelope);\n }\n return reply(envelope, { result: out.result });\n }\n\n // -- audit ---------------------------------------------------------\n\n recordAudit(ws: Workspace, envelope: Envelope): void {\n const entry: AuditEntry = {\n seq: ws.audit.length,\n arrived: this.now(),\n envelope: JSON.parse(JSON.stringify(envelope)) as Envelope,\n };\n if (ws.chain_enabled || this.options.enableChain) {\n const prev = ws.chain_head ?? ZERO_HASH;\n entry.prev_hash = prev;\n ws.chain_head = linkHash(entry.envelope, prev);\n }\n ws.audit.push(entry);\n for (const l of this.auditListeners) {\n try { l(ws, entry); } catch { /* listeners never break dispatch */ }\n }\n // Persistence: only meaningful when a non-Memory store is configured;\n // MemoryStore.save() is a no-op for the dispatcher's perspective.\n this.persist(ws);\n }\n\n // -- signature verification (security-signed/1.0) -----------------\n\n private verifySignature(envelope: Envelope): { code: number; message: string; data?: unknown } | null {\n const sig = envelope.sig;\n if (!sig || typeof sig !== \"string\") {\n return rpcError(E.SIG_VERIFY_FAILED, \"Missing top-level `sig` field\");\n }\n const parts = sig.split(\":\");\n if (parts.length !== 3 || parts[0] !== \"ed25519\") {\n return rpcError(E.SIG_VERIFY_FAILED, \"Malformed signature tag\");\n }\n const kid = parts[1];\n const params = (envelope.params ?? {}) as Record<string, unknown>;\n const sender = params.from as string | undefined;\n const wsId = params.workspace as string | undefined;\n const ts = (params.ts as string | undefined) ?? this.now();\n // Fail closed: a signature is present and requireSignatures is on, so it\n // must verify. If we cannot resolve the context needed to verify it,\n // reject rather than skip -- a signature we cannot check must never be\n // treated as valid.\n if (!sender || !wsId) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: missing from/workspace\");\n }\n const ws = this.workspaces.get(wsId);\n if (!ws) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: unknown workspace\");\n }\n const member = ws.members.get(sender);\n if (!member) return rpcError(E.SIG_KEY_NOT_FOUND, `No member: ${sender}`);\n\n // Revocation is present-tense: a revoked key must be rejected for any\n // live request regardless of the envelope's self-asserted `ts`. Checking\n // against `ts` alone lets a holder of a revoked key backdate `ts` to\n // before the revocation and still be accepted. Use the coordinator's\n // trusted clock for the revocation decision.\n const now = this.now();\n if (member.keys.some(k => k.kid === kid && k.revoked_at !== undefined && now >= k.revoked_at)) {\n return rpcError(E.SIG_KEY_REVOKED, `Key ${kid} is revoked`);\n }\n\n const key = this.lookupKey(member, kid, ts);\n if (!key) {\n const revoked = member.keys.find(k => k.kid === kid && k.revoked_at);\n if (revoked) return rpcError(E.SIG_KEY_REVOKED, `Key ${kid} is revoked`);\n return rpcError(E.SIG_KEY_NOT_FOUND, `No key ${kid} valid at ${ts} for ${sender}`);\n }\n\n // Verify\n try {\n const stripped: Envelope = JSON.parse(JSON.stringify(envelope));\n delete stripped.sig;\n const canonical = canonicalize(stripped);\n const pub = publicKeyFromJwk(key.jwk);\n if (!verifyEnvelope(canonical, sig, pub)) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Signature failed verification\");\n }\n return null;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return rpcError(E.INTERNAL, `Signature check error: ${msg}`);\n }\n }\n\n /** Lookup the key valid for a given participant at a given time. */\n lookupKey(member: Member, kid: string, ts: string): KeyRecord | null {\n for (const k of member.keys) {\n if (k.kid !== kid) continue;\n if (k.revoked_at !== undefined && ts >= k.revoked_at) continue;\n if (ts < k.valid_from) continue;\n if (k.valid_until !== undefined && ts >= k.valid_until) continue;\n return k;\n }\n return null;\n }\n\n // -- step-up (identity-oidc/1.0) -----------------------------------\n\n private checkStepUp(params: Record<string, unknown>): { code: number; message: string; data?: unknown } | null {\n const wsId = params.workspace as string | undefined;\n const sender = params.from as string | undefined;\n if (!wsId || !sender) return null;\n const ws = this.workspaces.get(wsId);\n if (!ws) return null;\n const member = ws.members.get(sender);\n if (!member) return null;\n // Step-up applies to OIDC actors -- humans, or any member with an OIDC\n // binding. Agents and services authenticate out of band (SPIFFE/X.509),\n // so they are not held to an auth_time window here.\n if (member.type !== \"human\" && member.oidc_sub === undefined) return null;\n if (member.oidc_auth_time === undefined) {\n return rpcError(E.OIDC_STEP_UP_REQUIRED, \"Step-up authentication required\", {\n window_sec: ws.step_up_window_sec,\n });\n }\n const nowSec = Math.floor(Date.now() / 1000);\n const age = nowSec - member.oidc_auth_time;\n if (age > ws.step_up_window_sec) {\n return rpcError(E.OIDC_STEP_UP_REQUIRED, \"Step-up authentication required\", {\n window_sec: ws.step_up_window_sec, age_sec: age,\n });\n }\n if (ws.min_acr !== undefined && member.oidc_acr !== ws.min_acr) {\n return rpcError(E.OIDC_STEP_UP_REQUIRED, \"Step-up required: acr below the workspace minimum\", {\n required_acr: ws.min_acr, acr: member.oidc_acr,\n });\n }\n return null;\n }\n\n // ==========================================================\n // Registration\n // ==========================================================\n\n private registerCoreHandlers(): void {\n this.handlers.set(\"workspace.create\", p => this.opWorkspaceCreate(p));\n this.handlers.set(\"workspace.describe\", p => this.opWorkspaceDescribe(p));\n this.handlers.set(\"workspace.set_profiles\", p => this.opWorkspaceSetProfiles(p));\n this.handlers.set(\"participant.join\", p => this.opParticipantJoin(p));\n this.handlers.set(\"participant.leave\", p => this.opParticipantLeave(p));\n this.handlers.set(\"task.create\", p => this.opTaskCreate(p));\n this.handlers.set(\"task.update\", p => this.opTaskUpdate(p));\n this.handlers.set(\"task.complete\", p => this.opTaskComplete(p));\n this.handlers.set(\"audit.read\", p => this.opAuditRead(p));\n this.handlers.set(\"review.request\", p => this.opReviewRequest(p));\n this.handlers.set(\"decide.approve\", p => this.opDecide(p, \"approve\"));\n this.handlers.set(\"decide.reject\", p => this.opDecide(p, \"reject\"));\n this.handlers.set(\"decide.override\", p => this.opDecideOverride(p));\n this.handlers.set(\"abstain.declare\", p => this.opAbstainDeclare(p));\n this.handlers.set(\"escalate.raise\", p => this.opEscalateRaise(p));\n }\n\n private registerProfileHandlers(): void {\n // Profiles register themselves by mutating this.handlers\n registerWhisper(this);\n registerDeliberation(this);\n registerHandoff(this);\n registerControl(this);\n registerRouting(this);\n registerSecuritySigned(this);\n registerAuditScitt(this);\n }\n\n // ==========================================================\n // Core method handlers\n // ==========================================================\n\n private opWorkspaceCreate(p: Record<string, unknown>): ReturnType<Handler> {\n const id = (p.workspace as string) || this.ids.workspaceId();\n if (typeof id !== \"string\") return { error: rpcError(E.PARAMS, \"workspace must be a string id\") };\n if (this.workspaces.has(id)) return { error: rpcError(E.PARAMS, `workspace already exists: ${id}`) };\n const profiles: string[] = Array.isArray(p.profiles) ? [...(p.profiles as string[])] : [...(this.options.defaultProfiles ?? [\"core/1.0\", \"review/1.0\"])];\n const chainEnabled = profiles.includes(\"audit-scitt/1.0\") || !!this.options.enableChain;\n const ws: Workspace = {\n id,\n created: this.now(),\n state: \"active\",\n profiles,\n mode: (p.mode as Mode) ?? \"trial\",\n mode_ceiling: (p.mode_ceiling as Mode) ?? \"production\",\n routing_policy_uri: p.routing_policy_uri as string | undefined,\n step_up_window_sec: typeof p.step_up_window_sec === \"number\" ? p.step_up_window_sec : 300,\n min_acr: p.min_acr as string | undefined,\n members: new Map(),\n tasks: new Map(),\n overrides: new Map(),\n whispers: new Map(),\n deliberations: new Map(),\n handoffs: new Map(),\n snapshots: new Map(),\n route_decisions: new Map(),\n idempotency_keys: {},\n audit: [],\n chain_enabled: chainEnabled,\n chain_head: chainEnabled ? ZERO_HASH : undefined,\n };\n this.workspaces.set(id, ws);\n return { result: { workspace: id, created: ws.created } };\n }\n\n private opWorkspaceDescribe(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, `Unknown workspace: ${p.workspace}`) };\n if (this.options.requireReadMembership) {\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n }\n return { result: {\n id: ws.id,\n created: ws.created,\n state: ws.state,\n mode: ws.mode,\n mode_ceiling: ws.mode_ceiling,\n step_up_window_sec: ws.step_up_window_sec,\n profiles: ws.profiles,\n members: Array.from(ws.members.values()).map(memberToDict),\n audit_count: ws.audit.length,\n task_count: ws.tasks.size,\n override_count: ws.overrides.size,\n evidence_head: ws.chain_head,\n ...(ws.routing_policy_uri ? { routing_policy_uri: ws.routing_policy_uri } : {}),\n }};\n }\n\n private opWorkspaceSetProfiles(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"profiles\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n if (ws.members.get(p.from as string)!.role !== \"admin\") {\n return { error: rpcError(E.NOT_AUTHORISED, \"workspace.set_profiles requires the admin role\") };\n }\n const newProfiles = [...(p.profiles as string[])];\n if (!newProfiles.some(pr => pr.startsWith(\"core/\"))) newProfiles.push(\"core/1.0\");\n ws.profiles = newProfiles;\n if (newProfiles.includes(\"audit-scitt/1.0\") && !ws.chain_enabled) {\n ws.chain_enabled = true;\n ws.chain_head = ZERO_HASH;\n }\n return { result: { profiles: ws.profiles } };\n }\n\n private opParticipantJoin(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"type\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n let ws = this.workspaces.get(p.workspace as string);\n if (!ws) {\n const create = this.opWorkspaceCreate({ workspace: p.workspace });\n if (create.error) return create;\n ws = this.workspaces.get(p.workspace as string)!;\n }\n const uri = p.from as ParticipantUri;\n const now = this.now();\n\n const member: Member = {\n uri,\n type: p.type as Member[\"type\"],\n role: (p.role as string) || \"participant\",\n joined: now,\n display_name: p.display_name as string | undefined,\n capabilities: p.capabilities as Record<string, unknown> | undefined,\n scopes: p.scopes as string[] | undefined,\n keys: [],\n paused: false,\n };\n\n // identity-oidc/1.0\n if (this.options.verifyOidcToken && typeof p.oidc_token === \"string\") {\n const claims = this.options.verifyOidcToken(p.oidc_token);\n if (claims === null) return { error: rpcError(E.OIDC_TOKEN_INVALID, \"OIDC token invalid\") };\n member.oidc_sub = claims.sub as string | undefined;\n const at = claims.auth_time;\n if (typeof at === \"number\") member.oidc_auth_time = at;\n member.oidc_acr = claims.acr as string | undefined;\n const cnf = claims.cnf as Record<string, unknown> | undefined;\n const cnfJwk = cnf?.jwk as Record<string, unknown> | undefined;\n if (cnfJwk && typeof cnfJwk.kid === \"string\") {\n member.keys.push({ jwk: cnfJwk as unknown as KeyRecord[\"jwk\"], kid: cnfJwk.kid as string, valid_from: now });\n }\n }\n // identity-vc/1.0\n if (this.options.verifyVc && typeof p.vc_presentation === \"object\" && p.vc_presentation !== null) {\n const subject = this.options.verifyVc(p.vc_presentation as Record<string, unknown>);\n if (subject === null) return { error: rpcError(E.VC_VP_INVALID, \"VC presentation invalid\") };\n member.vc_holder = (subject.holder as string | undefined) ?? (subject.id as string | undefined);\n const vpJwk = subject.cnf_jwk as Record<string, unknown> | undefined;\n if (vpJwk && typeof vpJwk.kid === \"string\") {\n member.keys.push({ jwk: vpJwk as unknown as KeyRecord[\"jwk\"], kid: vpJwk.kid as string, valid_from: now });\n }\n }\n\n const attested = [...member.keys];\n\n // Self-asserted JWKs are ignored for an identity-bound participant: the\n // verifier-pinned cnf.jwk / vp_jwk is the signing key (proof of possession).\n const jwks = p.jwks as { keys?: Array<{ kid: string; [k: string]: unknown }> } | undefined;\n if (jwks?.keys && attested.length === 0) {\n for (const j of jwks.keys) {\n if (j.kid && !member.keys.some(k => k.kid === j.kid)) {\n member.keys.push({ jwk: j as unknown as KeyRecord[\"jwk\"], kid: j.kid, valid_from: now });\n }\n }\n }\n\n const existing = ws.members.get(uri);\n if (existing) {\n if (member.oidc_sub !== undefined) existing.oidc_sub = member.oidc_sub;\n if (member.oidc_auth_time !== undefined) existing.oidc_auth_time = member.oidc_auth_time;\n if (member.oidc_acr !== undefined) existing.oidc_acr = member.oidc_acr;\n if (member.vc_holder !== undefined) existing.vc_holder = member.vc_holder;\n for (const k of attested) {\n if (!existing.keys.some(x => x.kid === k.kid)) existing.keys.push(k);\n }\n return { result: { joined: true, as: uri } };\n }\n ws.members.set(uri, member);\n return { result: { joined: true, as: uri } };\n }\n\n private opParticipantLeave(p: Record<string, unknown>): ReturnType<Handler> {\n // Self-removal: deletes the caller's own `from`. Under requireSignatures the\n // signature binds `from`, so a member can only remove itself; evicting\n // another member is an admin operation, not this. Unsigned, a spoofed\n // `from` is the transport's responsibility.\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n ws.members.delete(p.from as string);\n return { result: { left: true } };\n }\n\n private opTaskCreate(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"kind\", \"input\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const assignee = (p.assignee as string) || (p.to as string);\n if (!assignee || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"Assignee not in workspace\") };\n }\n if (ws.members.get(assignee)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${assignee} is paused`) };\n }\n\n // modes/1.0 ceiling check\n const requestedMode = ((p.mode as Mode) || ws.mode);\n if (!modeLE(requestedMode, ws.mode_ceiling)) {\n return { error: rpcError(E.MODE_CEILING_EXCEEDED,\n `Requested mode ${requestedMode} exceeds ceiling ${ws.mode_ceiling}`) };\n }\n\n const taskId = this.ids.taskId();\n const now = this.now();\n const task: Task = {\n id: taskId,\n kind: p.kind as string,\n state: \"created\",\n assignee,\n delegator: p.from as ParticipantUri,\n input: p.input as Record<string, unknown>,\n created_at: now,\n updated_at: now,\n deadline: p.deadline as string | undefined,\n mode: requestedMode,\n routing_hints: p.routing_hints as Task[\"routing_hints\"],\n history: [{ ts: now, from: p.from as ParticipantUri, state: \"created\" }],\n paused: false,\n };\n\n // modes/1.0: trial mode forces review\n if (task.mode === \"trial\") task.review_required = true;\n else if (\"review_required\" in p) task.review_required = !!p.review_required;\n\n ws.tasks.set(taskId, task);\n if (typeof p.idempotency_key === \"string\") ws.idempotency_keys[p.idempotency_key] = taskId;\n return { result: { task_id: taskId, state: \"created\" } };\n }\n\n private opTaskUpdate(p: Record<string, unknown>): ReturnType<Handler> {\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const newState = p.state as Task[\"state\"];\n const legal: Record<string, string[]> = {\n created: [\"in_progress\", \"declined\", \"paused\"],\n in_progress: [\"in_progress\", \"completed\", \"declined\", \"review_requested\", \"paused\"],\n review_requested: [\"in_progress\", \"completed\", \"declined\"],\n paused: [\"in_progress\", \"cancelled\"],\n };\n if (!legal[task.state]?.includes(newState)) {\n return { error: rpcError(E.PARAMS, `Illegal transition ${task.state} -> ${newState}`) };\n }\n task.state = newState;\n task.updated_at = this.now();\n task.history.push({\n ts: task.updated_at, from: p.from as ParticipantUri,\n state: newState, note: p.progress_note as string | undefined,\n });\n return { result: { state: newState } };\n }\n\n private opTaskComplete(p: Record<string, unknown>): ReturnType<Handler> {\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n // Completion is only legal from an active, non-terminal, non-paused state.\n // An allowlist (rather than a denylist of terminal states) is safer: any\n // state not listed -- cancelled, superseded, paused, already\n // completed/declined, abstained, escalated -- is rejected, so completion\n // can neither revive a terminated task nor bypass a pause.\n if (task.state !== \"created\" && task.state !== \"in_progress\") {\n return { error: rpcError(E.PARAMS, `Cannot complete task in state: ${task.state}`) };\n }\n task.output = p.output;\n if (typeof p.confidence === \"number\" || typeof p.confidence === \"string\") task.confidence = p.confidence;\n task.state = \"completed\";\n task.updated_at = this.now();\n task.history.push({ ts: task.updated_at, from: p.from as ParticipantUri, state: \"completed\" });\n return { result: { state: \"completed\" } };\n }\n\n private opAuditRead(p: Record<string, unknown>): ReturnType<Handler> {\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n if (this.options.requireReadMembership) {\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n }\n const range = (p.range as { from_seq?: number; to_seq?: number } | undefined) ?? {};\n const filter = (p.filter as { method?: string; from?: string; task_id?: string } | undefined) ?? {};\n const fromSeq = range.from_seq ?? 0;\n const toSeq = range.to_seq ?? ws.audit.length;\n const out: unknown[] = [];\n for (const entry of ws.audit.slice(fromSeq, toSeq)) {\n const ep = (entry.envelope.params ?? {}) as Record<string, unknown>;\n if (filter.method && entry.envelope.method !== filter.method) continue;\n if (filter.from && ep.from !== filter.from) continue;\n if (filter.task_id && ep.task_id !== filter.task_id) continue;\n const item: Record<string, unknown> = {\n seq: entry.seq, arrived: entry.arrived, envelope: entry.envelope,\n };\n if (entry.prev_hash) item.prev_hash = entry.prev_hash;\n out.push(item);\n }\n return { result: { entries: out, next_seq: toSeq } };\n }\n\n // ==========================================================\n // review/1.0 handlers\n // ==========================================================\n\n private opReviewRequest(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\", \"artefact\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const to = p.to;\n const reviewers: string[] = Array.isArray(to) ? (to as string[]) : typeof to === \"string\" ? [to] : [];\n if (!reviewers.length) return { error: rpcError(E.PARAMS, \"review.request needs 'to'\") };\n const now = this.now();\n const rule = (p.rule as string) || \"any_one_approves\";\n\n // A review already open on this task. Replacing the artefact underneath\n // it would let a reviewer decide on content they never saw, and would\n // discard decisions already cast while their envelopes remain in the\n // audit log, so a quorum could appear to have been assembled across two\n // different artefacts. Re-requesting the *same* artefact is a different\n // thing: it widens the reviewer set on an open review, which is legitimate\n // and preserves what has been decided so far.\n if (task.state === \"review_requested\" && task.review) {\n if (contentHash(task.pending_artefact) !== contentHash(p.artefact)) {\n return { error: rpcError(\n E.REVIEW_ALREADY_OPEN,\n \"A review is already open on this task with different content. \" +\n \"Decide, abstain, escalate or cancel it before requesting review of a new artefact.\",\n ) };\n }\n if (rule !== task.review.rule) {\n return { error: rpcError(\n E.REVIEW_ALREADY_OPEN,\n `Cannot change the decision rule of an open review (currently ${task.review.rule})`,\n ) };\n }\n // Union, preserving order and the decisions already recorded.\n for (const r of reviewers) {\n if (!task.review.requested_to.includes(r)) task.review.requested_to.push(r);\n }\n if (p.deadline !== undefined) task.review.deadline = p.deadline as string;\n task.updated_at = now;\n return { result: {\n state: \"review_requested\",\n review_id: task.id,\n amended: true,\n requested_to: [...task.review.requested_to],\n } };\n }\n\n task.state = \"review_requested\";\n task.updated_at = now;\n task.review = {\n requested_at: now,\n requested_to: reviewers,\n rule,\n deadline: p.deadline as string | undefined,\n decisions: [],\n };\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: \"review_requested\" });\n task.pending_artefact = p.artefact;\n return { result: { state: \"review_requested\", review_id: task.id } };\n }\n\n /**\n * Verify an optional `approved_artefact_digest` against the artefact under\n * review (review/1.0 S3.2).\n *\n * The digest sits in params, so it is inside whatever the envelope signature\n * covers: the decision then attests the content the reviewer saw rather than\n * a task reference, and a relying party can check it without trusting the\n * Coordinator that produced it. Absent, behaviour is exactly as before.\n *\n * On mismatch nothing is recorded and no state changes, so a client that\n * computes the wrong digest refuses only its own decision.\n */\n private checkArtefactDigest(p: Record<string, unknown>, task: Task): ReturnType<Handler> | null {\n const declared = p.approved_artefact_digest;\n if (declared === undefined || declared === null) return null;\n if (typeof declared !== \"string\") {\n return { error: rpcError(E.PARAMS, \"approved_artefact_digest must be a string\") };\n }\n if (task.pending_artefact === undefined) {\n return { error: rpcError(E.PARAMS, \"No artefact under review to bind a digest to\") };\n }\n const actual = contentHash(task.pending_artefact);\n if (declared !== actual) {\n return { error: rpcError(\n E.SIG_ARTEFACT_DIGEST_MISMATCH,\n \"approved_artefact_digest does not match the artefact under review\",\n { declared, actual },\n ) };\n }\n return null;\n }\n\n private opDecide(p: Record<string, unknown>, kind: \"approve\" | \"reject\"): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const badTags = tagsError(p);\n if (badTags) return badTags;\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"review_requested\") {\n return { error: rpcError(E.NOT_REVIEWABLE, `Task not awaiting review: ${task.state}`) };\n }\n const notReviewer = this.requireReviewer(task, p.from);\n if (notReviewer) return notReviewer;\n const digestError = this.checkArtefactDigest(p, task);\n if (digestError) return digestError;\n const now = this.now();\n task.review!.decisions.push({\n reviewer: p.from as ParticipantUri,\n kind,\n ts: now,\n comment: p.comment as string | undefined,\n tags: p.tags as string[] | undefined,\n });\n if (kind === \"approve\") {\n task.output = task.pending_artefact;\n task.state = \"completed\";\n } else {\n task.state = p.request_revision ? \"in_progress\" : \"declined\";\n }\n task.updated_at = now;\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: task.state });\n return { result: { state: task.state } };\n }\n\n private opDecideOverride(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\", \"diff\", \"rationale\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const badTags = tagsError(p);\n if (badTags) return badTags;\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"review_requested\") {\n return { error: rpcError(E.NOT_REVIEWABLE, `Task not awaiting review: ${task.state}`) };\n }\n const notReviewer = this.requireReviewer(task, p.from);\n if (notReviewer) return notReviewer;\n const digestError = this.checkArtefactDigest(p, task);\n if (digestError) return digestError;\n // The override is of the artefact under review; use the coordinator's\n // record, not a caller-supplied \"before\" that could be fabricated.\n const base = task.pending_artefact;\n if (base === undefined) return { error: rpcError(E.PARAMS, \"No base artefact for override\") };\n let applied: unknown;\n try {\n applied = applyJsonPatch(base, p.diff as never);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.PATCH_FAILED, msg) };\n }\n const now = this.now();\n const id = this.ids.artefactId();\n const override: OverrideArtefact = {\n id,\n task_id: task.id,\n reviewer: p.from as ParticipantUri,\n based_on_artefact: base,\n diff: p.diff as never,\n result: applied,\n rationale: p.rationale as string,\n tags: (p.tags as string[]) ?? [],\n policy_refs: (p.policy_refs as string[]) ?? [],\n ts: now,\n logical_id: p.logical_id as string | undefined,\n instance_id: p.instance_id as string | undefined,\n intent_preserved: p.intent_preserved as boolean | undefined,\n };\n ws.overrides.set(id, override);\n task.review!.decisions.push({\n reviewer: p.from as ParticipantUri,\n kind: \"override\",\n ts: now,\n tags: override.tags,\n override_artefact_id: id,\n });\n task.output = applied;\n task.state = \"completed\";\n task.updated_at = now;\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: \"completed\", note: \"override applied\" });\n return { result: { state: \"completed\", override_artefact_id: id, applied } };\n }\n\n private opAbstainDeclare(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\", \"reason\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"review_requested\") {\n return { error: rpcError(E.NOT_REVIEWABLE, `Task not awaiting review: ${task.state}`) };\n }\n const notReviewer = this.requireReviewer(task, p.from);\n if (notReviewer) return notReviewer;\n const now = this.now();\n task.review!.decisions.push({\n reviewer: p.from as ParticipantUri,\n kind: \"abstain\",\n ts: now,\n comment: p.reason as string,\n abstain_category: (p.category as string) || \"other\",\n });\n task.state = \"abstained\";\n task.updated_at = now;\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: \"abstained\", note: p.reason as string });\n return { result: { state: \"abstained\" } };\n }\n\n private opEscalateRaise(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"original_task_id\", \"new_task\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const orig = ws.tasks.get(p.original_task_id as string);\n if (!orig) return { error: rpcError(E.PARAMS, \"Unknown original task\") };\n if (orig.state === \"completed\" || orig.state === \"cancelled\" || orig.state === \"superseded\") {\n return { error: rpcError(E.PARAMS, `Cannot escalate a terminal task: ${orig.state}`) };\n }\n const nt = p.new_task as Record<string, unknown>;\n const assignee = nt.assignee as string;\n if (!assignee || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"Escalation assignee not in workspace\") };\n }\n const now = this.now();\n const newId = this.ids.taskId();\n const newTask: Task = {\n id: newId,\n kind: (nt.kind as string) || orig.kind,\n state: \"created\",\n assignee,\n delegator: p.from as ParticipantUri,\n input: (nt.input as Record<string, unknown>) ?? {},\n created_at: now,\n updated_at: now,\n mode: orig.mode,\n supersedes: orig.id,\n history: [{ ts: now, from: p.from as ParticipantUri, state: \"created\", note: `escalated from ${orig.id}` }],\n paused: false,\n };\n ws.tasks.set(newId, newTask);\n orig.state = \"escalated\";\n orig.updated_at = now;\n orig.superseded_by = newId;\n orig.history.push({ ts: now, from: p.from as ParticipantUri, state: \"escalated\", note: `-> ${newId}` });\n return { result: { new_task_id: newId, escalated_from: orig.id } };\n }\n}\n\nfunction memberToDict(m: Member): Record<string, unknown> {\n const out: Record<string, unknown> = {\n uri: m.uri, type: m.type, role: m.role, joined: m.joined,\n };\n if (m.display_name) out.display_name = m.display_name;\n if (m.capabilities) out.capabilities = m.capabilities;\n if (m.scopes) out.scopes = m.scopes;\n if (m.keys.length) {\n out.jwks = { keys: m.keys.filter(k => !k.revoked_at && !k.valid_until).map(k => k.jwk) };\n out.key_history = m.keys;\n }\n if (m.paused) out.paused = true;\n if (m.oidc_sub) out.oidc_sub = m.oidc_sub;\n if (m.vc_holder) out.vc_holder = m.vc_holder;\n return out;\n}\n","/**\n * Default routing policy factory.\n *\n * Returns a partial CoordinatorOptions configured with the three\n * routing hooks (routingPolicy, reviewDepthPolicy, escalationPolicy)\n * that the playground and demo use out of the box. Operators can\n * override individual hooks by passing their own functions in\n * CoordinatorOptions.\n *\n * The defaults shipped with the Coordinator (in profiles/routing.ts)\n * implement the same logic; this factory exists so that the legacy\n * call site can keep using:\n *\n * new Coordinator({ ...makeDefaultPolicy(SENIOR_URI), ... })\n *\n * The seniorTarget argument is the URI auto-escalation routes to\n * when no other target is supplied.\n */\nimport type {\n EscalationPolicyFn,\n ReviewDepthPolicyFn,\n RoutingPolicyFn,\n CoordinatorOptions,\n} from \"./coordinator.js\";\n\nconst CRIT: Record<string, number> = { low: 0, medium: 1, high: 2, critical: 3 };\n\nexport function makeDefaultPolicy(seniorTarget: string): Pick<CoordinatorOptions,\n \"routingPolicy\" | \"reviewDepthPolicy\" | \"escalationPolicy\"> {\n\n const routingPolicy: RoutingPolicyFn = (task, candidates) => {\n const eligible = candidates; // delegate elig check to coordinator\n return {\n selected: eligible[0],\n rationale: {\n policy_id: \"default\",\n hints_used: Object.keys(task.routing_hints ?? {}),\n summary: \"default policy: first eligible candidate\",\n alternatives_considered: eligible.slice(1).map(c => ({\n candidate: c, reason_excluded: \"not first eligible\",\n })),\n },\n };\n };\n\n const reviewDepthPolicy: ReviewDepthPolicyFn = (_task, hints) => {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n if (r >= 3) return { depth: \"full\",\n rationale: { policy_id: \"default\", summary: \"criticality=critical: full review\" }};\n if (r === 2 && conf < 0.7) return { depth: \"full\",\n rationale: { policy_id: \"default\", summary: \"criticality=high and confidence<0.7: full review\" }};\n if (r === 0 && conf >= 0.95) return { depth: \"skip\",\n rationale: { policy_id: \"default\", summary: \"very low criticality + very high confidence: skip\" }};\n if (r <= 1 && conf >= 0.85) return { depth: \"spot_check\", sampling_probability: 0.10,\n rationale: { policy_id: \"default\", summary: \"low criticality + high confidence: 10% sample\" }};\n return { depth: \"spot_check\", sampling_probability: 0.25,\n rationale: { policy_id: \"default\", summary: \"default mid-confidence: 25% sample\" }};\n };\n\n const escalationPolicy: EscalationPolicyFn = (_task, hints) => {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n const escalate = (r >= 3) || (r >= 2 && conf < 0.6);\n return {\n escalate,\n to: escalate ? seniorTarget : undefined,\n triggered_rule: {\n rule_id: \"default-auto-esc\",\n summary: \"criticality=critical OR (criticality>=high AND confidence<0.6)\",\n hints_used: [\"criticality\", \"confidence\"],\n },\n };\n };\n\n return { routingPolicy, reviewDepthPolicy, escalationPolicy };\n}\n","/**\n * @brightbeamai/chap-coordinator/transports/wrap\n *\n * Inward integration helpers: turn an external tool/agent event into\n * a CHAP envelope landing in a workspace's audit log. Library\n * counterpart to the patterns described in\n * ``integrations/CHAP-with-MCP.md`` and ``integrations/CHAP-with-A2A.md``.\n *\n * The outward transports let external clients drive a CHAP workspace.\n * These helpers go the other direction: when work has already\n * happened outside CHAP, wrap it so the audit log carries a faithful,\n * citable record.\n *\n * Spec target: CHAP 0.2. MCP 2026-07-28. A2A 1.0.\n */\n\nimport { contentHash } from \"../canonical.js\";\nimport type { Coordinator } from \"../coordinator.js\";\n\nexport { contentHash } from \"../canonical.js\";\n\nexport interface WrapMcpToolCallOptions {\n /** Participant URI making the call. Must already be a workspace member. */\n caller: string;\n /** MCP tool name, e.g. ``\"github.create_issue\"``. */\n tool: string;\n /** Arguments passed to the MCP tool. */\n args: Record<string, unknown>;\n /** Return value from the MCP tool. */\n result: unknown;\n /** Optional MCP server identifier, e.g. \"github\". */\n server?: string;\n /** Override the default task kind ``\"mcp_call:<tool>\"``. */\n taskKind?: string;\n /** Optional routing hints attached to the CHAP task. */\n routingHints?: Record<string, unknown>;\n /** Optional confidence value attached to task.complete. */\n confidence?: number | string;\n}\n\nexport interface WrapResult {\n task_id: string;\n input_hash: string;\n output_hash: string;\n}\n\n/**\n * Wrap a completed MCP tool call as a CHAP task pair.\n *\n * Emits ``task.create`` + ``task.complete`` envelopes into the\n * workspace so the MCP call shows up as a first-class audit entry.\n * The result artefact is the MCP tool's return value, plus a\n * ``citations[]`` entry with the input/output hashes per\n * ``integrations/CHAP-with-MCP.md`` §2.\n */\nexport function wrapMcpToolCall(\n coord: Coordinator,\n workspace: string,\n options: WrapMcpToolCallOptions,\n): WrapResult {\n if (!workspace) throw new Error(\"workspace is required\");\n if (!options.caller) throw new Error(\"caller is required\");\n if (!options.tool) throw new Error(\"tool is required\");\n\n const inputHash = contentHash(options.args);\n const outputHash = contentHash(options.result);\n const kind = options.taskKind ?? `mcp_call:${options.tool}`;\n\n const citations = [{\n kind: \"mcp_tool_call\" as const,\n server: options.server ?? \"unknown\",\n tool: options.tool,\n input_hash: inputHash,\n output_hash: outputHash,\n }];\n\n const createParams: Record<string, unknown> = {\n workspace,\n from: options.caller,\n kind,\n assignee: options.caller,\n input: options.args,\n };\n if (options.routingHints) createParams.routing_hints = { ...options.routingHints };\n\n const createResp = coord.dispatch({\n jsonrpc: \"2.0\",\n id: `wrap-${options.tool}-create`,\n method: \"task.create\",\n params: createParams,\n });\n if (createResp.error) throw new Error(`task.create failed: ${JSON.stringify(createResp.error)}`);\n const taskId = (createResp.result as { task_id: string }).task_id;\n\n coord.dispatch({\n jsonrpc: \"2.0\",\n id: `wrap-${options.tool}-update`,\n method: \"task.update\",\n params: { workspace, from: options.caller, task_id: taskId, state: \"in_progress\" },\n });\n\n const completeParams: Record<string, unknown> = {\n workspace,\n from: options.caller,\n task_id: taskId,\n output: { result: options.result, citations },\n };\n if (options.confidence !== undefined) completeParams.confidence = options.confidence;\n\n const completeResp = coord.dispatch({\n jsonrpc: \"2.0\",\n id: `wrap-${options.tool}-complete`,\n method: \"task.complete\",\n params: completeParams,\n });\n if (completeResp.error) throw new Error(`task.complete failed: ${JSON.stringify(completeResp.error)}`);\n\n return { task_id: taskId, input_hash: inputHash, output_hash: outputHash };\n}\n\n// ============================================================\n\nexport interface WrapA2aExchangeOptions {\n /** URI of the local bridge participant. Must be a workspace member. */\n bridgeUri: string;\n /** Identifier of the remote A2A agent. Recorded in the citation. */\n remoteAgent: string;\n /** The A2A message body sent outbound. */\n sent: Record<string, unknown>;\n /** The A2A message body received in response. */\n received: Record<string, unknown>;\n /** CHAP task kind. Default ``\"a2a_exchange\"``. */\n taskKind?: string;\n /** Optional routing hints attached to the task. */\n routingHints?: Record<string, unknown>;\n /** Optional confidence value attached to task.complete. */\n confidence?: number | string;\n}\n\nexport interface WrapA2aResult {\n task_id: string;\n sent_hash: string;\n received_hash: string;\n}\n\n/**\n * Wrap a completed A2A message exchange as a CHAP task pair.\n *\n * Implements the bridge-participant pattern from\n * ``integrations/CHAP-with-A2A.md`` §3 as a library helper.\n */\nexport function wrapA2aMessageExchange(\n coord: Coordinator,\n workspace: string,\n options: WrapA2aExchangeOptions,\n): WrapA2aResult {\n if (!workspace) throw new Error(\"workspace is required\");\n if (!options.bridgeUri) throw new Error(\"bridgeUri is required\");\n if (!options.remoteAgent) throw new Error(\"remoteAgent is required\");\n\n const sentHash = contentHash(options.sent);\n const receivedHash = contentHash(options.received);\n const kind = options.taskKind ?? \"a2a_exchange\";\n\n const citation = {\n kind: \"a2a_exchange\" as const,\n remote_agent: options.remoteAgent,\n sent_hash: sentHash,\n received_hash: receivedHash,\n };\n\n const createParams: Record<string, unknown> = {\n workspace,\n from: options.bridgeUri,\n kind,\n assignee: options.bridgeUri,\n input: { remote_agent: options.remoteAgent, sent: options.sent },\n };\n if (options.routingHints) createParams.routing_hints = { ...options.routingHints };\n\n const createResp = coord.dispatch({\n jsonrpc: \"2.0\", id: \"wrap-a2a-create\",\n method: \"task.create\", params: createParams,\n });\n if (createResp.error) throw new Error(`task.create failed: ${JSON.stringify(createResp.error)}`);\n const taskId = (createResp.result as { task_id: string }).task_id;\n\n coord.dispatch({\n jsonrpc: \"2.0\", id: \"wrap-a2a-update\",\n method: \"task.update\",\n params: { workspace, from: options.bridgeUri,\n task_id: taskId, state: \"in_progress\" },\n });\n\n const completeParams: Record<string, unknown> = {\n workspace, from: options.bridgeUri, task_id: taskId,\n output: { received: options.received, citations: [citation] },\n };\n if (options.confidence !== undefined) completeParams.confidence = options.confidence;\n\n const completeResp = coord.dispatch({\n jsonrpc: \"2.0\", id: \"wrap-a2a-complete\",\n method: \"task.complete\", params: completeParams,\n });\n if (completeResp.error) throw new Error(`task.complete failed: ${JSON.stringify(completeResp.error)}`);\n\n return { task_id: taskId, sent_hash: sentHash, received_hash: receivedHash };\n}\n"],"mappings":";AAkBA,SAAS,kBAAkB;AAEpB,IAAM,YAAY,YAAY,IAAI,OAAO,EAAE;AAElD,IAAM,oBACJ;AAEF,IAAM,qBACJ;AAGF,SAAS,gBAAgB,GAAmB;AAE1C,SAAO,KAAK,UAAU,CAAC;AACzB;AAEA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A,IAAe,QAAQ;AAAA,EACjC,CAAC;AACD,MAAI,WAAW,MAAO,OAAM,IAAI,MAAM,uBAAuB,KAAK,UAAU,WAAW,KAAK,CAAC,EAAE;AAC/F,QAAM,SAAU,WAAW,OAA+B;AAE1D,QAAM,SAAS;AAAA,IACb,SAAS;AAAA,IAAO,IAAI;AAAA,IACpB,QAAQ;AAAA,IACR,QAAQ;AAAA,MAAE;AAAA,MAAW,MAAM,QAAQ;AAAA,MACzB,SAAS;AAAA,MAAQ,OAAO;AAAA,IAAc;AAAA,EAClD,CAAC;AAED,QAAM,iBAA0C;AAAA,IAC9C;AAAA,IAAW,MAAM,QAAQ;AAAA,IAAW,SAAS;AAAA,IAC7C,QAAQ,EAAE,UAAU,QAAQ,UAAU,WAAW,CAAC,QAAQ,EAAE;AAAA,EAC9D;AACA,MAAI,QAAQ,eAAe,OAAW,gBAAe,aAAa,QAAQ;AAE1E,QAAM,eAAe,MAAM,SAAS;AAAA,IAClC,SAAS;AAAA,IAAO,IAAI;AAAA,IACpB,QAAQ;AAAA,IAAiB,QAAQ;AAAA,EACnC,CAAC;AACD,MAAI,aAAa,MAAO,OAAM,IAAI,MAAM,yBAAyB,KAAK,UAAU,aAAa,KAAK,CAAC,EAAE;AAErG,SAAO,EAAE,SAAS,QAAQ,WAAW,UAAU,eAAe,aAAa;AAC7E;","names":["createHash","wsId","CRIT"]}
1
+ {"version":3,"sources":["../src/canonical.ts","../src/crypto.ts","../src/ids.ts","../src/jsonrpc.ts","../src/patch.ts","../src/storage/store.ts","../src/api.ts","../src/types.ts","../src/profiles/audit_scitt.ts","../src/profiles/control.ts","../src/profiles/deliberation.ts","../src/profiles/handoff.ts","../src/profiles/routing.ts","../src/profiles/security_signed.ts","../src/profiles/whisper.ts","../src/coordinator.ts","../src/policy.ts","../src/transports/wrap.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/canonical\n *\n * Deterministic JSON canonicalisation for CHAP. CHAP signs and hashes the\n * canonicalisation of envelopes.\n *\n * Follows RFC 8785 (JCS) for objects, arrays, strings, booleans, and null,\n * with one deliberate restriction on numbers. RFC 8785 mandates the\n * ECMAScript number-to-string algorithm, which is hard to reproduce\n * byte-identically across languages; a subtle mismatch would make a chain\n * written by one implementation fail verification against another. To make\n * cross-implementation agreement provable rather than approximate, a CHAP\n * canonical number MUST be an integer within the safe-integer range\n * (abs value <= Number.MAX_SAFE_INTEGER). Non-integers and larger\n * magnitudes are rejected: represent them as strings. The Python reference\n * enforces the identical rule.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport const ZERO_HASH = \"sha256:\" + \"0\".repeat(64);\n\nconst NON_INTEGER_ERROR =\n 'CHAP canonical numbers must be integers; represent decimals as strings ' +\n '(e.g. \"8.2\") so the hash is deterministic across implementations.';\nconst NUMBER_RANGE_ERROR =\n \"CHAP canonical integers must be within the safe-integer range \" +\n \"(abs value <= Number.MAX_SAFE_INTEGER); represent larger numbers as strings.\";\n\nfunction canonicalString(s: string): string {\n // JSON string escaping; \\uXXXX for control chars\n return JSON.stringify(s);\n}\n\nfunction canonicalNumber(n: number): string {\n if (!Number.isFinite(n)) {\n throw new Error(\n \"Non-finite numbers are not permitted in a CHAP canonical value\",\n );\n }\n if (!Number.isInteger(n)) {\n throw new Error(NON_INTEGER_ERROR);\n }\n if (Math.abs(n) > Number.MAX_SAFE_INTEGER) {\n throw new Error(NUMBER_RANGE_ERROR);\n }\n // A safe integer's toString() is always plain decimal digits (no\n // exponent), byte-identical to Python's str(int(...)).\n return n.toString();\n}\n\nfunction canon(value: unknown): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return canonicalString(value);\n if (typeof value === \"number\") return canonicalNumber(value);\n if (Array.isArray(value)) {\n return \"[\" + value.map(canon).join(\",\") + \"]\";\n }\n if (typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const key of keys) {\n parts.push(canonicalString(key) + \":\" + canon(obj[key]));\n }\n return \"{\" + parts.join(\",\") + \"}\";\n }\n throw new TypeError(`Cannot canonicalise value of type ${typeof value}`);\n}\n\n/** Return the JCS canonical UTF-8 bytes for a JSON-compatible value. */\nexport function canonicalize(value: unknown): Buffer {\n return Buffer.from(canon(value), \"utf-8\");\n}\n\n/** Return ``sha256:<64-hex>`` digest of bytes. */\nexport function sha256Hex(data: Buffer | string): string {\n const h = createHash(\"sha256\");\n h.update(typeof data === \"string\" ? Buffer.from(data, \"utf-8\") : data);\n return \"sha256:\" + h.digest(\"hex\");\n}\n\n/** Convenience: content hash for an artefact payload via JCS. */\nexport function contentHash(content: unknown): string {\n return sha256Hex(canonicalize(content));\n}\n","/**\n * @brightbeamai/chap-coordinator/crypto\n *\n * Ed25519 signing/verification for the security-signed/1.0 profile.\n *\n * Uses Node's built-in crypto (no external dependencies). Keys are\n * represented as RFC 7517 JWKs with kty=OKP, crv=Ed25519.\n */\n\nimport {\n createPrivateKey,\n createPublicKey,\n KeyObject,\n sign as nodeSign,\n verify as nodeVerify,\n randomBytes,\n createHash,\n} from \"node:crypto\";\n\nconst ED25519_OID = Buffer.from(\"302a300506032b6570032100\", \"hex\");\n\nfunction b64urlNoPad(buf: Buffer): string {\n return buf.toString(\"base64\").replace(/=+$/, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\nfunction b64urlDecode(s: string): Buffer {\n const pad = \"=\".repeat((4 - (s.length % 4)) % 4);\n return Buffer.from(s.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad, \"base64\");\n}\n\nexport interface Jwk {\n kty: \"OKP\";\n crv: \"Ed25519\";\n kid: string;\n x: string;\n d?: string;\n use?: string;\n alg?: string;\n}\n\n/**\n * Deterministically derive a 32-byte Ed25519 seed from a participant URI.\n * Demo / test only. production deployments supply real keys.\n */\nexport function deriveSeed(uri: string): Buffer {\n return createHash(\"sha256\").update(\"chap:\" + uri).digest();\n}\n\n/**\n * Build a Node KeyObject (private key) from a raw 32-byte Ed25519 seed.\n */\nexport function privateKeyFromSeed(seed: Buffer): KeyObject {\n if (seed.length !== 32) {\n throw new Error(\"Ed25519 seed must be 32 bytes\");\n }\n // PKCS#8 DER for Ed25519: SEQ(SEQ(OID), OCTET(OCTET(seed)))\n const pkcs8 = Buffer.concat([\n Buffer.from(\"302e020100300506032b657004220420\", \"hex\"),\n seed,\n ]);\n return createPrivateKey({ key: pkcs8, format: \"der\", type: \"pkcs8\" });\n}\n\n/** Public key bytes (32 bytes) from a private key. */\nexport function publicKeyBytes(privateKey: KeyObject): Buffer {\n const pub = createPublicKey(privateKey);\n const der = pub.export({ format: \"der\", type: \"spki\" }) as Buffer;\n // SPKI for Ed25519 is the OID prefix + 32-byte raw public key\n return der.subarray(der.length - 32);\n}\n\n/** Public KeyObject from raw 32-byte Ed25519 public key. */\nexport function publicKeyFromRaw(raw: Buffer): KeyObject {\n if (raw.length !== 32) {\n throw new Error(\"Ed25519 public key must be 32 bytes\");\n }\n const der = Buffer.concat([ED25519_OID, raw]);\n return createPublicKey({ key: der, format: \"der\", type: \"spki\" });\n}\n\n/** Render a JWK from a Node private KeyObject. */\nexport function jwkFromPrivateKey(uri: string, key: KeyObject): Jwk {\n const pub = publicKeyBytes(key);\n return {\n kty: \"OKP\",\n crv: \"Ed25519\",\n kid: createHash(\"sha256\").update(uri).digest(\"hex\").slice(0, 16),\n use: \"sig\",\n alg: \"EdDSA\",\n x: b64urlNoPad(pub),\n };\n}\n\n/** Sign canonical bytes; return ``ed25519:<kid>:<base64>``. */\nexport function signEnvelope(canonical: Buffer, privateKey: KeyObject, kid: string): string {\n const sig = nodeSign(null, canonical, privateKey);\n return `ed25519:${kid}:${sig.toString(\"base64\")}`;\n}\n\n/** Verify a CHAP sig string against canonical bytes and a public key. */\nexport function verifyEnvelope(canonical: Buffer, sigTag: string, publicKey: KeyObject): boolean {\n if (!sigTag.startsWith(\"ed25519:\")) return false;\n const parts = sigTag.split(\":\");\n if (parts.length < 2) return false;\n const sigB64 = parts[parts.length - 1];\n try {\n const sig = Buffer.from(sigB64, \"base64\");\n return nodeVerify(null, canonical, publicKey, sig);\n } catch {\n return false;\n }\n}\n\n/** Parse a JWK x (base64url) into a Node public KeyObject. */\nexport function publicKeyFromJwk(jwk: Jwk): KeyObject {\n return publicKeyFromRaw(b64urlDecode(jwk.x));\n}\n\n/** Demo helper: build a deterministic keypair + JWK for a URI. */\nexport function deriveKeypair(uri: string): { privateKey: KeyObject; jwk: Jwk } {\n const seed = deriveSeed(uri);\n const privateKey = privateKeyFromSeed(seed);\n return { privateKey, jwk: jwkFromPrivateKey(uri, privateKey) };\n}\n\nexport { b64urlNoPad, b64urlDecode };\n","/**\n * @brightbeamai/chap-coordinator/ids\n *\n * ULID-format identifier generation. Supports a deterministic mode\n * for tests/demos so byte-for-byte replay works.\n */\n\nconst ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\"; // Crockford\n\nfunction encode(value: bigint, length: number): string {\n let out = \"\";\n for (let i = 0; i < length; i++) {\n const idx = Number(value & 31n);\n out = ALPHABET[idx] + out;\n value >>= 5n;\n }\n return out;\n}\n\nexport class IdFactory {\n private counter: bigint;\n private clockMs: number;\n\n constructor(\n public readonly deterministic: boolean = false,\n seed: bigint = 0n,\n startMs: number = 1_700_000_000_000,\n ) {\n this.counter = seed;\n this.clockMs = startMs;\n }\n\n nowMs(): number {\n if (this.deterministic) {\n this.clockMs += 1;\n return this.clockMs;\n }\n return Date.now();\n }\n\n private randomness(): bigint {\n if (this.deterministic) {\n this.counter += 1n;\n return (this.counter * 0x9E3779B97F4A7C15n) & ((1n << 80n) - 1n);\n }\n // 80 bits of randomness. `globalThis.crypto` is standard from Node 19\n // and present in every other supported runtime, so there is no fallback\n // path: the previous one called `require`, which does not exist in an\n // ES module and so threw on any runtime without the global.\n const buf = new Uint8Array(10);\n crypto.getRandomValues(buf);\n let n = 0n;\n for (const b of buf) n = (n << 8n) | BigInt(b);\n return n;\n }\n\n ulid(): string {\n const ts = BigInt(this.nowMs()) & ((1n << 48n) - 1n);\n const rand = this.randomness();\n return encode(ts, 10) + encode(rand, 16);\n }\n\n envelopeId(): string { return this.ulid(); }\n taskId(): string { return \"tsk_\" + this.ulid(); }\n artefactId(): string { return \"art_\" + this.ulid(); }\n logicalId(): string { return \"lgl_\" + this.ulid(); }\n workspaceId(): string { return \"wsp_\" + this.ulid(); }\n deliberationId(): string { return \"dlb_\" + this.ulid(); }\n handoffId(): string { return \"hnd_\" + this.ulid(); }\n snapshotId(): string { return \"snp_\" + this.ulid(); }\n}\n","/**\n * @brightbeamai/chap-coordinator/jsonrpc\n *\n * Error codes (JSON-RPC standard + CHAP private range) and helpers.\n *\n * Error code allocations come directly from each profile spec. See\n * profiles/*.md for the authoritative definitions.\n */\n\nexport const E = {\n // JSON-RPC 2.0 standard\n PARSE: -32700,\n REQUEST: -32600,\n METHOD: -32601,\n PARAMS: -32602,\n INTERNAL: -32603,\n\n // review/1.0 profile\n NOT_REVIEWABLE: -32010,\n NOT_AUTHORISED: -32011,\n PATCH_FAILED: -32012,\n REVIEW_LAPSED: -32013,\n REVIEW_ALREADY_OPEN: -32014,\n\n // whisper/1.0 profile (profiles/whisper.md S6)\n WHISPER_ALREADY_ANSWERED: -32020,\n WHISPER_LAPSED: -32021,\n WHISPER_OPTION_NOT_IN_SET: -32022,\n\n // deliberation/1.0 profile (profiles/deliberation.md S5)\n DELIB_VOTER_NOT_IN_LIST: -32030,\n DELIB_ALREADY_VOTED: -32031,\n DELIB_CLOSED_OR_LAPSED: -32032,\n DELIB_UNKNOWN_RULE: -32033,\n\n // modes/1.0 profile (profiles/modes.md S6)\n MODE_CEILING_EXCEEDED: -32040,\n MODE_STEP_UP_REQUIRED: -32041,\n\n // handoff/1.0 profile (profiles/handoff.md S6)\n HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER: -32050,\n HANDOFF_ALREADY_RESOLVED: -32051,\n HANDOFF_RECIPIENT_NOT_MEMBER: -32052,\n\n // control/1.0 profile (profiles/control.md S6)\n CONTROL_STEP_UP_REQUIRED: -32060,\n CONTROL_NOT_AUTHORISED: -32061,\n CONTROL_SNAPSHOT_NOT_FOUND: -32062,\n CONTROL_WORKSPACE_PAUSED: -32063,\n\n // security-signed/1.0 profile (profiles/security-signed.md S7)\n SIG_VERIFY_FAILED: -32070,\n SIG_KEY_NOT_FOUND: -32071,\n SIG_KEY_REVOKED: -32072,\n SIG_ROTATION_KEY_MISMATCH: -32073,\n SIG_ARTEFACT_DIGEST_MISMATCH: -32074,\n\n // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)\n SCITT_UNREACHABLE: -32080,\n SCITT_STATEMENT_REJECTED: -32081,\n SCITT_RECEIPT_INVALID: -32082,\n\n // identity-oidc/1.0 profile (profiles/identity-oidc.md S8)\n OIDC_STEP_UP_REQUIRED: -32402,\n OIDC_TOKEN_INVALID: -32403,\n OIDC_CNF_MISMATCH: -32404,\n OIDC_SCOPE_MISSING: -32405,\n\n // identity-vc/1.0 profile (profiles/identity-vc.md S8)\n VC_VP_INVALID: -32410,\n VC_HOLDER_BINDING_INVALID: -32411,\n VC_CREDENTIAL_REVOKED: -32412,\n VC_SCHEMA_UNKNOWN: -32413,\n\n // routing/1.0 profile (profiles/routing.md S3-S5)\n ROUTING_NO_ELIGIBLE_ASSIGNEE: -32510,\n ROUTING_POLICY_VIOLATION: -32511,\n ROUTING_AUTO_ESCALATION_TRIGGERED: -32512,\n ROUTING_CANDIDATES_EMPTY: -32513,\n ROUTING_DEPTH_NOT_APPLICABLE: -32514,\n ROUTING_POLICY_UNREACHABLE: -32515,\n ROUTING_ESC_TARGET_UNAVAILABLE: -32516,\n} as const;\n\nexport function rpcError(code: number, message: string, data?: unknown) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\nexport function isValidEnvelope(env: unknown): boolean {\n if (typeof env !== \"object\" || env === null) return false;\n const e = env as Record<string, unknown>;\n return e.jsonrpc === \"2.0\";\n}\n","/**\n * @brightbeamai/chap-coordinator/patch\n *\n * RFC 6902 JSON Patch implementation, plus a small diff computer that\n * produces a patch from two values. Used by the Coordinator for\n * `decide.override` apply and by the playground UI (in the browser) to\n * compute the patch from a textarea edit.\n *\n * Implements all six RFC 6902 operations (add, remove, replace, move,\n * copy, test) with semantics identical to the Python reference. Path\n * segments that enable prototype pollution in a JavaScript runtime\n * (`__proto__`, `constructor`, `prototype`) are rejected, so the two\n * references accept and reject exactly the same patches.\n */\n\nimport type { JsonPatchOp } from \"./types.js\";\n\nexport class PatchError extends Error {}\n\n// Rejected in every JSON Pointer segment: these enable prototype pollution.\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n// An array index is an RFC 6901 array index: \"0\" or a positive integer with no\n// leading zero. A shared strict rule keeps the two references in step -- JS\n// Number() and Python int() otherwise accept disjoint token sets (e.g. \"1e1\",\n// \"0x0a\", \"3.0\", \"\", \"1_0\"), which would apply the same patch differently.\nconst ARRAY_INDEX_RE = /^(0|[1-9][0-9]*)$/;\n\nfunction arrayIndex(seg: string): number {\n if (!ARRAY_INDEX_RE.test(seg)) throw new PatchError(`Array index expected at ${JSON.stringify(seg)}`);\n return Number(seg);\n}\n\nfunction unescape(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction splitPath(path: string): string[] {\n if (path === \"\") return [];\n if (!path.startsWith(\"/\")) {\n throw new PatchError(`JSON Pointer must start with '/': ${JSON.stringify(path)}`);\n }\n const segments = path.slice(1).split(\"/\").map(unescape);\n for (const seg of segments) {\n if (DANGEROUS_KEYS.has(seg)) {\n throw new PatchError(`Refusing unsafe path segment ${JSON.stringify(seg)}`);\n }\n }\n return segments;\n}\n\n/** Navigate to the parent of the target; return [parent, lastKey]. */\nfunction navigate(doc: any, parts: string[]): [any, string | number] {\n if (parts.length === 0) {\n throw new PatchError(\"Cannot operate on root with this helper.\");\n }\n let parent = doc;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (Array.isArray(parent)) {\n const idx = arrayIndex(part);\n if (idx >= parent.length) {\n throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[idx];\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, part)) {\n throw new PatchError(`Path not found: /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[part];\n } else {\n throw new PatchError(`Cannot traverse into ${typeof parent} at ${JSON.stringify(part)}`);\n }\n }\n const last = parts[parts.length - 1];\n if (Array.isArray(parent)) {\n if (last === \"-\") return [parent, \"-\"];\n return [parent, arrayIndex(last)];\n }\n return [parent, last];\n}\n\nfunction getAt(doc: any, path: string): any {\n const parts = splitPath(path);\n if (parts.length === 0) return doc;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") throw new PatchError(\"Cannot read '-' position.\");\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) throw new PatchError(`Index out of range: ${path}`);\n return parent[idx];\n }\n if (\n parent === null ||\n typeof parent !== \"object\" ||\n !Object.prototype.hasOwnProperty.call(parent, key)\n ) {\n throw new PatchError(`Path not found: ${path}`);\n }\n return parent[key as string];\n}\n\nfunction clone<T>(v: T): T {\n return v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T);\n}\n\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;\n return true;\n }\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (!deepEqual(a[k], b[k])) return false;\n }\n return true;\n}\n\nfunction applyOne(doc: any, op: JsonPatchOp): any {\n const kind = op.op;\n const path = op.path ?? \"\";\n\n if (kind === \"add\") {\n if (!(\"value\" in op)) throw new PatchError(\"'add' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value; // replace whole document\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") {\n parent.push(op.value);\n } else {\n const idx = key as number;\n if (idx < 0 || idx > parent.length) {\n throw new PatchError(`Index out of range for add: ${path}`);\n }\n parent.splice(idx, 0, op.value);\n }\n } else if (parent !== null && typeof parent === \"object\") {\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot add into ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"replace\") {\n if (!(\"value\" in op)) throw new PatchError(\"'replace' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[idx] = op.value;\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot replace in ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"remove\") {\n const parts = splitPath(path);\n if (parts.length === 0) throw new PatchError(\"Cannot remove root.\");\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range for remove: ${path}`);\n }\n parent.splice(idx, 1);\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for remove: ${path}`);\n }\n delete parent[key as string];\n } else {\n throw new PatchError(`Cannot remove from ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"copy\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'copy' requires 'from'\");\n const value = clone(getAt(doc, src));\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"move\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'move' requires 'from'\");\n // RFC 6902 4.4: 'from' MUST NOT be a proper prefix of 'path'.\n if (path.startsWith(src + \"/\")) {\n throw new PatchError(\"'move' cannot move a location into its own child.\");\n }\n const value = clone(getAt(doc, src));\n doc = applyOne(doc, { op: \"remove\", path: src });\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"test\") {\n if (!(\"value\" in op)) throw new PatchError(\"'test' requires 'value'\");\n const actual = getAt(doc, path);\n if (!deepEqual(actual, op.value)) throw new PatchError(`'test' failed at ${path}`);\n return doc;\n }\n\n throw new PatchError(`Unsupported op: ${JSON.stringify(kind)}`);\n}\n\nconst MAX_PATCH_OPS = 1000;\nconst MAX_DOCUMENT_NODES = 100_000;\n\nfunction nodeCount(value: unknown): number {\n if (Array.isArray(value)) {\n let n = 1;\n for (const v of value) n += nodeCount(v);\n return n;\n }\n if (value !== null && typeof value === \"object\") {\n let n = 1;\n for (const v of Object.values(value as Record<string, unknown>)) n += nodeCount(v);\n return n;\n }\n return 1;\n}\n\nexport function applyJsonPatch(doc: unknown, ops: JsonPatchOp[]): unknown {\n if (ops.length > MAX_PATCH_OPS) {\n throw new PatchError(`Patch has too many operations (${ops.length} > ${MAX_PATCH_OPS})`);\n }\n let out: any = JSON.parse(JSON.stringify(doc));\n for (const op of ops) {\n out = applyOne(out, op);\n if (nodeCount(out) > MAX_DOCUMENT_NODES) {\n throw new PatchError(`Patched document exceeds the node limit (${MAX_DOCUMENT_NODES})`);\n }\n }\n return out;\n}\n\n// ============================================================\n// diff: produce a patch that transforms `from` into `to`\n// ============================================================\n\n/**\n * Compute an RFC 6902 patch that, when applied to `from`, produces\n * `to`. Walks objects key-by-key; arrays use a shallow whole-array\n * replace if any element differs. Sufficient for the playground's\n * draft-edit use case where drafts are small JSON objects.\n */\nexport function diffJsonPatch(from: unknown, to: unknown, basePath = \"\"): JsonPatchOp[] {\n const ops: JsonPatchOp[] = [];\n\n if (typeof from !== typeof to || Array.isArray(from) !== Array.isArray(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n return ops;\n }\n\n if (from === null || to === null || typeof from !== \"object\") {\n if (from !== to) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n if (Array.isArray(from) && Array.isArray(to)) {\n if (JSON.stringify(from) !== JSON.stringify(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n const fromObj = from as Record<string, unknown>;\n const toObj = to as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(fromObj), ...Object.keys(toObj)]);\n\n for (const key of allKeys) {\n const escaped = key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n const path = `${basePath}/${escaped}`;\n if (!(key in fromObj)) {\n ops.push({ op: \"add\", path, value: toObj[key] });\n } else if (!(key in toObj)) {\n ops.push({ op: \"remove\", path });\n } else {\n ops.push(...diffJsonPatch(fromObj[key], toObj[key], path));\n }\n }\n\n return ops;\n}\n","/**\n * Pluggable persistence for the Coordinator.\n *\n * A Store persists workspace state between process restarts. Coordinators\n * call `store.save(workspaceId, snapshot)` after every mutation that\n * appends to the audit chain, and `store.load()` on startup to restore.\n *\n * Two implementations ship in-tree:\n * - MemoryStore (default, no persistence; existing behaviour)\n * - SqliteStore (real SQLite via better-sqlite3, opt-in)\n *\n * Third-party stores (Postgres, Redis, etc.) implement this interface.\n *\n * Concurrency model\n * -----------------\n *\n * A Coordinator is a **single-writer** component: dispatch is serial, workspace\n * state is held in memory, and each chain link is computed from the head the\n * instance holds. This interface is a persistence mechanism, not a\n * concurrency-control one. `save` is an unconditional write and no\n * implementation rejects a stale record.\n *\n * Running two or more Coordinator instances against one shared store is\n * therefore not supported. A stale instance's write replaces a newer one\n * wholesale: entries written by the other instance are lost, the chain is\n * re-linked from the surviving head, and `audit.verify_chain` still reports\n * `ok`, because the surviving chain is internally consistent. The loss is\n * silent and CHAP's own verification will not reveal it.\n *\n * If you need more than one instance, serialise writes above the Coordinator by\n * partitioning workspaces so no workspace is ever written by two, or by holding\n * an external lock. See SPECIFICATION.md section 10.3.\n *\n * Stores hold per-workspace JSON snapshots, not a decomposed relational\n * model. The Coordinator's snapshot/restore methods produce JSON-safe\n * payloads; this is fast for workspaces in the low-thousands of audit\n * entries and trades query flexibility for simplicity. Production\n * deployments needing rich query semantics should project the audit log\n * into their own analytics store via the `onAudit` listener.\n */\n\nexport interface WorkspaceRecord {\n /** Workspace identifier. */\n id: string;\n /** JSON-serialisable payload produced by `Coordinator.snapshot()`. */\n data: unknown;\n /**\n * Incremented on each save. Recorded for diagnostics and for stores that\n * want it; it is NOT enforced. Nothing here performs a compare-and-swap,\n * so this field does not give you optimistic concurrency. See the\n * concurrency model in this module's header.\n */\n version: number;\n /** Wall-clock timestamp of the last write, ISO-8601. */\n updated_at: string;\n}\n\nexport interface Store {\n /** Load all workspace records into memory. Called once on coordinator start. */\n load(): Promise<WorkspaceRecord[]> | WorkspaceRecord[];\n\n /** Persist one workspace record. Called after every mutation. */\n save(record: WorkspaceRecord): Promise<void> | void;\n\n /** Remove one workspace. Used by `workspace.delete` semantics (not in v0.2). */\n delete(id: string): Promise<void> | void;\n\n /** Release resources. Idempotent. */\n close?(): Promise<void> | void;\n}\n\n/**\n * In-memory store. Default behaviour: no persistence, fast tests.\n * State lives in a Map; closing it discards everything.\n */\nexport class MemoryStore implements Store {\n private records = new Map<string, WorkspaceRecord>();\n\n load(): WorkspaceRecord[] {\n return Array.from(this.records.values());\n }\n\n save(record: WorkspaceRecord): void {\n this.records.set(record.id, record);\n }\n\n delete(id: string): void {\n this.records.delete(id);\n }\n\n close(): void {\n this.records.clear();\n }\n}\n","/**\n * Typed method facade for the Coordinator.\n *\n * Replaces the verbose dispatch pattern:\n *\n * const env = await coord.dispatch({\n * jsonrpc: \"2.0\", id: \"x\",\n * method: \"task.create\",\n * params: { workspace, from, kind, input }\n * });\n * const taskId = env.result.task_id;\n *\n * with namespace-grouped calls that autocomplete and type-check:\n *\n * const { task_id } = coord.api.task.create({ workspace, from, kind, input });\n *\n * Every method on the facade calls `dispatch(envelope)` internally with\n * an auto-generated envelope id, so the audit chain semantics, profile\n * gates, and signature checks all run identically.\n *\n * On dispatch error, the facade throws a `CoordinatorError` carrying the\n * JSON-RPC error code and message. Callers expecting `error` objects on\n * the wire can still use `dispatch()` directly.\n */\n\nimport type { Coordinator } from \"./coordinator.js\";\nimport type { Envelope } from \"./types.js\";\nimport type {\n MethodName, MethodParams, MethodResult,\n} from \"./methods.js\";\n\nexport class CoordinatorError extends Error {\n readonly code: number;\n readonly data?: unknown;\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.name = \"CoordinatorError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/**\n * Single-call helper. Type-safe wrapper around `coord.dispatch()`.\n * Throws CoordinatorError if dispatch returns an error response.\n */\nexport function call<M extends MethodName>(\n coord: Coordinator,\n method: M,\n params: MethodParams<M>,\n): MethodResult<M> {\n const envelope: Envelope = {\n jsonrpc: \"2.0\",\n id: coord.ids.envelopeId(),\n method,\n params: params as unknown as Record<string, unknown>,\n };\n const out = coord.dispatch(envelope);\n if (out.error) {\n throw new CoordinatorError(out.error.code, out.error.message, out.error.data);\n }\n return out.result as MethodResult<M>;\n}\n\n// ============================================================\n// Namespace-grouped facades\n// ============================================================\n//\n// Each namespace facade is a small object exposing one method per\n// CHAP verb. Implementations are one-liners that delegate to call().\n// The pattern is verbose but autocompletes well and type-checks\n// param shape and result shape from one declaration in methods.ts.\n\nexport function makeApi(coord: Coordinator) {\n const c = <M extends MethodName>(m: M, p: MethodParams<M>) => call(coord, m, p);\n\n return {\n workspace: {\n create: (p: MethodParams<\"workspace.create\">) => c(\"workspace.create\", p),\n describe: (p: MethodParams<\"workspace.describe\">) => c(\"workspace.describe\", p),\n set_profiles: (p: MethodParams<\"workspace.set_profiles\">) => c(\"workspace.set_profiles\", p),\n },\n participant: {\n join: (p: MethodParams<\"participant.join\">) => c(\"participant.join\", p),\n leave: (p: MethodParams<\"participant.leave\">) => c(\"participant.leave\", p),\n rotate_key: (p: MethodParams<\"participant.rotate_key\">) => c(\"participant.rotate_key\", p),\n revoke_key: (p: MethodParams<\"participant.revoke_key\">) => c(\"participant.revoke_key\", p),\n },\n task: {\n create: (p: MethodParams<\"task.create\">) => c(\"task.create\", p),\n update: (p: MethodParams<\"task.update\">) => c(\"task.update\", p),\n complete: (p: MethodParams<\"task.complete\">) => c(\"task.complete\", p),\n route: (p: MethodParams<\"task.route\">) => c(\"task.route\", p),\n },\n review: {\n request: (p: MethodParams<\"review.request\">) => c(\"review.request\", p),\n depth: (p: MethodParams<\"review.depth\">) => c(\"review.depth\", p),\n },\n decide: {\n approve: (p: MethodParams<\"decide.approve\">) => c(\"decide.approve\", p),\n reject: (p: MethodParams<\"decide.reject\">) => c(\"decide.reject\", p),\n override: (p: MethodParams<\"decide.override\">) => c(\"decide.override\", p),\n },\n abstain: {\n declare: (p: MethodParams<\"abstain.declare\">) => c(\"abstain.declare\", p),\n },\n escalate: {\n raise: (p: MethodParams<\"escalate.raise\">) => c(\"escalate.raise\", p),\n auto: (p: MethodParams<\"escalate.auto\">) => c(\"escalate.auto\", p),\n },\n whisper: {\n ask: (p: MethodParams<\"whisper.ask\">) => c(\"whisper.ask\", p),\n answer: (p: MethodParams<\"whisper.answer\">) => c(\"whisper.answer\", p),\n },\n deliberate: {\n open: (p: MethodParams<\"deliberate.open\">) => c(\"deliberate.open\", p),\n comment: (p: MethodParams<\"deliberate.comment\">) => c(\"deliberate.comment\", p),\n vote: (p: MethodParams<\"deliberate.vote\">) => c(\"deliberate.vote\", p),\n close: (p: MethodParams<\"deliberate.close\">) => c(\"deliberate.close\", p),\n },\n handoff: {\n propose: (p: MethodParams<\"handoff.propose\">) => c(\"handoff.propose\", p),\n accept: (p: MethodParams<\"handoff.accept\">) => c(\"handoff.accept\", p),\n decline: (p: MethodParams<\"handoff.decline\">) => c(\"handoff.decline\", p),\n },\n control: {\n pause: (p: MethodParams<\"control.pause\">) => c(\"control.pause\", p),\n resume: (p: MethodParams<\"control.resume\">) => c(\"control.resume\", p),\n cancel: (p: MethodParams<\"control.cancel\">) => c(\"control.cancel\", p),\n supersede: (p: MethodParams<\"control.supersede\">) => c(\"control.supersede\", p),\n snapshot: (p: MethodParams<\"control.snapshot\">) => c(\"control.snapshot\", p),\n rollback: (p: MethodParams<\"control.rollback\">) => c(\"control.rollback\", p),\n set_mode_ceiling: (p: MethodParams<\"control.set_mode_ceiling\">) => c(\"control.set_mode_ceiling\", p),\n },\n audit: {\n read: (p: MethodParams<\"audit.read\">) => c(\"audit.read\", p),\n submit_to_scitt: (p: MethodParams<\"audit.submit_to_scitt\">) => c(\"audit.submit_to_scitt\", p),\n verify_receipt: (p: MethodParams<\"audit.verify_receipt\">) => c(\"audit.verify_receipt\", p),\n verify_chain: (p: MethodParams<\"audit.verify_chain\">) => c(\"audit.verify_chain\", p),\n },\n };\n}\n\nexport type CoordinatorApi = ReturnType<typeof makeApi>;\n","/**\n * @brightbeamai/chap-coordinator. type vocabulary\n *\n * Wire-shape and in-memory types for the Coordinator. The schemas at\n * schemas/ are the normative wire types; these mirror them in\n * TypeScript for in-process use.\n */\n\nexport type ParticipantUri = string;\nexport type WorkspaceId = string;\nexport type TaskId = string;\nexport type ArtefactId = string;\n\nexport type ParticipantType = \"human\" | \"agent\" | \"service\" | \"group\" | \"workspace\";\n\nexport interface Envelope {\n jsonrpc: \"2.0\";\n id?: string | number;\n method?: string;\n params?: Record<string, unknown>;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n /** security-signed/1.0: top-level signature, signed over JCS of the\n * envelope with this field removed. Form: ``ed25519:<kid>:<b64>``. */\n sig?: string;\n}\n\nexport type Mode = \"shadow\" | \"trial\" | \"production\";\nexport type WorkspaceState = \"active\" | \"paused\" | \"closed\";\nexport type PauseScope = \"task\" | \"participant\" | \"workspace\";\n\nexport type TaskState =\n | \"created\"\n | \"in_progress\"\n | \"review_requested\"\n | \"completed\"\n | \"declined\"\n | \"abstained\"\n | \"escalated\"\n | \"superseded\"\n | \"paused\"\n | \"cancelled\";\n\n// ============================================================\n// Key records (security-signed/1.0)\n// ============================================================\n\nexport interface Jwk {\n kty: \"OKP\";\n crv: \"Ed25519\";\n kid: string;\n x: string;\n use?: string;\n alg?: string;\n}\n\n/** A participant's JWK plus the validity window. Lookup by\n * (participant, kid, ts) so historical envelopes verify across\n * rotation per security-signed/1.0 S3-S5. */\nexport interface KeyRecord {\n jwk: Jwk;\n kid: string;\n valid_from: string; // ISO timestamp; inclusive\n valid_until?: string; // ISO timestamp; exclusive; absent = unbounded\n revoked_at?: string;\n revoked_reason?: string;\n}\n\n// ============================================================\n// Participants\n// ============================================================\n\nexport interface Member {\n uri: ParticipantUri;\n type: ParticipantType;\n role: string;\n joined: string;\n display_name?: string;\n capabilities?: Record<string, unknown>;\n scopes?: string[];\n keys: KeyRecord[];\n paused: boolean; // control.pause scope=participant\n oidc_sub?: string;\n oidc_auth_time?: number; // unix seconds\n oidc_acr?: string;\n vc_holder?: string;\n}\n\n// ============================================================\n// Routing hints\n// ============================================================\n\nexport interface TaskRoutingHints {\n criticality?: \"low\" | \"medium\" | \"high\" | \"critical\";\n deadline?: string;\n max_cost_usd?: number;\n risk_tier?: string;\n [extra: string]: unknown;\n}\n\nexport interface ArtefactRoutingHints {\n confidence?: number | string;\n model_id?: string;\n cost_consumed_usd?: number;\n latency_ms?: number;\n [extra: string]: unknown;\n}\n\n// ============================================================\n// JSON Patch (RFC 6902)\n// ============================================================\n\nexport interface JsonPatchOp {\n op: \"add\" | \"replace\" | \"remove\" | \"copy\" | \"move\" | \"test\";\n path: string;\n value?: unknown;\n from?: string;\n}\n\n// ============================================================\n// Override artefact (review/1.0)\n// ============================================================\n\nexport interface OverrideArtefact {\n id: ArtefactId;\n task_id: TaskId;\n reviewer: ParticipantUri;\n based_on_artefact: unknown;\n diff: JsonPatchOp[];\n result: unknown;\n rationale: string;\n tags: string[];\n policy_refs: string[];\n ts: string;\n logical_id?: string;\n instance_id?: string;\n intent_preserved?: boolean;\n}\n\n// ============================================================\n// Route decision artefact (routing/1.0)\n// ============================================================\n\nexport interface RouteDecisionArtefact {\n id: ArtefactId;\n kind: \"route_decision\";\n decision_type: \"task.route\" | \"review.depth\" | \"escalate.auto\";\n outcome: unknown;\n produced_by: ParticipantUri;\n produced_at: string;\n task?: TaskId;\n policy_id?: string;\n hints_observed: Record<string, unknown>;\n rationale: string;\n // Auxiliary fields per decision_type:\n // task.route: alternatives_considered\n // review.depth: sampling_probability\n // escalate.auto: escalation_target\n [extra: string]: unknown;\n}\n\n// ============================================================\n// Snapshot artefact (control/1.0)\n// ============================================================\n\nexport interface SnapshotArtefact {\n id: ArtefactId;\n kind: \"snapshot\";\n ts: string;\n by: ParticipantUri;\n workspace: WorkspaceId;\n audit_seq: number;\n label?: string;\n include: string[];\n state: Record<string, unknown>;\n}\n\n// ============================================================\n// Whisper (whisper/1.0)\n// ============================================================\n\nexport interface WhisperPrompt {\n id: ArtefactId;\n task_id: TaskId;\n asker: ParticipantUri;\n askee: ParticipantUri[];\n question: string;\n options?: Array<{ id: string; label?: string }>;\n asked_at: string;\n deadline_ms: number;\n default_if_lapsed: unknown;\n urgency: \"low\" | \"medium\" | \"high\";\n state: \"pending\" | \"answered\" | \"lapsed\";\n answered_at?: string;\n answered_by?: ParticipantUri;\n answer_option?: string;\n answer_text?: string;\n comment?: string;\n default_applied?: unknown;\n}\n\n// ============================================================\n// Deliberation (deliberation/1.0)\n// ============================================================\n\nexport interface DeliberationVote {\n ts: string;\n voter: ParticipantUri;\n vote: \"yea\" | \"nay\" | \"abstain\";\n weight?: number;\n comment?: string;\n veto_invoked?: boolean;\n}\n\nexport interface Deliberation {\n id: string;\n task_id?: TaskId;\n opener: ParticipantUri;\n participants: ParticipantUri[];\n rule: string; // raw rule string\n question?: string;\n weights?: Record<ParticipantUri, number>;\n veto?: Record<ParticipantUri, boolean>;\n deadline?: string;\n state: \"open\" | \"closed\" | \"lapsed\";\n comments: { ts: string; from: ParticipantUri; text: string }[];\n votes: DeliberationVote[];\n outcome?: {\n outcome: \"approved\" | \"rejected\" | \"error\";\n rule: string;\n tally?: { yea: number; nay: number };\n vetoes?: ParticipantUri[];\n reason?: string;\n };\n opened_at: string;\n}\n\n// ============================================================\n// Handoff (handoff/1.0)\n// ============================================================\n\nexport interface HandoffTaskItem {\n task_id: TaskId;\n title?: string;\n status_summary?: string;\n next_action?: string;\n blockers?: string[];\n}\n\nexport interface Handoff {\n id: string;\n proposer: ParticipantUri;\n recipient: ParticipantUri; // single URI or \"group:...\"\n proposed_at: string;\n tasks: HandoffTaskItem[];\n summary?: string;\n context_links: string[];\n state: \"proposed\" | \"accepted\" | \"declined\";\n resolved_at?: string;\n accepted_by?: ParticipantUri;\n accepted_task_ids?: TaskId[];\n accept_comment?: string;\n decline_reason?: string;\n decline_suggested_target?: ParticipantUri;\n}\n\n// ============================================================\n// Review decision (review/1.0)\n// ============================================================\n\nexport interface ReviewDecision {\n reviewer: ParticipantUri;\n kind: \"approve\" | \"reject\" | \"override\" | \"abstain\";\n ts: string;\n comment?: string;\n tags?: string[];\n override_artefact_id?: ArtefactId;\n abstain_category?: string;\n}\n\n// ============================================================\n// Task\n// ============================================================\n\nexport interface Task {\n id: TaskId;\n kind: string;\n state: TaskState;\n assignee: ParticipantUri;\n delegator: ParticipantUri;\n input: Record<string, unknown>;\n output?: unknown;\n confidence?: number | string;\n deadline?: string;\n created_at: string;\n updated_at: string;\n mode: Mode;\n review_required?: boolean;\n routing_hints?: TaskRoutingHints;\n artefact_routing_hints?: ArtefactRoutingHints;\n review?: {\n requested_at: string;\n requested_to: ParticipantUri[];\n rule: string;\n deadline?: string;\n decisions: ReviewDecision[];\n };\n history: { ts: string; from: ParticipantUri; state: TaskState; note?: string }[];\n supersedes?: TaskId;\n superseded_by?: TaskId;\n parent?: TaskId;\n paused: boolean;\n /** Transient: holds the artefact passed to review.request so\n * decide.override can use it as the patch base. */\n pending_artefact?: unknown;\n}\n\n// ============================================================\n// Audit\n// ============================================================\n\nexport interface AuditEntry {\n seq: number;\n arrived: string;\n envelope: Envelope;\n prev_hash?: string;\n}\n\n// ============================================================\n// Workspace\n// ============================================================\n\nexport interface Workspace {\n id: WorkspaceId;\n created: string;\n state: WorkspaceState;\n profiles: string[];\n mode: Mode;\n mode_ceiling: Mode;\n routing_policy_uri?: string;\n step_up_window_sec: number;\n min_acr?: string;\n members: Map<ParticipantUri, Member>;\n tasks: Map<TaskId, Task>;\n overrides: Map<ArtefactId, OverrideArtefact>;\n whispers: Map<string, WhisperPrompt>;\n deliberations: Map<string, Deliberation>;\n handoffs: Map<string, Handoff>;\n snapshots: Map<ArtefactId, SnapshotArtefact>;\n route_decisions: Map<ArtefactId, RouteDecisionArtefact>;\n // task.create idempotency: caller-supplied key -> task_id.\n idempotency_keys: Record<string, TaskId>;\n audit: AuditEntry[];\n chain_head?: string;\n chain_enabled: boolean;\n}\n\n/**\n * Listener callback invoked synchronously when an envelope is appended\n * to the workspace audit log.\n */\nexport type AuditListener = (workspace: Workspace, entry: AuditEntry) => void;\n\n/** True iff mode `a` is <= ceiling. */\nexport function modeLE(a: Mode, ceiling: Mode): boolean {\n const order: Record<Mode, number> = { shadow: 0, trial: 1, production: 2 };\n return order[a] <= order[ceiling];\n}\n","/**\n * audit-scitt/1.0 profile (profiles/audit-scitt.md).\n *\n * Methods:\n * - audit.submit_to_scitt -> build COSE_Sign1-shaped statements, pass to submitter\n * - audit.verify_receipt -> delegate to deployment hook\n * - audit.verify_chain -> replay local prev_hash chain\n *\n * External SCITT integration is the deployment's job; the Coordinator\n * builds the statement shape and routes through CoordinatorOptions.scittSubmitter.\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { canonicalize, sha256Hex, ZERO_HASH } from \"../canonical.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { Envelope } from \"../types.js\";\n\nfunction buildStatement(workspaceId: string, envelope: Envelope, issuer: string): Record<string, unknown> {\n return {\n protected: {\n alg: -8, // Ed25519 per COSE\n iss: issuer,\n kid: \"scitt-issuer\",\n cwt_claims: { sub: workspaceId, iat: null },\n \"content-type\": \"application/chap+json;version=0.2\",\n },\n payload: canonicalize(envelope).toString(\"utf-8\"),\n signature: \"<deployment-supplied>\",\n };\n}\n\nexport function registerAuditScitt(coord: Coordinator): void {\n coord.handlers.set(\"audit.submit_to_scitt\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const range = (p.range as { from_seq?: number; to_seq?: number } | undefined) ?? {};\n const fromSeq = range.from_seq ?? 0;\n const toSeq = range.to_seq ?? ws.audit.length;\n const issuer = (p.issuer as string) ?? \"service:coordinator\";\n\n if (!coord.options.scittSubmitter) {\n const statements = ws.audit.slice(fromSeq, toSeq).map(e =>\n buildStatement(ws.id, e.envelope, issuer));\n return { result: {\n statements,\n note: \"No scittSubmitter configured; submit these out-of-band\",\n }};\n }\n const receipts: unknown[] = [];\n for (const entry of ws.audit.slice(fromSeq, toSeq)) {\n const statement = buildStatement(ws.id, entry.envelope, issuer);\n let receipt: Record<string, unknown> | null;\n try {\n receipt = coord.options.scittSubmitter(statement);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.SCITT_UNREACHABLE, `SCITT submission error: ${msg}`) };\n }\n if (receipt === null) {\n return { error: rpcError(E.SCITT_STATEMENT_REJECTED,\n `Statement rejected at seq ${entry.seq}`) };\n }\n receipts.push({ seq: entry.seq, receipt });\n }\n return { result: { receipts } };\n });\n\n coord.handlers.set(\"audit.verify_receipt\", (p) => {\n const receipt = p.receipt;\n if (typeof receipt !== \"object\" || receipt === null) {\n return { error: rpcError(E.PARAMS, \"receipt must be an object\") };\n }\n if (coord.options.verifyScittReceipt) {\n let ok: boolean;\n try { ok = !!coord.options.verifyScittReceipt(receipt as Record<string, unknown>); }\n catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.SCITT_RECEIPT_INVALID, `verify error: ${msg}`) };\n }\n if (!ok) return { error: rpcError(E.SCITT_RECEIPT_INVALID, \"Receipt did not verify\") };\n return { result: { verified: true } };\n }\n return { error: rpcError(E.SCITT_RECEIPT_INVALID, \"No verifyScittReceipt hook configured; receipt not verified\") };\n });\n\n coord.handlers.set(\"audit.verify_chain\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n if (!(ws.chain_enabled || coord.options.enableChain)) {\n return { error: rpcError(E.PARAMS, \"Chain not enabled for this workspace\") };\n }\n // Range verification is not implemented. Accepting the parameters and\n // replaying the whole log anyway would answer a wider question than the\n // caller asked while reporting counts scoped to the whole log, which is\n // the failure this method was just fixed to stop making.\n if (p.from_seq !== undefined || p.to_seq !== undefined) {\n return { error: rpcError(\n E.PARAMS,\n \"Range verification is not implemented; omit from_seq and to_seq to \" +\n \"verify the whole log.\",\n ) };\n }\n // Coverage begins at the first entry carrying a prev_hash. A workspace\n // may enable chaining part-way through its life, in which case every\n // earlier entry is outside the chain and cannot be evaluated against\n // anything. Those entries are not evidence of tampering and not\n // evidence of integrity: they were never checked, and the verdict\n // below has to say so rather than pass over them.\n let start = ws.audit.findIndex(e => e.prev_hash != null);\n if (start < 0) start = ws.audit.length;\n const errors: string[] = [];\n let prev = ZERO_HASH;\n for (const e of ws.audit.slice(start)) {\n const expectedPrev = prev;\n // A chain-enabled workspace must have prev_hash on every entry; a\n // missing value is a defect, not a reason to skip the check.\n if (e.prev_hash !== expectedPrev) {\n errors.push(`seq ${e.seq}: prev_hash mismatch`);\n }\n prev = sha256Hex(Buffer.concat([canonicalize(e.envelope), Buffer.from(expectedPrev, \"utf-8\")]));\n }\n // The recomputed head must match the stored head; this is what makes\n // the final entry tamper-evident.\n // Explicit null/undefined check, matching Python. A falsy-but-present\n // head must not be silently replaced with ZERO_HASH, or the two\n // implementations return different verdicts for the same state.\n const storedHead = (ws.chain_head === undefined || ws.chain_head === null)\n ? ZERO_HASH : ws.chain_head;\n if (prev !== storedHead) {\n errors.push(\"chain_head mismatch: replay does not match stored head\");\n }\n if (errors.length) {\n return { error: rpcError(E.PARAMS, errors.join(\"; \")) };\n }\n const entriesTotal = ws.audit.length;\n const entriesChecked = entriesTotal - start;\n const entriesUnchecked = start;\n // Three terminal verdicts, mutually exclusive: a broken chain returned\n // above as an error, an unevaluated range here, and a pass only when\n // coverage is complete. `not_evaluated` never rides alongside ok:true;\n // a reader that looks at ok alone fails closed rather than reading a\n // pass over entries nothing was checked against.\n if (entriesUnchecked > 0) {\n return { result: {\n status: \"not_evaluated\",\n ok: false,\n reason: \"unchained_prefix\",\n entries_total: entriesTotal,\n entries_checked: entriesChecked,\n entries_unchecked: entriesUnchecked,\n checked_from_seq: entriesChecked > 0 ? ws.audit[start].seq : null,\n chain_head: storedHead,\n }};\n }\n return { result: {\n status: \"verified\",\n ok: true,\n entries_total: entriesTotal,\n entries_checked: entriesChecked,\n entries_unchecked: 0,\n checked_from_seq: entriesChecked > 0 ? ws.audit[start].seq : null,\n chain_head: storedHead,\n }};\n });\n}\n","/**\n * control/1.0 profile (profiles/control.md).\n *\n * Methods:\n * - control.pause / control.resume (scope: task|participant|workspace)\n * - control.cancel\n * - control.snapshot (returns art_... id)\n * - control.rollback (to_snapshot_artefact_id + what_to_restore)\n * - control.supersede (creates successor in one shot)\n * - control.set_mode_ceiling\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport { modeLE } from \"../types.js\";\nimport type { Mode, SnapshotArtefact, Task } from \"../types.js\";\n\nconst VALID_MODES = new Set<Mode>([\"shadow\", \"trial\", \"production\"]);\nconst VALID_SCOPES = new Set([\"task\", \"participant\", \"workspace\"]);\n\nexport function registerControl(coord: Coordinator): void {\n coord.handlers.set(\"control.pause\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const scope = (p.scope as string) || \"task\";\n if (!VALID_SCOPES.has(scope)) {\n return { error: rpcError(E.PARAMS, `scope must be task/participant/workspace`) };\n }\n if (scope === \"task\") {\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state === \"completed\" || task.state === \"declined\" || task.state === \"cancelled\" || task.state === \"superseded\") {\n return { error: rpcError(E.CONTROL_NOT_AUTHORISED, `Cannot pause ${task.state} task`) };\n }\n task.paused = true;\n const prior = task.state;\n task.state = \"paused\";\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: \"paused\", note: `was ${prior}` });\n return { result: { scope: \"task\", task_id: task.id, state: \"paused\" } };\n }\n if (scope === \"participant\") {\n const uri = (p.participant_uri as string) || (p.uri as string);\n if (!uri || !ws.members.has(uri)) return { error: rpcError(E.PARAMS, `Unknown participant: ${uri}`) };\n ws.members.get(uri)!.paused = true;\n return { result: {\n scope: \"participant\", participant_uri: uri, paused: true,\n in_flight_policy: (p.in_flight_policy as string) || \"allow_to_complete\",\n }};\n }\n // workspace\n ws.state = \"paused\";\n return { result: { scope: \"workspace\", workspace: ws.id, state: \"paused\" } };\n });\n\n coord.handlers.set(\"control.resume\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const scope = (p.scope as string) || \"task\";\n if (!VALID_SCOPES.has(scope)) {\n return { error: rpcError(E.PARAMS, `scope must be task/participant/workspace`) };\n }\n if (scope === \"task\") {\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"paused\") {\n return { error: rpcError(E.CONTROL_NOT_AUTHORISED, `Cannot resume ${task.state} task`) };\n }\n task.paused = false;\n task.state = \"in_progress\";\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: \"in_progress\" });\n return { result: { scope: \"task\", task_id: task.id, state: \"in_progress\" } };\n }\n if (scope === \"participant\") {\n const uri = (p.participant_uri as string) || (p.uri as string);\n if (!uri || !ws.members.has(uri)) return { error: rpcError(E.PARAMS, `Unknown participant: ${uri}`) };\n ws.members.get(uri)!.paused = false;\n return { result: { scope: \"participant\", participant_uri: uri, paused: false } };\n }\n ws.state = \"active\";\n return { result: { scope: \"workspace\", workspace: ws.id, state: \"active\" } };\n });\n\n coord.handlers.set(\"control.cancel\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state === \"completed\" || task.state === \"declined\" || task.state === \"cancelled\" || task.state === \"superseded\") {\n return { error: rpcError(E.CONTROL_NOT_AUTHORISED, `Cannot cancel ${task.state} task`) };\n }\n task.state = \"cancelled\";\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: \"cancelled\", note: p.reason as string | undefined });\n return { result: { state: \"cancelled\" } };\n });\n\n coord.handlers.set(\"control.snapshot\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const include: string[] = (p.include as string[]) ?? [\"members\", \"open_tasks\", \"mode_ceiling\"];\n const state: Record<string, unknown> = {};\n if (include.includes(\"members\")) {\n state.members = Array.from(ws.members.values()).map(m => ({\n uri: m.uri, type: m.type, role: m.role, scopes: m.scopes,\n }));\n }\n if (include.includes(\"open_tasks\")) {\n state.open_tasks = Array.from(ws.tasks.values())\n .filter(t => t.state !== \"completed\" && t.state !== \"declined\" && t.state !== \"cancelled\" && t.state !== \"superseded\")\n .map(t => ({ id: t.id, kind: t.kind, state: t.state, assignee: t.assignee }));\n }\n if (include.includes(\"mode_ceiling\")) state.mode_ceiling = ws.mode_ceiling;\n if (include.includes(\"policy\")) state.routing_policy_uri = ws.routing_policy_uri;\n if (include.includes(\"audit\") || include.includes(\"all\")) state.audit_seq = ws.audit.length;\n\n const snapId = coord.ids.artefactId();\n const snap: SnapshotArtefact = {\n id: snapId,\n kind: \"snapshot\",\n ts: coord.now(),\n by: p.from as string,\n workspace: ws.id,\n audit_seq: ws.audit.length,\n label: p.label as string | undefined,\n include,\n state,\n };\n ws.snapshots.set(snapId, snap);\n return { result: { snapshot_artefact_id: snapId, audit_seq: snap.audit_seq, artefact: snap } };\n });\n\n coord.handlers.set(\"control.rollback\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const snapId = (p.to_snapshot_artefact_id as string)\n || (p.snapshot_artefact_id as string)\n || (p.snapshot_id as string);\n if (!snapId) return { error: rpcError(E.PARAMS, \"to_snapshot_artefact_id is required\") };\n const snap = ws.snapshots.get(snapId);\n if (!snap) return { error: rpcError(E.CONTROL_SNAPSHOT_NOT_FOUND, `Unknown snapshot: ${snapId}`) };\n const what: string[] = (p.what_to_restore as string[]) ?? snap.include;\n const restored: string[] = [];\n if (what.includes(\"mode_ceiling\") && snap.state.mode_ceiling) {\n ws.mode_ceiling = snap.state.mode_ceiling as Mode;\n restored.push(\"mode_ceiling\");\n }\n if (what.includes(\"members\") && Array.isArray(snap.state.members)) {\n const snapByUri = new Map<string, Record<string, unknown>>();\n for (const m of snap.state.members as Array<Record<string, unknown>>) {\n snapByUri.set(m.uri as string, m);\n }\n for (const [uri, snapM] of snapByUri) {\n if (ws.members.has(uri)) {\n const cur = ws.members.get(uri)!;\n cur.role = (snapM.role as string) ?? cur.role;\n cur.scopes = snapM.scopes as string[] | undefined;\n }\n }\n restored.push(\"members\");\n }\n return { result: {\n rolled_back_to: snapId, audit_seq: snap.audit_seq, restored,\n reason: p.reason as string | undefined,\n }};\n });\n\n coord.handlers.set(\"control.supersede\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const oldId = p.task_id as string;\n const old = ws.tasks.get(oldId);\n if (!old) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const newSpec = (p.successor_task as Record<string, unknown>) ?? {};\n if (!newSpec.kind) {\n return { error: rpcError(E.PARAMS, \"successor_task must include kind\") };\n }\n const assignee = (newSpec.assignee as string) || old.assignee;\n if (!ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"successor assignee not in workspace\") };\n }\n // The successor is a created task, so it is bound by the same modes/1.0\n // invariants as task.create: it must not exceed the workspace ceiling, and\n // a trial-mode task forces review on regardless of its own setting.\n const requestedMode = (newSpec.mode as Mode) ?? old.mode;\n if (!modeLE(requestedMode, ws.mode_ceiling)) {\n return { error: rpcError(E.MODE_CEILING_EXCEEDED,\n `Requested mode ${requestedMode} exceeds ceiling ${ws.mode_ceiling}`) };\n }\n const now = coord.now();\n const newId = coord.ids.taskId();\n const newTask: Task = {\n id: newId,\n kind: newSpec.kind as string,\n state: \"created\",\n assignee,\n delegator: p.from as string,\n input: (newSpec.input as Record<string, unknown>) ?? {},\n created_at: now,\n updated_at: now,\n mode: requestedMode,\n supersedes: old.id,\n history: [{ ts: now, from: p.from as string, state: \"created\",\n note: `supersedes ${old.id}: ${(p.reason as string) || \"\"}` }],\n paused: false,\n };\n // Trial forces review only when the workspace opted into modes/1.0,\n // matching task.create -- mode is inert without the profile.\n if (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && newTask.mode === \"trial\") newTask.review_required = true;\n else if (\"review_required\" in newSpec) newTask.review_required = !!newSpec.review_required;\n ws.tasks.set(newId, newTask);\n old.state = \"superseded\";\n old.superseded_by = newId;\n old.updated_at = now;\n old.history.push({ ts: now, from: p.from as string, state: \"superseded\",\n note: `-> ${newId}: ${(p.reason as string) || \"\"}` });\n return { result: { superseded_task_id: old.id, new_task_id: newId, reason: p.reason as string | undefined } };\n });\n\n coord.handlers.set(\"control.set_mode_ceiling\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const m = (p.new_ceiling as Mode) ?? (p.mode_ceiling as Mode);\n if (!VALID_MODES.has(m)) {\n return { error: rpcError(E.PARAMS, `new_ceiling must be shadow/trial/production`) };\n }\n ws.mode_ceiling = m;\n return { result: { mode_ceiling: ws.mode_ceiling, reason: p.reason as string | undefined } };\n });\n}\n","/**\n * deliberation/1.0 profile (profiles/deliberation.md).\n *\n * Methods:\n * - deliberate.open\n * - deliberate.comment\n * - deliberate.vote\n * - deliberate.close\n *\n * Rules: any_one_approves | all_approve | quorum:N |\n * weighted_vote:T | weighted_vote_with_veto:T\n *\n * Error codes (spec S5):\n * -32030 voter not in participant list\n * -32031 already voted\n * -32032 closed or lapsed\n * -32033 unknown rule\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { Deliberation } from \"../types.js\";\n\nfunction parseRule(rule: string): { kind: string; params: Record<string, number> } {\n if (rule.includes(\":\")) {\n const [kind, arg] = rule.split(\":\", 2);\n if (kind === \"quorum\") return { kind, params: { n: parseInt(arg, 10) } };\n if (kind === \"weighted_vote\" || kind === \"weighted_vote_with_veto\") {\n return { kind, params: { threshold: parseFloat(arg) } };\n }\n }\n if (rule === \"any_one_approves\" || rule === \"all_approve\") return { kind: rule, params: {} };\n throw new Error(`Unknown rule: ${rule}`);\n}\n\nfunction computeOutcome(delib: Deliberation): Deliberation[\"outcome\"] {\n const parsed = parseRule(delib.rule);\n const yea = delib.votes.filter(v => v.vote === \"yea\");\n const nay = delib.votes.filter(v => v.vote === \"nay\");\n const vetoes = delib.votes.filter(v => v.veto_invoked && (delib.veto ?? {})[v.voter]);\n const weights = delib.weights ?? {};\n\n const weighted = (vs: typeof yea) =>\n vs.reduce((s, v) => s + (weights[v.voter] ?? 1.0), 0);\n\n if (parsed.kind === \"any_one_approves\") {\n return {\n outcome: yea.length >= 1 ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length },\n vetoes: vetoes.map(v => v.voter),\n };\n }\n if (parsed.kind === \"all_approve\") {\n const passed = yea.length === delib.participants.length && nay.length === 0;\n return {\n outcome: passed ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length },\n vetoes: vetoes.map(v => v.voter),\n };\n }\n if (parsed.kind === \"quorum\") {\n const n = parsed.params.n;\n const cast = yea.length + nay.length;\n if (cast < n) {\n return {\n outcome: \"rejected\", reason: \"quorum not met\", rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length }, vetoes: [],\n };\n }\n return {\n outcome: yea.length > nay.length ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yea.length, nay: nay.length },\n vetoes: [],\n };\n }\n if (parsed.kind === \"weighted_vote\") {\n const yeaW = weighted(yea), nayW = weighted(nay);\n return {\n outcome: yeaW >= parsed.params.threshold ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yeaW, nay: nayW }, vetoes: [],\n };\n }\n if (parsed.kind === \"weighted_vote_with_veto\") {\n if (vetoes.length) {\n return {\n outcome: \"rejected\", rule: delib.rule,\n tally: { yea: 0, nay: 0 },\n vetoes: vetoes.map(v => v.voter),\n };\n }\n const yeaW = weighted(yea), nayW = weighted(nay);\n return {\n outcome: yeaW >= parsed.params.threshold ? \"approved\" : \"rejected\",\n rule: delib.rule,\n tally: { yea: yeaW, nay: nayW }, vetoes: [],\n };\n }\n return { outcome: \"error\", rule: delib.rule, reason: `unsupported rule ${parsed.kind}` };\n}\n\nexport function registerDeliberation(coord: Coordinator): void {\n coord.handlers.set(\"deliberate.open\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"rule\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const to = p.to ?? p.participants;\n const participants: string[] = Array.isArray(to) ? (to as string[]) : typeof to === \"string\" ? [to] : [];\n if (!participants.length) {\n return { error: rpcError(E.PARAMS, \"deliberate.open needs 'to' (participants list)\") };\n }\n try { parseRule(p.rule as string); }\n catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.DELIB_UNKNOWN_RULE, msg) };\n }\n const id = (p.deliberation_id as string) || coord.ids.deliberationId();\n const delib: Deliberation = {\n id,\n task_id: p.task_id as string | undefined,\n opener: p.from as string,\n participants,\n rule: p.rule as string,\n question: p.question as string | undefined,\n weights: p.weights as Deliberation[\"weights\"],\n veto: p.veto as Deliberation[\"veto\"],\n deadline: p.deadline as string | undefined,\n state: \"open\",\n comments: [],\n votes: [],\n opened_at: coord.now(),\n };\n ws.deliberations.set(id, delib);\n return { result: { deliberation_id: id, state: \"open\" } };\n });\n\n coord.handlers.set(\"deliberate.comment\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const delib = ws.deliberations.get(p.deliberation_id as string);\n if (!delib) return { error: rpcError(E.PARAMS, \"Unknown deliberation\") };\n if (delib.state !== \"open\") {\n return { error: rpcError(E.DELIB_CLOSED_OR_LAPSED, \"Deliberation not open\") };\n }\n delib.comments.push({\n ts: coord.now(),\n from: p.from as string,\n text: (p.comment as string) || (p.text as string) || \"\",\n });\n return { result: { accepted: true } };\n });\n\n coord.handlers.set(\"deliberate.vote\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const delib = ws.deliberations.get(p.deliberation_id as string);\n if (!delib) return { error: rpcError(E.PARAMS, \"Unknown deliberation\") };\n if (delib.state !== \"open\") {\n return { error: rpcError(E.DELIB_CLOSED_OR_LAPSED, \"Deliberation not open\") };\n }\n for (const f of [\"from\", \"vote\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const v = p.vote as string;\n if (v !== \"yea\" && v !== \"nay\" && v !== \"abstain\") {\n return { error: rpcError(E.PARAMS, \"vote must be yea/nay/abstain\") };\n }\n const voter = p.from as string;\n if (!delib.participants.includes(voter)) {\n return { error: rpcError(E.DELIB_VOTER_NOT_IN_LIST,\n `Voter ${voter} not in participant list`) };\n }\n if (delib.votes.some(x => x.voter === voter)) {\n return { error: rpcError(E.DELIB_ALREADY_VOTED, `Voter ${voter} has already voted`) };\n }\n delib.votes.push({\n ts: coord.now(),\n voter,\n vote: v as \"yea\" | \"nay\" | \"abstain\",\n weight: p.weight as number | undefined,\n comment: p.comment as string | undefined,\n veto_invoked: !!p.veto_invoked,\n });\n return { result: { recorded: true } };\n });\n\n coord.handlers.set(\"deliberate.close\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const delib = ws.deliberations.get(p.deliberation_id as string);\n if (!delib) return { error: rpcError(E.PARAMS, \"Unknown deliberation\") };\n if (delib.state === \"closed\") return { result: delib.outcome! };\n delib.state = \"closed\";\n delib.outcome = computeOutcome(delib);\n return { result: delib.outcome };\n });\n}\n","/**\n * handoff/1.0 profile (profiles/handoff.md).\n *\n * Carries multiple tasks. Recipient is a single URI or a group:... URI.\n *\n * Error codes (spec S6):\n * -32050 tasks not assigned to proposer\n * -32051 already resolved\n * -32052 recipient not a workspace member\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { Handoff, HandoffTaskItem } from \"../types.js\";\n\nexport function registerHandoff(coord: Coordinator): void {\n coord.handlers.set(\"handoff.propose\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"to\", \"tasks\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const proposer = p.from as string;\n const recipient = p.to as string;\n if (typeof recipient === \"string\" && !recipient.startsWith(\"group:\")) {\n if (!ws.members.has(recipient)) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n `Recipient ${recipient} is not a member`) };\n }\n }\n const tasksIn = p.tasks;\n if (!Array.isArray(tasksIn) || !tasksIn.length) {\n return { error: rpcError(E.PARAMS, \"tasks must be a non-empty list\") };\n }\n const proposed: HandoffTaskItem[] = [];\n for (const t of tasksIn as Array<Record<string, unknown>>) {\n const tid = t.task_id as string;\n if (!tid || !ws.tasks.has(tid)) {\n return { error: rpcError(E.PARAMS, `Unknown task in handoff: ${tid}`) };\n }\n const task = ws.tasks.get(tid)!;\n if (task.assignee !== proposer) {\n return { error: rpcError(E.HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER,\n `Task ${tid} is not currently assigned to ${proposer}`) };\n }\n proposed.push({\n task_id: tid,\n title: t.title as string | undefined,\n status_summary: t.status_summary as string | undefined,\n next_action: t.next_action as string | undefined,\n blockers: (t.blockers as string[] | undefined) ?? [],\n });\n }\n const id = (p.handoff_id as string) || coord.ids.handoffId();\n const ho: Handoff = {\n id,\n proposer,\n recipient,\n proposed_at: coord.now(),\n tasks: proposed,\n summary: p.summary as string | undefined,\n context_links: (p.context_links as string[] | undefined) ?? [],\n state: \"proposed\",\n };\n ws.handoffs.set(id, ho);\n return { result: { handoff_id: id, state: \"proposed\", task_ids: proposed.map(t => t.task_id) } };\n });\n\n coord.handlers.set(\"handoff.accept\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"handoff_id\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const ho = ws.handoffs.get(p.handoff_id as string);\n if (!ho) return { error: rpcError(E.PARAMS, \"Unknown handoff\") };\n if (ho.state !== \"proposed\") {\n return { error: rpcError(E.HANDOFF_ALREADY_RESOLVED, `Handoff already ${ho.state}`) };\n }\n const acceptor = p.from as string;\n if (ho.recipient.startsWith(\"group:\")) {\n if (!ws.members.has(acceptor)) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n \"Acceptor is not a workspace member\") };\n }\n } else {\n if (acceptor !== ho.recipient) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n \"Acceptor is not the named recipient\") };\n }\n if (!ws.members.has(acceptor)) {\n return { error: rpcError(E.HANDOFF_RECIPIENT_NOT_MEMBER,\n \"Acceptor is not a workspace member\") };\n }\n }\n const validIds = new Set(ho.tasks.map(t => t.task_id));\n const acceptedIds: string[] = Array.isArray(p.accepted_task_ids)\n ? (p.accepted_task_ids as string[])\n : ho.tasks.map(t => t.task_id);\n for (const tid of acceptedIds) {\n if (!validIds.has(tid)) {\n return { error: rpcError(E.PARAMS, `Task ${tid} not in this handoff`) };\n }\n }\n const now = coord.now();\n for (const tid of acceptedIds) {\n const task = ws.tasks.get(tid)!;\n task.assignee = acceptor;\n task.updated_at = now;\n task.history.push({\n ts: now, from: acceptor, state: task.state,\n note: `handoff accepted from ${ho.proposer}`,\n });\n }\n ho.state = \"accepted\";\n ho.accepted_by = acceptor;\n ho.accepted_task_ids = [...acceptedIds];\n ho.accept_comment = p.comment as string | undefined;\n ho.resolved_at = now;\n return { result: { accepted: true, task_ids: [...acceptedIds], assignee: acceptor } };\n });\n\n coord.handlers.set(\"handoff.decline\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"handoff_id\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const ho = ws.handoffs.get(p.handoff_id as string);\n if (!ho) return { error: rpcError(E.PARAMS, \"Unknown handoff\") };\n if (ho.state !== \"proposed\") {\n return { error: rpcError(E.HANDOFF_ALREADY_RESOLVED, `Handoff already ${ho.state}`) };\n }\n const decliner = p.from as string;\n ho.decline_reason = p.reason as string | undefined;\n ho.decline_suggested_target = p.suggested_target as string | undefined;\n if (!ho.recipient.startsWith(\"group:\") && decliner === ho.recipient) {\n ho.state = \"declined\";\n ho.resolved_at = coord.now();\n }\n return { result: { recorded: true, state: ho.state } };\n });\n}\n","/**\n * routing/1.0 profile (profiles/routing.md).\n *\n * Three methods, each emits a route_decision artefact:\n * - task.route -> pick assignee + update task.assignee\n * - review.depth -> skip / spot_check / full + sampling_probability\n * - escalate.auto -> evaluate auto-escalation\n *\n * Error codes:\n * -32510 no eligible assignee\n * -32513 candidates_empty\n * -32514 depth_not_applicable\n * -32515 policy_unreachable\n * -32516 escalation target unavailable\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { RouteDecisionArtefact, Task } from \"../types.js\";\n\nconst CRIT: Record<string, number> = { low: 0, medium: 1, high: 2, critical: 3 };\n\nfunction defaultDepth(hints: Record<string, unknown>): {\n depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n sampling?: number;\n summary: string;\n} {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n if (r >= 3) return { depth: \"full\", summary: \"criticality=critical: full review\" };\n if (r === 2 && conf < 0.7) return { depth: \"full\", summary: \"criticality=high and confidence<0.7: full review\" };\n if (r === 0 && conf >= 0.95) return { depth: \"skip\", summary: \"very low criticality + very high confidence: skip\" };\n if (r <= 1 && conf >= 0.85) return { depth: \"spot_check\", sampling: 0.10, summary: \"low criticality + high confidence: 10% sample\" };\n return { depth: \"spot_check\", sampling: 0.25, summary: \"default mid-confidence: 25% sample\" };\n}\n\nexport function registerRouting(coord: Coordinator): void {\n coord.handlers.set(\"task.route\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const candidates = (p.candidates as string[]) ?? [];\n if (!candidates.length) {\n return { error: rpcError(E.ROUTING_CANDIDATES_EMPTY, \"candidates array was empty\") };\n }\n let selected: string;\n let rationale: Record<string, unknown>;\n if (coord.options.routingPolicy) {\n try {\n const d = coord.options.routingPolicy(task, [...candidates]);\n selected = d.selected;\n rationale = d.rationale;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.ROUTING_POLICY_UNREACHABLE, `routing policy error: ${msg}`) };\n }\n } else {\n const eligible = candidates.filter(c => ws.members.has(c));\n if (!eligible.length) {\n return { error: rpcError(E.ROUTING_NO_ELIGIBLE_ASSIGNEE, \"No candidate is a workspace member\") };\n }\n selected = eligible[0];\n rationale = {\n policy_id: \"default\",\n hints_used: Object.keys(task.routing_hints ?? {}),\n summary: \"default policy: first eligible candidate\",\n alternatives_considered: eligible.slice(1).map(c => ({\n candidate: c, reason_excluded: \"not first eligible\",\n })),\n };\n }\n if (!ws.members.has(selected)) {\n return { error: rpcError(E.ROUTING_NO_ELIGIBLE_ASSIGNEE,\n `Selected ${JSON.stringify(selected)} is not a member`) };\n }\n task.assignee = selected;\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: \"service:coordinator\",\n state: task.state, note: `routed to ${selected}` });\n const artId = coord.ids.artefactId();\n const artefact: RouteDecisionArtefact = {\n id: artId, kind: \"route_decision\",\n decision_type: \"task.route\", outcome: selected,\n produced_by: \"service:coordinator\", produced_at: task.updated_at,\n task: task.id,\n policy_id: rationale.policy_id as string | undefined,\n hints_observed: { ...(task.routing_hints ?? {}) },\n rationale: (rationale.summary as string) ?? \"\",\n alternatives_considered: rationale.alternatives_considered,\n };\n ws.route_decisions.set(artId, artefact);\n return { result: { selected, decision_artefact: artId, rationale } };\n });\n\n coord.handlers.set(\"review.depth\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const hints: Record<string, unknown> = { ...(task.routing_hints ?? {}),\n ...((p.artefact_routing_hints as Record<string, unknown>) ?? {}) };\n if (!Object.keys(hints).length) {\n return { error: rpcError(E.ROUTING_DEPTH_NOT_APPLICABLE, \"No routing_hints to consult\") };\n }\n let depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n let sampling: number | undefined;\n let summary: string;\n let policyId: string;\n if (coord.options.reviewDepthPolicy) {\n try {\n const d = coord.options.reviewDepthPolicy(task, hints);\n depth = d.depth;\n sampling = d.sampling_probability;\n summary = (d.rationale.summary as string) ?? \"operator policy\";\n policyId = (d.rationale.policy_id as string) ?? \"operator\";\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.ROUTING_POLICY_UNREACHABLE, `depth policy error: ${msg}`) };\n }\n } else {\n const d = defaultDepth(hints);\n depth = d.depth; sampling = d.sampling; summary = d.summary;\n policyId = \"default\";\n }\n const artId = coord.ids.artefactId();\n const artefact: RouteDecisionArtefact = {\n id: artId, kind: \"route_decision\",\n decision_type: \"review.depth\", outcome: depth,\n produced_by: \"service:coordinator\", produced_at: coord.now(),\n task: task.id, policy_id: policyId,\n hints_observed: hints, rationale: summary,\n ...(sampling !== undefined ? { sampling_probability: sampling } : {}),\n };\n ws.route_decisions.set(artId, artefact);\n const result: Record<string, unknown> = {\n depth, decision_artefact: artId,\n rationale: { policy_id: policyId, hints_used: Object.keys(hints), summary },\n };\n if (sampling !== undefined) result.sampling_probability = sampling;\n return { result };\n });\n\n coord.handlers.set(\"escalate.auto\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const hints = { ...(task.routing_hints ?? {}) };\n let escalate: boolean, to: string | undefined, rule: Record<string, unknown>;\n if (coord.options.escalationPolicy) {\n try {\n const d = coord.options.escalationPolicy(task, hints);\n escalate = !!d.escalate;\n to = d.to;\n rule = d.triggered_rule ?? {};\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.ROUTING_POLICY_UNREACHABLE, `escalation policy error: ${msg}`) };\n }\n } else {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n escalate = r >= 3 || (r >= 2 && conf < 0.6);\n to = p.default_escalation_target as string | undefined;\n rule = {\n rule_id: \"default-auto-esc\",\n summary: \"criticality=critical OR (criticality>=high AND confidence<0.6)\",\n hints_used: [\"criticality\", \"confidence\"],\n };\n }\n const artId = coord.ids.artefactId();\n const artefact: RouteDecisionArtefact = {\n id: artId, kind: \"route_decision\",\n decision_type: \"escalate.auto\",\n outcome: escalate ? { escalate: true, to } : { escalate: false },\n produced_by: \"service:coordinator\", produced_at: coord.now(),\n task: task.id,\n policy_id: rule.rule_id as string | undefined,\n hints_observed: hints,\n rationale: (rule.summary as string) ?? \"\",\n ...(escalate ? { escalation_target: to } : {}),\n };\n ws.route_decisions.set(artId, artefact);\n if (escalate) {\n if (!to) return { error: rpcError(E.ROUTING_ESC_TARGET_UNAVAILABLE,\n \"Escalation triggered but no target available\") };\n if (!to.startsWith(\"group:\") && !ws.members.has(to)) {\n return { error: rpcError(E.ROUTING_ESC_TARGET_UNAVAILABLE,\n `Escalation target ${to} is not a member or group`) };\n }\n if (coord.options.onAutoEscalate) {\n try { coord.options.onAutoEscalate(task, to); } catch { /* */ }\n }\n return { result: { escalate: true, to, decision_artefact: artId, triggered_rule: rule } };\n }\n return { result: { escalate: false, decision_artefact: artId } };\n });\n}\n","/**\n * security-signed/1.0 profile (profiles/security-signed.md).\n *\n * Top-level `sig` field on every envelope: ed25519:<kid>:<base64>.\n * Verification happens at dispatch (see Coordinator.verifySignature).\n *\n * Methods:\n * - participant.rotate_key\n * - participant.revoke_key\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { KeyRecord } from \"../types.js\";\n\nexport function registerSecuritySigned(coord: Coordinator): void {\n coord.handlers.set(\"participant.rotate_key\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"old_kid\", \"new_jwk\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const member = ws.members.get(p.from as string);\n if (!member) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `Unknown participant: ${p.from}`) };\n const oldKid = p.old_kid as string;\n const oldKey = member.keys.find(k => k.kid === oldKid);\n if (!oldKey) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `No key ${oldKid} for ${p.from}`) };\n if (oldKey.revoked_at) return { error: rpcError(E.SIG_KEY_REVOKED, `Key ${oldKid} is revoked`) };\n\n const newJwk = p.new_jwk as Record<string, unknown>;\n if (!newJwk || typeof newJwk.kid !== \"string\") {\n return { error: rpcError(E.PARAMS, \"new_jwk must include kid\") };\n }\n const now = coord.now();\n oldKey.valid_until = now;\n member.keys.push({\n jwk: newJwk as unknown as KeyRecord[\"jwk\"],\n kid: newJwk.kid as string,\n valid_from: now,\n });\n return { result: { rotated: true, old_kid: oldKid, new_kid: newJwk.kid, valid_from: now } };\n });\n\n coord.handlers.set(\"participant.revoke_key\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"target_uri\", \"kid\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const sender = p.from as string | undefined;\n if (sender !== p.target_uri) {\n const caller = sender ? ws.members.get(sender) : undefined;\n if (!caller || caller.role !== \"admin\") {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"Revoking another member's key requires the admin role\") };\n }\n }\n const member = ws.members.get(p.target_uri as string);\n if (!member) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `Unknown target: ${p.target_uri}`) };\n const key = member.keys.find(k => k.kid === p.kid);\n if (!key) return { error: rpcError(E.SIG_KEY_NOT_FOUND, `No key ${p.kid} for target`) };\n const now = coord.now();\n key.revoked_at = now;\n key.revoked_reason = (p.reason as string) || \"unspecified\";\n return { result: { revoked: true, kid: key.kid, revoked_at: now, reason: key.revoked_reason } };\n });\n}\n","/**\n * whisper/1.0 profile (profiles/whisper.md).\n *\n * Methods:\n * - whisper.ask -> pose a deadline-bound question with options + default\n * - whisper.answer -> answer a whisper\n *\n * Lapse handling: coordinator.checkWhisperLapses(workspaceId, now?) is\n * registered on the Coordinator instance for deployments to call from a\n * scheduler.\n *\n * Error codes (per spec S6):\n * -32020 WHISPER_ALREADY_ANSWERED\n * -32021 WHISPER_LAPSED\n * -32022 WHISPER_OPTION_NOT_IN_SET\n */\nimport type { Coordinator } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport type { WhisperPrompt, Envelope } from \"../types.js\";\n\nfunction parseIso(ts: string): number { return new Date(ts).getTime(); }\n\nexport function registerWhisper(coord: Coordinator): void {\n coord.handlers.set(\"whisper.ask\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"to\", \"task_id\", \"question\", \"deadline_ms\", \"default_if_lapsed\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n if (!ws.tasks.has(p.task_id as string)) {\n return { error: rpcError(E.PARAMS, \"Unknown task\") };\n }\n const to = p.to;\n const askee: string[] = Array.isArray(to) ? (to as string[]) : [to as string];\n const id = (p.whisper_id as string) || coord.ids.artefactId();\n const prompt: WhisperPrompt = {\n id,\n task_id: p.task_id as string,\n asker: p.from as string,\n askee,\n question: p.question as string,\n options: p.options as WhisperPrompt[\"options\"],\n asked_at: coord.now(),\n deadline_ms: Number(p.deadline_ms),\n default_if_lapsed: p.default_if_lapsed,\n urgency: (p.urgency as WhisperPrompt[\"urgency\"]) || \"low\",\n state: \"pending\",\n };\n ws.whispers.set(id, prompt);\n return { result: { whisper_id: id, deadline_ms: prompt.deadline_ms } };\n });\n\n coord.handlers.set(\"whisper.answer\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n for (const f of [\"from\", \"whisper_id\"]) {\n if (!(f in p)) return { error: rpcError(E.PARAMS, `Missing field: ${f}`) };\n }\n const prompt = ws.whispers.get(p.whisper_id as string);\n if (!prompt) return { error: rpcError(E.PARAMS, \"Unknown whisper id\") };\n // Only a participant the whisper was addressed to may answer it. A\n // broadcast scope (workspace:/group:) is satisfied by any member; the\n // coordinator does not model group membership (see SPECIFICATION.md).\n const answerer = p.from as string;\n const broadcast = prompt.askee.some((a) => typeof a === \"string\" && (a.startsWith(\"workspace:\") || a.startsWith(\"group:\")));\n if (broadcast) {\n if (!ws.members.has(answerer)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not a workspace member: ${answerer}`) };\n }\n } else if (!prompt.askee.includes(answerer)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Whisper was not addressed to ${answerer}`) };\n }\n if (prompt.state === \"answered\") {\n return { error: rpcError(E.WHISPER_ALREADY_ANSWERED, \"Whisper already answered\") };\n }\n if (prompt.state === \"lapsed\") {\n return { error: rpcError(E.WHISPER_LAPSED, \"Whisper already lapsed\") };\n }\n\n const answerOption = p.answer_option as string | undefined;\n const answerText = (p.answer as string | undefined) ?? (p.answer_text as string | undefined);\n if (prompt.options && prompt.options.length) {\n if (answerOption === undefined) {\n return { error: rpcError(E.PARAMS, \"answer_option is required when options are defined\") };\n }\n const valid = new Set(prompt.options.map(o => o.id));\n if (!valid.has(answerOption)) {\n return { error: rpcError(E.WHISPER_OPTION_NOT_IN_SET,\n `Answer option ${JSON.stringify(answerOption)} not in option set`) };\n }\n } else {\n if (answerText === undefined && answerOption === undefined) {\n return { error: rpcError(E.PARAMS, \"answer or answer_option required\") };\n }\n }\n\n prompt.state = \"answered\";\n prompt.answered_at = coord.now();\n prompt.answered_by = p.from as string;\n prompt.answer_option = answerOption;\n prompt.answer_text = answerText;\n prompt.comment = p.comment as string | undefined;\n // Echo the whisper's task_id onto the recorded envelope so a\n // task-filtered audit.read returns the answer alongside the ask. The\n // value comes from the stored whisper, not the caller, so an answer\n // cannot be filed against a different task.\n p.task_id = prompt.task_id;\n return { result: { answered: true, whisper_id: prompt.id, task_id: prompt.task_id } };\n });\n\n // Expose the lapse-check function on the coordinator instance.\n coord.checkWhisperLapses = (workspaceId: string, now?: string): Envelope[] => {\n const ws = coord.workspaces.get(workspaceId);\n if (!ws) return [];\n const cutoff = parseIso(now ?? coord.now());\n const emitted: Envelope[] = [];\n for (const prompt of ws.whispers.values()) {\n if (prompt.state !== \"pending\") continue;\n const asked = parseIso(prompt.asked_at);\n const deadline = asked + prompt.deadline_ms;\n if (cutoff < deadline) continue;\n prompt.state = \"lapsed\";\n prompt.default_applied = prompt.default_if_lapsed;\n const notify: Envelope = {\n jsonrpc: \"2.0\",\n method: \"notify.message\",\n params: {\n workspace: ws.id,\n from: \"service:coordinator\",\n to: [prompt.asker, ...prompt.askee],\n ts: coord.now(),\n kind: \"whisper_lapsed\",\n whisper_id: prompt.id,\n // Carry the task so a task-filtered audit.read surfaces the\n // lapse. A lapsed whisper applies its default with no human\n // input, so it is the case most in need of being visible on\n // the task's thread.\n task_id: prompt.task_id,\n default_applied: prompt.default_if_lapsed,\n },\n };\n coord.recordAudit(ws, notify);\n emitted.push(notify);\n }\n return emitted;\n };\n}\n","/**\n * @brightbeamai/chap-coordinator/coordinator\n *\n * The Coordinator class. CHAP protocol logic, packaged as a library\n * rather than a CLI server. Applications instantiate one, call\n * `dispatch(envelope)`, subscribe to audit events, and persist via\n * the provided hooks.\n *\n * Coverage:\n * - Core (9 methods)\n * - review/1.0 (6 methods)\n * - whisper/1.0 (2 methods + lapse handling)\n * - deliberation/1.0 (4 methods)\n * - modes/1.0 (mode handling at task.create; trial forces review)\n * - handoff/1.0 (3 methods with multi-task and group support)\n * - control/1.0 (7 methods with task/participant/workspace scopes)\n * - routing/1.0 (3 methods producing route_decision artefacts)\n * - security-signed/1.0 (top-level `sig` field; key history)\n * - audit-scitt/1.0 (statement assembly + local chain linkage)\n * - identity-oidc/1.0 + identity-vc/1.0 (binding hooks at join)\n */\n\nimport { canonicalize, contentHash, sha256Hex, ZERO_HASH } from \"./canonical.js\";\nimport { publicKeyFromJwk, verifyEnvelope } from \"./crypto.js\";\nimport { IdFactory } from \"./ids.js\";\nimport { E, isValidEnvelope, rpcError } from \"./jsonrpc.js\";\nimport { applyJsonPatch } from \"./patch.js\";\nimport type { Store, WorkspaceRecord } from \"./storage/store.js\";\nimport { MemoryStore } from \"./storage/store.js\";\nimport { makeApi, type CoordinatorApi } from \"./api.js\";\nimport type {\n ArtefactId,\n AuditEntry,\n AuditListener,\n Envelope,\n KeyRecord,\n Member,\n Mode,\n OverrideArtefact,\n ParticipantUri,\n Task,\n TaskId,\n Workspace,\n WorkspaceId,\n} from \"./types.js\";\nimport { modeLE } from \"./types.js\";\nimport { registerAuditScitt } from \"./profiles/audit_scitt.js\";\nimport { registerControl } from \"./profiles/control.js\";\nimport { registerDeliberation } from \"./profiles/deliberation.js\";\nimport { registerHandoff } from \"./profiles/handoff.js\";\nimport { registerRouting } from \"./profiles/routing.js\";\nimport { registerSecuritySigned } from \"./profiles/security_signed.js\";\nimport { registerWhisper } from \"./profiles/whisper.js\";\n\n// ============================================================\n// Options\n// ============================================================\n\nexport type TokenVerifier = (token: string) => Record<string, unknown> | null;\nexport type CredentialVerifier = (presentation: Record<string, unknown>) => Record<string, unknown> | null;\nexport type ScittSubmitter = (statement: Record<string, unknown>) => Record<string, unknown> | null;\nexport type ScittReceiptVerifier = (receipt: Record<string, unknown>) => boolean;\nexport type RoutingPolicyFn = (task: Task, candidates: ParticipantUri[]) => {\n selected: ParticipantUri;\n rationale: Record<string, unknown>;\n};\nexport type ReviewDepthPolicyFn = (task: Task, hints: Record<string, unknown>) => {\n depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n sampling_probability?: number;\n rationale: Record<string, unknown>;\n};\nexport type EscalationPolicyFn = (task: Task, hints: Record<string, unknown>) => {\n escalate: boolean;\n to?: ParticipantUri;\n triggered_rule?: Record<string, unknown>;\n};\n\n/** Methods classified as privileged for step-up auth. */\nexport const PRIVILEGED_METHODS = new Set<string>([\n \"control.pause\", \"control.resume\", \"control.cancel\", \"control.supersede\",\n \"control.snapshot\", \"control.rollback\", \"control.set_mode_ceiling\",\n \"workspace.set_profiles\",\n \"participant.rotate_key\", \"participant.revoke_key\",\n]);\n\n// Read-only methods return workspace state but do not mutate it, so they are not\n// recorded in the audit chain -- recording a read would grow and re-link it.\nconst READ_ONLY_METHODS = new Set<string>([\n \"workspace.describe\", \"audit.read\", \"audit.verify_chain\", \"audit.verify_receipt\",\n]);\n\n// Cap on a workspace's task.create idempotency map. Older keys are evicted, so\n// the dedup window is bounded rather than growing unbounded in a long-lived\n// workspace; a redelivery beyond this many intervening creates is not deduped.\nconst MAX_IDEMPOTENCY_KEYS = 10_000;\n\n// Largest envelope accepted, published in the workspace descriptor (SPEC S4.4).\nconst DEFAULT_MAX_ENVELOPE_BYTES = 1_048_576;\n\nexport interface CoordinatorOptions {\n deterministicIds?: boolean;\n deterministicClock?: boolean;\n enableChain?: boolean;\n requireSignatures?: boolean;\n enforceStepUp?: boolean;\n requireReadMembership?: boolean;\n /** Largest envelope accepted (default 1 MiB), published in the descriptor. */\n maxEnvelopeBytes?: number;\n onAudit?: AuditListener;\n onAutoEscalate?: (task: Task, to: ParticipantUri) => void;\n verifyOidcToken?: TokenVerifier;\n verifyVc?: CredentialVerifier;\n scittSubmitter?: ScittSubmitter;\n verifyScittReceipt?: ScittReceiptVerifier;\n routingPolicy?: RoutingPolicyFn;\n reviewDepthPolicy?: ReviewDepthPolicyFn;\n escalationPolicy?: EscalationPolicyFn;\n defaultProfiles?: string[];\n /**\n * Persistence backend. Defaults to MemoryStore (no persistence).\n * Pass SqliteStore or any other Store implementation to persist\n * workspaces between process restarts. The Coordinator calls\n * `store.load()` once during `start()` and `store.save()` after\n * every successful mutation.\n */\n store?: Store;\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\nfunction nowIso(clockMs?: number): string {\n const d = clockMs === undefined ? new Date() : new Date(clockMs);\n return d.toISOString().replace(/\\.(\\d{3})Z$/, \".$1Z\");\n}\n\nfunction missing(params: Record<string, unknown>, fields: string[]): string | null {\n for (const f of fields) if (!(f in params)) return f;\n return null;\n}\n\nfunction tagsError(p: Record<string, unknown>): { error: ReturnType<typeof rpcError> } | null {\n const tags = p.tags;\n if (tags !== undefined && (!Array.isArray(tags) || !tags.every((t) => typeof t === \"string\"))) {\n return { error: rpcError(E.PARAMS, \"tags must be a list of strings\") };\n }\n return null;\n}\n\nfunction linkHash(envelope: Envelope, prev: string): string {\n return sha256Hex(Buffer.concat([canonicalize(envelope), Buffer.from(prev, \"utf-8\")]));\n}\n\nfunction reviewRuleSupported(rule: string): boolean {\n if (rule === \"any_one_approves\" || rule === \"all_approve\") return true;\n if (rule.startsWith(\"quorum:\")) {\n const arg = rule.slice(\"quorum:\".length);\n return /^[0-9]+$/.test(arg) && parseInt(arg, 10) >= 1;\n }\n return false;\n}\n\nfunction reviewSatisfied(review: { requested_to: string[]; rule: string; decisions: { kind: string; reviewer: string }[] }): boolean {\n const approvers = new Set(review.decisions.filter(d => d.kind === \"approve\").map(d => d.reviewer));\n const rule = review.rule || \"any_one_approves\";\n if (rule === \"all_approve\") {\n // A broadcast-only review has no bounded reviewer set to wait on, so it\n // degrades to first-approve.\n const named = review.requested_to.filter(r => !(r.startsWith(\"workspace:\") || r.startsWith(\"group:\")));\n if (named.length === 0) return approvers.size >= 1;\n return named.every(r => approvers.has(r));\n }\n if (rule.startsWith(\"quorum:\")) return approvers.size >= parseInt(rule.slice(\"quorum:\".length), 10);\n return approvers.size >= 1; // any_one_approves (and the default)\n}\n\nfunction reply(env: Envelope, body: { result?: unknown; error?: { code: number; message: string; data?: unknown } }): Envelope {\n const out: Envelope = { jsonrpc: \"2.0\", id: env.id };\n if (body.error !== undefined) out.error = body.error;\n else out.result = body.result;\n return out;\n}\n\n// ============================================================\n// Handler type for profile modules\n// ============================================================\n\nexport type Handler = (params: Record<string, unknown>) => { result?: unknown; error?: { code: number; message: string; data?: unknown } };\n\n// ============================================================\n// Coordinator\n// ============================================================\n\nexport class Coordinator {\n readonly workspaces = new Map<WorkspaceId, Workspace>();\n readonly options: CoordinatorOptions;\n readonly ids: IdFactory;\n readonly store: Store;\n private wsVersions = new Map<WorkspaceId, number>();\n private clockMs?: number;\n private auditListeners: AuditListener[] = [];\n /** Method handler registry; profiles plug into this. */\n readonly handlers = new Map<string, Handler>();\n /** Custom lapse-check function (whisper/1.0). Set by the whisper profile. */\n checkWhisperLapses?: (workspaceId: string, now?: string) => Envelope[];\n /** Typed method facade. Defined via getter in the constructor. */\n readonly api!: CoordinatorApi;\n /** @internal cached facade instance */\n private _api?: CoordinatorApi;\n\n constructor(options: CoordinatorOptions = {}) {\n this.options = options;\n this.store = options.store ?? new MemoryStore();\n this.ids = new IdFactory(!!options.deterministicIds, 0n, 1_700_000_000_000);\n if (options.deterministicClock) this.clockMs = 1_700_000_000_000;\n if (options.onAudit) this.auditListeners.push(options.onAudit);\n\n this.registerCoreHandlers();\n this.registerProfileHandlers();\n\n // Lazily-initialised typed facade. Constructed on first access so\n // tests that don't use it pay nothing.\n Object.defineProperty(this, \"api\", {\n get: () => {\n if (!this._api) this._api = makeApi(this);\n return this._api;\n },\n enumerable: false,\n configurable: true,\n });\n\n // Rehydrate any persisted state synchronously. Async stores can\n // call `start()` instead; this fallback covers the common\n // synchronous Memory/Sqlite path with no async setup needed.\n try {\n const loaded = this.store.load();\n if (!(loaded instanceof Promise)) {\n this.applyRecords(loaded);\n }\n } catch {\n /* fall through; caller must invoke start() */\n }\n }\n\n /**\n * Asynchronously hydrate workspaces from the store. Required only for\n * stores whose `load()` returns a Promise. Idempotent.\n */\n async start(): Promise<void> {\n const records = await this.store.load();\n this.applyRecords(records);\n }\n\n private applyRecords(records: WorkspaceRecord[]): void {\n this.workspaces.clear();\n this.wsVersions.clear();\n for (const r of records) {\n this.restore([r.data]);\n this.wsVersions.set(r.id, r.version);\n }\n }\n\n /** Persist the current snapshot of one workspace to the store. */\n private persist(ws: Workspace): void {\n const next = (this.wsVersions.get(ws.id) ?? 0) + 1;\n this.wsVersions.set(ws.id, next);\n try {\n // snapshot() returns an array of all workspaces; we only need\n // this one, so slice it. Stores are per-workspace.\n const all = this.snapshot() as Array<Record<string, unknown>>;\n const data = all.find(w => w.id === ws.id);\n if (!data) return;\n const result = this.store.save({\n id: ws.id,\n data,\n version: next,\n updated_at: this.now(),\n });\n // Async stores: fire-and-forget; failures surface via process unhandled-rejection.\n // Sync stores: nothing to do.\n if (result instanceof Promise) {\n result.catch(() => { /* deliberately swallowed; stores should log */ });\n }\n } catch {\n // Persistence failures must not break dispatch. Audit listeners\n // can mirror the audit stream to a second sink for durability.\n }\n }\n\n // -- lifecycle -----------------------------------------------------\n\n now(): string {\n if (this.clockMs !== undefined) {\n this.clockMs += 1000;\n return nowIso(this.clockMs);\n }\n return nowIso();\n }\n\n onAudit(listener: AuditListener): () => void {\n this.auditListeners.push(listener);\n return () => {\n const i = this.auditListeners.indexOf(listener);\n if (i >= 0) this.auditListeners.splice(i, 1);\n };\n }\n\n /** Convenience: get a workspace by id, or undefined. */\n getWorkspace(id: WorkspaceId): Workspace | undefined {\n return this.workspaces.get(id);\n }\n\n // ----- authorisation preconditions -----\n\n /**\n * Assert that `sender` is a joined member of `ws`. Returns an error\n * fragment if not, else null. Every actor-action method runs this on\n * its `from` so a decision, completion, or review request can never\n * be attributed to a participant who never joined. See\n * SPECIFICATION.md S6.3 and the `unknown_participant` condition in\n * S13.3. (The published spec assigns -32403; the reference\n * implementations use NOT_AUTHORISED -32011 because -32403 already\n * denotes OIDC_TOKEN_INVALID in their private range. The spec/impl\n * error-table divergence is tracked separately.)\n */\n private requireMember(ws: Workspace, sender: unknown): { error: ReturnType<typeof rpcError> } | null {\n if (typeof sender !== \"string\" || !ws.members.has(sender)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not a workspace member: ${String(sender)}`) };\n }\n return null;\n }\n\n /**\n * Assert that `sender` was addressed in the task's review. Applied to\n * review-decision methods (decide.* and abstain.declare): to act on a\n * review you must be one of the reviewers it was addressed to (the\n * `to` set on review.request). Membership is the floor; this is the\n * eligibility ceiling for decisions. Returns an error fragment if not\n * eligible, else null.\n */\n private requireReviewer(task: Task, sender: unknown): { error: ReturnType<typeof rpcError> } | null {\n const review = task.review;\n if (!review || !review.requested_to || review.requested_to.length === 0) {\n // No recorded reviewer set: fall back to the membership floor,\n // which the caller has already enforced.\n return null;\n }\n // A broadcast-scoped reviewer (workspace:/group: URI) is satisfied by\n // any workspace member; the membership floor already passed. Note the\n // coordinator does not model group membership: a group: target means\n // \"any member\", not \"any member of that group\" (deployments needing\n // true group restriction enforce it externally). Keeps the documented\n // `to: workspace:<id>` broadcast pattern working.\n if (review.requested_to.some((r) => typeof r === \"string\" && (r.startsWith(\"workspace:\") || r.startsWith(\"group:\")))) {\n return null;\n }\n if (typeof sender !== \"string\" || !review.requested_to.includes(sender as ParticipantUri)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not an addressed reviewer for this task: ${String(sender)}`) };\n }\n return null;\n }\n\n /** Serialise all workspaces to a JSON-safe structure for persistence. */\n snapshot(): unknown {\n const out: Array<Record<string, unknown>> = [];\n for (const ws of this.workspaces.values()) {\n out.push({\n id: ws.id,\n created: ws.created,\n state: ws.state,\n profiles: ws.profiles,\n mode: ws.mode,\n mode_ceiling: ws.mode_ceiling,\n routing_policy_uri: ws.routing_policy_uri,\n step_up_window_sec: ws.step_up_window_sec,\n min_acr: ws.min_acr,\n members: Array.from(ws.members.values()),\n tasks: Array.from(ws.tasks.values()),\n overrides: Array.from(ws.overrides.values()),\n whispers: Array.from(ws.whispers.values()),\n deliberations: Array.from(ws.deliberations.values()),\n handoffs: Array.from(ws.handoffs.values()),\n snapshots: Array.from(ws.snapshots.values()),\n route_decisions: Array.from(ws.route_decisions.values()),\n idempotency_keys: ws.idempotency_keys,\n audit: ws.audit,\n chain_head: ws.chain_head,\n chain_enabled: ws.chain_enabled,\n });\n }\n return out;\n }\n\n /** Restore from a snapshot produced by ``snapshot()``. Replaces\n * any existing in-memory workspaces. */\n restore(data: unknown): void {\n this.workspaces.clear();\n if (!Array.isArray(data)) return;\n for (const w of data as Array<Record<string, unknown>>) {\n const ws: Workspace = {\n id: w.id as WorkspaceId,\n created: w.created as string,\n state: (w.state as Workspace[\"state\"]) ?? \"active\",\n profiles: (w.profiles as string[]) ?? [],\n mode: (w.mode as Mode) ?? \"trial\",\n mode_ceiling: (w.mode_ceiling as Mode) ?? \"production\",\n routing_policy_uri: w.routing_policy_uri as string | undefined,\n step_up_window_sec: (w.step_up_window_sec as number) ?? 300,\n min_acr: w.min_acr as string | undefined,\n members: new Map(),\n tasks: new Map(),\n overrides: new Map(),\n whispers: new Map(),\n deliberations: new Map(),\n handoffs: new Map(),\n snapshots: new Map(),\n route_decisions: new Map(),\n idempotency_keys: (w.idempotency_keys as Record<string, string>) ?? {},\n audit: (w.audit as AuditEntry[]) ?? [],\n chain_head: w.chain_head as string | undefined,\n chain_enabled: !!w.chain_enabled,\n };\n for (const m of (w.members as Member[]) ?? []) {\n // Defensive: ensure required collections exist even on older snapshots.\n if (!Array.isArray(m.keys)) m.keys = [];\n if (m.paused === undefined) m.paused = false;\n ws.members.set(m.uri, m);\n }\n for (const t of (w.tasks as Task[]) ?? []) ws.tasks.set(t.id, t);\n for (const o of (w.overrides as OverrideArtefact[]) ?? []) ws.overrides.set(o.id, o);\n // The dynamic profile collections may not be present on legacy snapshots.\n for (const x of (w.whispers as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.whispers.set(x.id, x as never);\n for (const x of (w.deliberations as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.deliberations.set(x.id, x as never);\n for (const x of (w.handoffs as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.handoffs.set(x.id, x as never);\n for (const x of (w.snapshots as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.snapshots.set(x.id, x as never);\n for (const x of (w.route_decisions as Array<{ id: string } & Record<string, unknown>>) ?? [])\n ws.route_decisions.set(x.id, x as never);\n this.workspaces.set(ws.id, ws);\n }\n }\n\n // -- dispatch ------------------------------------------------------\n\n dispatch(envelope: Envelope): Envelope {\n if (!isValidEnvelope(envelope) || !envelope.method) {\n return reply(envelope, { error: rpcError(E.REQUEST, \"Invalid JSON-RPC 2.0 request\") });\n }\n const maxBytes = this.options.maxEnvelopeBytes ?? DEFAULT_MAX_ENVELOPE_BYTES;\n let size = 0;\n try { size = canonicalize(envelope).length; } catch { /* not canonicalisable; rejected by the ingress check below */ }\n if (size > maxBytes) {\n return reply(envelope, { error: rpcError(E.REQUEST,\n `Envelope exceeds max_envelope_bytes (${size} > ${maxBytes})`) });\n }\n const method = envelope.method;\n // JSON-RPC params, when present, must be a structured value (object).\n // CHAP methods use by-name params; reject non-object params cleanly as\n // Invalid params for parity with the Python reference.\n const rawParams = envelope.params;\n if (\n rawParams !== undefined &&\n rawParams !== null &&\n (typeof rawParams !== \"object\" || Array.isArray(rawParams))\n ) {\n return reply(envelope, { error: rpcError(E.PARAMS, \"Invalid params: expected an object\") });\n }\n const params = (rawParams ?? {}) as Record<string, unknown>;\n\n // security-signed/1.0: verify top-level sig if required.\n // participant.join and workspace.create are bootstrap operations that\n // run before any signing key is registered for the actor, so they cannot\n // be signature-verified; every other method must verify.\n if (this.options.requireSignatures && method !== \"participant.join\" && method !== \"workspace.create\") {\n const sigErr = this.verifySignature(envelope);\n if (sigErr) return reply(envelope, { error: sigErr });\n if (method === \"participant.rotate_key\") {\n const signingKid = (envelope.sig as string).split(\":\")[1];\n const oldKid = params.old_kid as string | undefined;\n if (oldKid !== undefined && signingKid !== oldKid) {\n return reply(envelope, { error: rpcError(E.SIG_ROTATION_KEY_MISMATCH,\n \"Rotation must be signed with the old key\") });\n }\n }\n }\n\n // identity-oidc/1.0: step-up freshness on privileged methods.\n if (this.options.enforceStepUp && PRIVILEGED_METHODS.has(method)) {\n const stale = this.checkStepUp(params);\n if (stale) return reply(envelope, { error: stale });\n }\n\n // control/1.0 and deliberation/1.0: these operations are privileged and\n // MUST be performed by a workspace member. Control is the governance\n // \"emergency brake\"; deliberation open/close set the vote parameters and\n // finalize the tally. Without this floor a non-member could resume a\n // paused workspace, raise the mode ceiling, or open and close a\n // deliberation to finalize an outcome early. (The per-voter eligibility\n // check in deliberate.vote is separate and still applies. A stricter role\n // gate than membership is layered on top via an identity-* profile.)\n if (method.startsWith(\"control.\") || method.startsWith(\"deliberate.\") || method.startsWith(\"handoff.\") || method.startsWith(\"whisper.\")) {\n const wsId = params.workspace as string | undefined;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n if (ws) {\n const notMember = this.requireMember(ws, params.from);\n if (notMember) return reply(envelope, { error: notMember.error });\n }\n }\n\n // control/1.0 workspace-paused gate (S6 -32063).\n const exempt = new Set([\"workspace.create\", \"workspace.describe\",\n \"control.resume\", \"audit.read\",\n \"participant.join\", \"participant.leave\"]);\n if (!exempt.has(method)) {\n const wsId = params.workspace as string | undefined;\n if (typeof wsId === \"string\") {\n const ws = this.workspaces.get(wsId);\n if (ws && ws.state === \"paused\") {\n return reply(envelope, { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Workspace ${wsId} is paused`) });\n }\n }\n }\n\n // task.create idempotency: a repeat carrying a seen idempotency_key returns\n // the original task rather than creating (or recording) a duplicate -- safe\n // for at-least-once redelivery.\n if (method === \"task.create\") {\n const wsId = params.workspace;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n const key = params.idempotency_key;\n if (ws && typeof key === \"string\") {\n const existingId = ws.idempotency_keys[key];\n const task = existingId ? ws.tasks.get(existingId) : undefined;\n if (task) return reply(envelope, { result: { task_id: existingId, state: task.state } });\n }\n }\n\n const handler = this.handlers.get(method);\n if (!handler) {\n return reply(envelope, { error: rpcError(E.METHOD, `Unknown method: ${method}`) });\n }\n\n try {\n canonicalize(envelope);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return reply(envelope, { error: rpcError(E.PARAMS, msg) });\n }\n\n let out: { result?: unknown; error?: { code: number; message: string; data?: unknown } };\n try {\n out = handler(params);\n } catch (e) {\n // Keep the wire message generic; a handler exception may carry internal\n // detail that should not be disclosed to callers. Specifics stay in the\n // data field for operators.\n const msg = e instanceof Error ? e.message : String(e);\n return reply(envelope, { error: rpcError(E.INTERNAL, \"Internal error\", { detail: msg }) });\n }\n if (out.error) return reply(envelope, { error: out.error });\n\n // Record audit on success\n const wsId = params.workspace as string | undefined;\n if (typeof wsId === \"string\" && !READ_ONLY_METHODS.has(method)) {\n const ws = this.workspaces.get(wsId);\n if (ws) this.recordAudit(ws, envelope);\n }\n return reply(envelope, { result: out.result });\n }\n\n // -- audit ---------------------------------------------------------\n\n recordAudit(ws: Workspace, envelope: Envelope): void {\n const entry: AuditEntry = {\n seq: ws.audit.length,\n arrived: this.now(),\n envelope: JSON.parse(JSON.stringify(envelope)) as Envelope,\n };\n if (ws.chain_enabled || this.options.enableChain) {\n const prev = ws.chain_head ?? ZERO_HASH;\n entry.prev_hash = prev;\n ws.chain_head = linkHash(entry.envelope, prev);\n }\n ws.audit.push(entry);\n for (const l of this.auditListeners) {\n try { l(ws, entry); } catch { /* listeners never break dispatch */ }\n }\n // Persistence: only meaningful when a non-Memory store is configured;\n // MemoryStore.save() is a no-op for the dispatcher's perspective.\n this.persist(ws);\n }\n\n // -- signature verification (security-signed/1.0) -----------------\n\n private verifySignature(envelope: Envelope): { code: number; message: string; data?: unknown } | null {\n const sig = envelope.sig;\n if (!sig || typeof sig !== \"string\") {\n return rpcError(E.SIG_VERIFY_FAILED, \"Missing top-level `sig` field\");\n }\n const parts = sig.split(\":\");\n if (parts.length !== 3 || parts[0] !== \"ed25519\") {\n return rpcError(E.SIG_VERIFY_FAILED, \"Malformed signature tag\");\n }\n const kid = parts[1];\n const params = (envelope.params ?? {}) as Record<string, unknown>;\n const sender = params.from as string | undefined;\n const wsId = params.workspace as string | undefined;\n const ts = (params.ts as string | undefined) ?? this.now();\n // Fail closed: a signature is present and requireSignatures is on, so it\n // must verify. If we cannot resolve the context needed to verify it,\n // reject rather than skip -- a signature we cannot check must never be\n // treated as valid.\n if (!sender || !wsId) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: missing from/workspace\");\n }\n const ws = this.workspaces.get(wsId);\n if (!ws) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: unknown workspace\");\n }\n const member = ws.members.get(sender);\n if (!member) return rpcError(E.SIG_KEY_NOT_FOUND, `No member: ${sender}`);\n\n // Revocation is present-tense: a revoked key must be rejected for any\n // live request regardless of the envelope's self-asserted `ts`. Checking\n // against `ts` alone lets a holder of a revoked key backdate `ts` to\n // before the revocation and still be accepted. Use the coordinator's\n // trusted clock for the revocation decision.\n const now = this.now();\n if (member.keys.some(k => k.kid === kid && k.revoked_at !== undefined && now >= k.revoked_at)) {\n return rpcError(E.SIG_KEY_REVOKED, `Key ${kid} is revoked`);\n }\n // Expiry is present-tense for the same reason: a rotated-out key\n // (valid_until set to the rotation time, but never explicitly revoked) must\n // not sign live requests. Selecting it by the self-asserted `ts` alone lets\n // its holder backdate `ts` to before valid_until and keep using it. Judge\n // expiry by the trusted clock.\n if (member.keys.some(k => k.kid === kid && k.valid_until !== undefined && now >= k.valid_until)) {\n return rpcError(E.SIG_KEY_NOT_FOUND, `Key ${kid} is no longer valid`);\n }\n\n const key = this.lookupKey(member, kid, ts);\n if (!key) {\n const revoked = member.keys.find(k => k.kid === kid && k.revoked_at);\n if (revoked) return rpcError(E.SIG_KEY_REVOKED, `Key ${kid} is revoked`);\n return rpcError(E.SIG_KEY_NOT_FOUND, `No key ${kid} valid at ${ts} for ${sender}`);\n }\n\n // Verify\n try {\n const stripped: Envelope = JSON.parse(JSON.stringify(envelope));\n delete stripped.sig;\n const canonical = canonicalize(stripped);\n const pub = publicKeyFromJwk(key.jwk);\n if (!verifyEnvelope(canonical, sig, pub)) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Signature failed verification\");\n }\n return null;\n } catch {\n // An exception here (malformed key or signature bytes) means the\n // signature cannot be verified: fail closed with the same generic code\n // as the Python reference, and do not leak the exception detail.\n return rpcError(E.SIG_VERIFY_FAILED, \"Signature failed verification\");\n }\n }\n\n /** Lookup the key valid for a given participant at a given time. */\n lookupKey(member: Member, kid: string, ts: string): KeyRecord | null {\n for (const k of member.keys) {\n if (k.kid !== kid) continue;\n if (k.revoked_at !== undefined && ts >= k.revoked_at) continue;\n if (ts < k.valid_from) continue;\n if (k.valid_until !== undefined && ts >= k.valid_until) continue;\n return k;\n }\n return null;\n }\n\n // -- step-up (identity-oidc/1.0) -----------------------------------\n\n private checkStepUp(params: Record<string, unknown>): { code: number; message: string; data?: unknown } | null {\n const wsId = params.workspace as string | undefined;\n const sender = params.from as string | undefined;\n if (!wsId || !sender) return null;\n const ws = this.workspaces.get(wsId);\n if (!ws) return null;\n const member = ws.members.get(sender);\n if (!member) return null;\n // Step-up applies to OIDC actors -- humans, or any member with an OIDC\n // binding. Agents and services authenticate out of band (SPIFFE/X.509),\n // so they are not held to an auth_time window here.\n if (member.type !== \"human\" && member.oidc_sub === undefined) return null;\n if (member.oidc_auth_time === undefined) {\n return rpcError(E.OIDC_STEP_UP_REQUIRED, \"Step-up authentication required\", {\n window_sec: ws.step_up_window_sec,\n });\n }\n const nowSec = Math.floor(Date.now() / 1000);\n const age = nowSec - member.oidc_auth_time;\n if (age > ws.step_up_window_sec) {\n return rpcError(E.OIDC_STEP_UP_REQUIRED, \"Step-up authentication required\", {\n window_sec: ws.step_up_window_sec, age_sec: age,\n });\n }\n if (ws.min_acr !== undefined && member.oidc_acr !== ws.min_acr) {\n return rpcError(E.OIDC_STEP_UP_REQUIRED, \"Step-up required: acr below the workspace minimum\", {\n required_acr: ws.min_acr, acr: member.oidc_acr,\n });\n }\n return null;\n }\n\n // ==========================================================\n // Registration\n // ==========================================================\n\n private registerCoreHandlers(): void {\n this.handlers.set(\"workspace.create\", p => this.opWorkspaceCreate(p));\n this.handlers.set(\"workspace.describe\", p => this.opWorkspaceDescribe(p));\n this.handlers.set(\"workspace.set_profiles\", p => this.opWorkspaceSetProfiles(p));\n this.handlers.set(\"participant.join\", p => this.opParticipantJoin(p));\n this.handlers.set(\"participant.leave\", p => this.opParticipantLeave(p));\n this.handlers.set(\"task.create\", p => this.opTaskCreate(p));\n this.handlers.set(\"task.update\", p => this.opTaskUpdate(p));\n this.handlers.set(\"task.complete\", p => this.opTaskComplete(p));\n this.handlers.set(\"audit.read\", p => this.opAuditRead(p));\n this.handlers.set(\"review.request\", p => this.opReviewRequest(p));\n this.handlers.set(\"decide.approve\", p => this.opDecide(p, \"approve\"));\n this.handlers.set(\"decide.reject\", p => this.opDecide(p, \"reject\"));\n this.handlers.set(\"decide.override\", p => this.opDecideOverride(p));\n this.handlers.set(\"abstain.declare\", p => this.opAbstainDeclare(p));\n this.handlers.set(\"escalate.raise\", p => this.opEscalateRaise(p));\n }\n\n private registerProfileHandlers(): void {\n // Profiles register themselves by mutating this.handlers\n registerWhisper(this);\n registerDeliberation(this);\n registerHandoff(this);\n registerControl(this);\n registerRouting(this);\n registerSecuritySigned(this);\n registerAuditScitt(this);\n }\n\n // ==========================================================\n // Core method handlers\n // ==========================================================\n\n private opWorkspaceCreate(p: Record<string, unknown>): ReturnType<Handler> {\n const id = (p.workspace as string) || this.ids.workspaceId();\n if (typeof id !== \"string\") return { error: rpcError(E.PARAMS, \"workspace must be a string id\") };\n if (this.workspaces.has(id)) return { error: rpcError(E.PARAMS, `workspace already exists: ${id}`) };\n const profiles: string[] = Array.isArray(p.profiles) ? [...(p.profiles as string[])] : [...(this.options.defaultProfiles ?? [\"core/1.0\", \"review/1.0\"])];\n const chainEnabled = profiles.includes(\"audit-scitt/1.0\") || !!this.options.enableChain;\n const ws: Workspace = {\n id,\n created: this.now(),\n state: \"active\",\n profiles,\n mode: (p.mode as Mode) ?? \"trial\",\n mode_ceiling: (p.mode_ceiling as Mode) ?? \"production\",\n routing_policy_uri: p.routing_policy_uri as string | undefined,\n step_up_window_sec: typeof p.step_up_window_sec === \"number\" ? p.step_up_window_sec : 300,\n min_acr: p.min_acr as string | undefined,\n members: new Map(),\n tasks: new Map(),\n overrides: new Map(),\n whispers: new Map(),\n deliberations: new Map(),\n handoffs: new Map(),\n snapshots: new Map(),\n route_decisions: new Map(),\n idempotency_keys: {},\n audit: [],\n chain_enabled: chainEnabled,\n chain_head: chainEnabled ? ZERO_HASH : undefined,\n };\n this.workspaces.set(id, ws);\n return { result: { workspace: id, created: ws.created } };\n }\n\n private opWorkspaceDescribe(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, `Unknown workspace: ${p.workspace}`) };\n if (this.options.requireReadMembership) {\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n }\n return { result: {\n id: ws.id,\n created: ws.created,\n state: ws.state,\n mode: ws.mode,\n mode_ceiling: ws.mode_ceiling,\n max_envelope_bytes: this.options.maxEnvelopeBytes ?? DEFAULT_MAX_ENVELOPE_BYTES,\n step_up_window_sec: ws.step_up_window_sec,\n profiles: ws.profiles,\n members: Array.from(ws.members.values()).map(memberToDict),\n audit_count: ws.audit.length,\n task_count: ws.tasks.size,\n override_count: ws.overrides.size,\n evidence_head: ws.chain_head,\n ...(ws.routing_policy_uri ? { routing_policy_uri: ws.routing_policy_uri } : {}),\n }};\n }\n\n private opWorkspaceSetProfiles(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"profiles\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n if (ws.members.get(p.from as string)!.role !== \"admin\") {\n return { error: rpcError(E.NOT_AUTHORISED, \"workspace.set_profiles requires the admin role\") };\n }\n const newProfiles = [...(p.profiles as string[])];\n if (!newProfiles.some(pr => pr.startsWith(\"core/\"))) newProfiles.push(\"core/1.0\");\n ws.profiles = newProfiles;\n if (newProfiles.includes(\"audit-scitt/1.0\") && !ws.chain_enabled) {\n ws.chain_enabled = true;\n ws.chain_head = ZERO_HASH;\n }\n return { result: { profiles: ws.profiles } };\n }\n\n private opParticipantJoin(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"type\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n let ws = this.workspaces.get(p.workspace as string);\n if (!ws) {\n const create = this.opWorkspaceCreate({ workspace: p.workspace });\n if (create.error) return create;\n ws = this.workspaces.get(p.workspace as string)!;\n }\n const uri = p.from as ParticipantUri;\n const now = this.now();\n\n const member: Member = {\n uri,\n type: p.type as Member[\"type\"],\n role: (p.role as string) || \"participant\",\n joined: now,\n display_name: p.display_name as string | undefined,\n capabilities: p.capabilities as Record<string, unknown> | undefined,\n scopes: p.scopes as string[] | undefined,\n keys: [],\n paused: false,\n };\n\n // identity-oidc/1.0\n if (this.options.verifyOidcToken && typeof p.oidc_token === \"string\") {\n const claims = this.options.verifyOidcToken(p.oidc_token);\n if (claims === null) return { error: rpcError(E.OIDC_TOKEN_INVALID, \"OIDC token invalid\") };\n member.oidc_sub = claims.sub as string | undefined;\n const at = claims.auth_time;\n if (typeof at === \"number\") member.oidc_auth_time = at;\n member.oidc_acr = claims.acr as string | undefined;\n const cnf = claims.cnf as Record<string, unknown> | undefined;\n const cnfJwk = cnf?.jwk as Record<string, unknown> | undefined;\n if (cnfJwk && typeof cnfJwk.kid === \"string\") {\n member.keys.push({ jwk: cnfJwk as unknown as KeyRecord[\"jwk\"], kid: cnfJwk.kid as string, valid_from: now });\n }\n }\n // identity-vc/1.0\n if (this.options.verifyVc && typeof p.vc_presentation === \"object\" && p.vc_presentation !== null) {\n const subject = this.options.verifyVc(p.vc_presentation as Record<string, unknown>);\n if (subject === null) return { error: rpcError(E.VC_VP_INVALID, \"VC presentation invalid\") };\n member.vc_holder = (subject.holder as string | undefined) ?? (subject.id as string | undefined);\n const vpJwk = subject.cnf_jwk as Record<string, unknown> | undefined;\n if (vpJwk && typeof vpJwk.kid === \"string\") {\n member.keys.push({ jwk: vpJwk as unknown as KeyRecord[\"jwk\"], kid: vpJwk.kid as string, valid_from: now });\n }\n }\n\n const attested = [...member.keys];\n\n // Self-asserted JWKs are ignored for an identity-bound participant: the\n // verifier-pinned cnf.jwk / vp_jwk is the signing key (proof of possession).\n const jwks = p.jwks as { keys?: Array<{ kid: string; [k: string]: unknown }> } | undefined;\n if (jwks?.keys && attested.length === 0) {\n for (const j of jwks.keys) {\n if (j.kid && !member.keys.some(k => k.kid === j.kid)) {\n member.keys.push({ jwk: j as unknown as KeyRecord[\"jwk\"], kid: j.kid, valid_from: now });\n }\n }\n }\n\n const existing = ws.members.get(uri);\n if (existing) {\n if (member.oidc_sub !== undefined) existing.oidc_sub = member.oidc_sub;\n if (member.oidc_auth_time !== undefined) existing.oidc_auth_time = member.oidc_auth_time;\n if (member.oidc_acr !== undefined) existing.oidc_acr = member.oidc_acr;\n if (member.vc_holder !== undefined) existing.vc_holder = member.vc_holder;\n for (const k of attested) {\n if (!existing.keys.some(x => x.kid === k.kid)) existing.keys.push(k);\n }\n return { result: { joined: true, as: uri } };\n }\n ws.members.set(uri, member);\n return { result: { joined: true, as: uri } };\n }\n\n private opParticipantLeave(p: Record<string, unknown>): ReturnType<Handler> {\n // Self-removal: deletes the caller's own `from`. Under requireSignatures the\n // signature binds `from`, so a member can only remove itself; evicting\n // another member is an admin operation, not this. Unsigned, a spoofed\n // `from` is the transport's responsibility.\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n ws.members.delete(p.from as string);\n return { result: { left: true } };\n }\n\n private opTaskCreate(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"kind\", \"input\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const assignee = (p.assignee as string) || (p.to as string);\n if (!assignee || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"Assignee not in workspace\") };\n }\n if (ws.members.get(assignee)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${assignee} is paused`) };\n }\n\n // modes/1.0 ceiling check\n const requestedMode = ((p.mode as Mode) || ws.mode);\n if (!modeLE(requestedMode, ws.mode_ceiling)) {\n return { error: rpcError(E.MODE_CEILING_EXCEEDED,\n `Requested mode ${requestedMode} exceeds ceiling ${ws.mode_ceiling}`) };\n }\n\n const taskId = this.ids.taskId();\n const now = this.now();\n const task: Task = {\n id: taskId,\n kind: p.kind as string,\n state: \"created\",\n assignee,\n delegator: p.from as ParticipantUri,\n input: p.input as Record<string, unknown>,\n created_at: now,\n updated_at: now,\n deadline: p.deadline as string | undefined,\n mode: requestedMode,\n routing_hints: p.routing_hints as Task[\"routing_hints\"],\n history: [{ ts: now, from: p.from as ParticipantUri, state: \"created\" }],\n paused: false,\n };\n\n // modes/1.0: trial mode forces review\n // modes/1.0: trial forces review, but only when the workspace opted into\n // modes/1.0. mode is inert without the profile.\n if (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && task.mode === \"trial\") task.review_required = true;\n else if (\"review_required\" in p) task.review_required = !!p.review_required;\n\n ws.tasks.set(taskId, task);\n if (typeof p.idempotency_key === \"string\") {\n ws.idempotency_keys[p.idempotency_key] = taskId;\n const keys = Object.keys(ws.idempotency_keys);\n if (keys.length > MAX_IDEMPOTENCY_KEYS) delete ws.idempotency_keys[keys[0]];\n }\n return { result: { task_id: taskId, state: \"created\" } };\n }\n\n private opTaskUpdate(p: Record<string, unknown>): ReturnType<Handler> {\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const newState = p.state as Task[\"state\"];\n const legal: Record<string, string[]> = {\n created: [\"in_progress\", \"declined\", \"paused\"],\n in_progress: [\"in_progress\", \"completed\", \"declined\", \"review_requested\", \"paused\"],\n review_requested: [\"in_progress\"],\n paused: [\"in_progress\", \"cancelled\"],\n };\n if (!legal[task.state]?.includes(newState)) {\n return { error: rpcError(E.PARAMS, `Illegal transition ${task.state} -> ${newState}`) };\n }\n task.state = newState;\n task.updated_at = this.now();\n task.history.push({\n ts: task.updated_at, from: p.from as ParticipantUri,\n state: newState, note: p.progress_note as string | undefined,\n });\n return { result: { state: newState } };\n }\n\n private opTaskComplete(p: Record<string, unknown>): ReturnType<Handler> {\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n // Completion is only legal from an active, non-terminal, non-paused state.\n // An allowlist (rather than a denylist of terminal states) is safer: any\n // state not listed -- cancelled, superseded, paused, already\n // completed/declined, abstained, escalated -- is rejected, so completion\n // can neither revive a terminated task nor bypass a pause.\n if (task.state !== \"created\" && task.state !== \"in_progress\") {\n return { error: rpcError(E.PARAMS, `Cannot complete task in state: ${task.state}`) };\n }\n // review/1.0 S3.1: task.complete on a task whose review is required opens a\n // review implicitly rather than completing. The submitted output becomes the\n // artefact under review; only a reviewer decision (decide.*) then takes the\n // task to completed. Without this a review_required task would reach\n // completed with unreviewed output and no decision.\n if (task.review_required) {\n const now = this.now();\n task.pending_artefact = p.output;\n if (!task.review) {\n // The producer must not satisfy its own review, so the implicit review\n // is addressed to the other members, excluding the caller and the\n // assignee. With nobody eligible there is no independent reviewer, so\n // refuse rather than open a review only its author could approve. (An\n // explicit review.request keeps its own `to`.)\n const producer = p.from as string;\n const eligible = [...ws.members.keys()].filter(uri => uri !== producer && uri !== task.assignee);\n if (eligible.length === 0) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"Task requires review but has no eligible reviewer (needs a member other than its assignee and completer)\") };\n }\n task.review = { requested_at: now, requested_to: eligible as ParticipantUri[], rule: \"any_one_approves\", decisions: [] };\n }\n task.state = \"review_requested\";\n task.updated_at = now;\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: \"review_requested\",\n note: \"review required; opened on task.complete\" });\n return { result: { state: \"review_requested\", review_id: task.id } };\n }\n task.output = p.output;\n if (typeof p.confidence === \"number\" || typeof p.confidence === \"string\") task.confidence = p.confidence;\n task.state = \"completed\";\n task.updated_at = this.now();\n task.history.push({ ts: task.updated_at, from: p.from as ParticipantUri, state: \"completed\" });\n return { result: { state: \"completed\" } };\n }\n\n private opAuditRead(p: Record<string, unknown>): ReturnType<Handler> {\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n if (this.options.requireReadMembership) {\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n }\n const range = (p.range as { from_seq?: number; to_seq?: number } | undefined) ?? {};\n const filter = (p.filter as { method?: string; from?: string; task_id?: string } | undefined) ?? {};\n const fromSeq = range.from_seq ?? 0;\n const toSeq = range.to_seq ?? ws.audit.length;\n const out: unknown[] = [];\n for (const entry of ws.audit.slice(fromSeq, toSeq)) {\n const ep = (entry.envelope.params ?? {}) as Record<string, unknown>;\n if (filter.method && entry.envelope.method !== filter.method) continue;\n if (filter.from && ep.from !== filter.from) continue;\n if (filter.task_id && ep.task_id !== filter.task_id) continue;\n const item: Record<string, unknown> = {\n seq: entry.seq, arrived: entry.arrived, envelope: entry.envelope,\n };\n if (entry.prev_hash) item.prev_hash = entry.prev_hash;\n out.push(item);\n }\n return { result: { entries: out, next_seq: toSeq } };\n }\n\n // ==========================================================\n // review/1.0 handlers\n // ==========================================================\n\n private opReviewRequest(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\", \"artefact\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n const to = p.to;\n const reviewers: string[] = Array.isArray(to) ? (to as string[]) : typeof to === \"string\" ? [to] : [];\n if (!reviewers.length) return { error: rpcError(E.PARAMS, \"review.request needs 'to'\") };\n const now = this.now();\n const rule = (p.rule as string) || \"any_one_approves\";\n if (!reviewRuleSupported(rule)) {\n return { error: rpcError(E.PARAMS, `Unsupported review rule ${JSON.stringify(rule)}: review/1.0 supports any_one_approves, all_approve, quorum:<n>`) };\n }\n\n // A review already open on this task. Replacing the artefact underneath\n // it would let a reviewer decide on content they never saw, and would\n // discard decisions already cast while their envelopes remain in the\n // audit log, so a quorum could appear to have been assembled across two\n // different artefacts. Re-requesting the *same* artefact is a different\n // thing: it widens the reviewer set on an open review, which is legitimate\n // and preserves what has been decided so far.\n if (task.state === \"review_requested\" && task.review) {\n if (contentHash(task.pending_artefact) !== contentHash(p.artefact)) {\n return { error: rpcError(\n E.REVIEW_ALREADY_OPEN,\n \"A review is already open on this task with different content. \" +\n \"Decide, abstain, escalate or cancel it before requesting review of a new artefact.\",\n ) };\n }\n if (rule !== task.review.rule) {\n return { error: rpcError(\n E.REVIEW_ALREADY_OPEN,\n `Cannot change the decision rule of an open review (currently ${task.review.rule})`,\n ) };\n }\n // Union, preserving order and the decisions already recorded.\n for (const r of reviewers) {\n if (!task.review.requested_to.includes(r)) task.review.requested_to.push(r);\n }\n if (p.deadline !== undefined) task.review.deadline = p.deadline as string;\n task.updated_at = now;\n return { result: {\n state: \"review_requested\",\n review_id: task.id,\n amended: true,\n requested_to: [...task.review.requested_to],\n } };\n }\n\n task.state = \"review_requested\";\n task.updated_at = now;\n task.review = {\n requested_at: now,\n requested_to: reviewers,\n rule,\n deadline: p.deadline as string | undefined,\n decisions: [],\n };\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: \"review_requested\" });\n task.pending_artefact = p.artefact;\n return { result: { state: \"review_requested\", review_id: task.id } };\n }\n\n /**\n * Verify an optional `approved_artefact_digest` against the artefact under\n * review (review/1.0 S3.2).\n *\n * The digest sits in params, so it is inside whatever the envelope signature\n * covers: the decision then attests the content the reviewer saw rather than\n * a task reference, and a relying party can check it without trusting the\n * Coordinator that produced it. Absent, behaviour is exactly as before.\n *\n * On mismatch nothing is recorded and no state changes, so a client that\n * computes the wrong digest refuses only its own decision.\n */\n private checkArtefactDigest(p: Record<string, unknown>, task: Task): ReturnType<Handler> | null {\n const declared = p.approved_artefact_digest;\n if (declared === undefined || declared === null) return null;\n if (typeof declared !== \"string\") {\n return { error: rpcError(E.PARAMS, \"approved_artefact_digest must be a string\") };\n }\n if (task.pending_artefact === undefined) {\n return { error: rpcError(E.PARAMS, \"No artefact under review to bind a digest to\") };\n }\n const actual = contentHash(task.pending_artefact);\n if (declared !== actual) {\n return { error: rpcError(\n E.SIG_ARTEFACT_DIGEST_MISMATCH,\n \"approved_artefact_digest does not match the artefact under review\",\n { declared, actual },\n ) };\n }\n return null;\n }\n\n private opDecide(p: Record<string, unknown>, kind: \"approve\" | \"reject\"): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const badTags = tagsError(p);\n if (badTags) return badTags;\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"review_requested\") {\n return { error: rpcError(E.NOT_REVIEWABLE, `Task not awaiting review: ${task.state}`) };\n }\n const notReviewer = this.requireReviewer(task, p.from);\n if (notReviewer) return notReviewer;\n const digestError = this.checkArtefactDigest(p, task);\n if (digestError) return digestError;\n const now = this.now();\n task.review!.decisions.push({\n reviewer: p.from as ParticipantUri,\n kind,\n ts: now,\n comment: p.comment as string | undefined,\n tags: p.tags as string[] | undefined,\n });\n if (kind === \"approve\") {\n // Complete only when the rule's approval predicate is met; otherwise the\n // approval is recorded and the task stays review_requested.\n if (reviewSatisfied(task.review!)) {\n task.output = task.pending_artefact;\n task.state = \"completed\";\n }\n } else {\n task.state = p.request_revision ? \"in_progress\" : \"declined\";\n }\n task.updated_at = now;\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: task.state });\n return { result: { state: task.state } };\n }\n\n private opDecideOverride(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\", \"diff\", \"rationale\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const badTags = tagsError(p);\n if (badTags) return badTags;\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"review_requested\") {\n return { error: rpcError(E.NOT_REVIEWABLE, `Task not awaiting review: ${task.state}`) };\n }\n const notReviewer = this.requireReviewer(task, p.from);\n if (notReviewer) return notReviewer;\n const digestError = this.checkArtefactDigest(p, task);\n if (digestError) return digestError;\n // The override is of the artefact under review; use the coordinator's\n // record, not a caller-supplied \"before\" that could be fabricated.\n const base = task.pending_artefact;\n if (base === undefined) return { error: rpcError(E.PARAMS, \"No base artefact for override\") };\n let applied: unknown;\n try {\n applied = applyJsonPatch(base, p.diff as never);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { error: rpcError(E.PATCH_FAILED, msg) };\n }\n const now = this.now();\n const id = this.ids.artefactId();\n const override: OverrideArtefact = {\n id,\n task_id: task.id,\n reviewer: p.from as ParticipantUri,\n based_on_artefact: base,\n diff: p.diff as never,\n result: applied,\n rationale: p.rationale as string,\n tags: (p.tags as string[]) ?? [],\n policy_refs: (p.policy_refs as string[]) ?? [],\n ts: now,\n logical_id: p.logical_id as string | undefined,\n instance_id: p.instance_id as string | undefined,\n intent_preserved: p.intent_preserved as boolean | undefined,\n };\n ws.overrides.set(id, override);\n task.review!.decisions.push({\n reviewer: p.from as ParticipantUri,\n kind: \"override\",\n ts: now,\n tags: override.tags,\n override_artefact_id: id,\n });\n task.output = applied;\n task.state = \"completed\";\n task.updated_at = now;\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: \"completed\", note: \"override applied\" });\n return { result: { state: \"completed\", override_artefact_id: id, applied } };\n }\n\n private opAbstainDeclare(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\", \"reason\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const task = ws.tasks.get(p.task_id as string);\n if (!task) return { error: rpcError(E.PARAMS, \"Unknown task\") };\n if (task.state !== \"review_requested\") {\n return { error: rpcError(E.NOT_REVIEWABLE, `Task not awaiting review: ${task.state}`) };\n }\n const notReviewer = this.requireReviewer(task, p.from);\n if (notReviewer) return notReviewer;\n const now = this.now();\n task.review!.decisions.push({\n reviewer: p.from as ParticipantUri,\n kind: \"abstain\",\n ts: now,\n comment: p.reason as string,\n abstain_category: (p.category as string) || \"other\",\n });\n task.state = \"abstained\";\n task.updated_at = now;\n task.history.push({ ts: now, from: p.from as ParticipantUri, state: \"abstained\", note: p.reason as string });\n return { result: { state: \"abstained\" } };\n }\n\n private opEscalateRaise(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"original_task_id\", \"new_task\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n const ws = this.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const notMember = this.requireMember(ws, p.from);\n if (notMember) return notMember;\n const orig = ws.tasks.get(p.original_task_id as string);\n if (!orig) return { error: rpcError(E.PARAMS, \"Unknown original task\") };\n if (orig.state === \"completed\" || orig.state === \"cancelled\" || orig.state === \"superseded\") {\n return { error: rpcError(E.PARAMS, `Cannot escalate a terminal task: ${orig.state}`) };\n }\n const nt = p.new_task as Record<string, unknown>;\n const assignee = nt.assignee as string;\n if (!assignee || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"Escalation assignee not in workspace\") };\n }\n const now = this.now();\n const newId = this.ids.taskId();\n const newTask: Task = {\n id: newId,\n kind: (nt.kind as string) || orig.kind,\n state: \"created\",\n assignee,\n delegator: p.from as ParticipantUri,\n input: (nt.input as Record<string, unknown>) ?? {},\n created_at: now,\n updated_at: now,\n mode: orig.mode,\n supersedes: orig.id,\n history: [{ ts: now, from: p.from as ParticipantUri, state: \"created\", note: `escalated from ${orig.id}` }],\n paused: false,\n };\n ws.tasks.set(newId, newTask);\n orig.state = \"escalated\";\n orig.updated_at = now;\n orig.superseded_by = newId;\n orig.history.push({ ts: now, from: p.from as ParticipantUri, state: \"escalated\", note: `-> ${newId}` });\n return { result: { new_task_id: newId, escalated_from: orig.id } };\n }\n}\n\nfunction memberToDict(m: Member): Record<string, unknown> {\n const out: Record<string, unknown> = {\n uri: m.uri, type: m.type, role: m.role, joined: m.joined,\n };\n if (m.display_name) out.display_name = m.display_name;\n if (m.capabilities) out.capabilities = m.capabilities;\n if (m.scopes) out.scopes = m.scopes;\n if (m.keys.length) {\n out.jwks = { keys: m.keys.filter(k => !k.revoked_at && !k.valid_until).map(k => k.jwk) };\n out.key_history = m.keys;\n }\n if (m.paused) out.paused = true;\n if (m.oidc_sub) out.oidc_sub = m.oidc_sub;\n if (m.vc_holder) out.vc_holder = m.vc_holder;\n return out;\n}\n","/**\n * Default routing policy factory.\n *\n * Returns a partial CoordinatorOptions configured with the three\n * routing hooks (routingPolicy, reviewDepthPolicy, escalationPolicy)\n * that the playground and demo use out of the box. Operators can\n * override individual hooks by passing their own functions in\n * CoordinatorOptions.\n *\n * The defaults shipped with the Coordinator (in profiles/routing.ts)\n * implement the same logic; this factory exists so that the legacy\n * call site can keep using:\n *\n * new Coordinator({ ...makeDefaultPolicy(SENIOR_URI), ... })\n *\n * The seniorTarget argument is the URI auto-escalation routes to\n * when no other target is supplied.\n */\nimport type {\n EscalationPolicyFn,\n ReviewDepthPolicyFn,\n RoutingPolicyFn,\n CoordinatorOptions,\n} from \"./coordinator.js\";\n\nconst CRIT: Record<string, number> = { low: 0, medium: 1, high: 2, critical: 3 };\n\nexport function makeDefaultPolicy(seniorTarget: string): Pick<CoordinatorOptions,\n \"routingPolicy\" | \"reviewDepthPolicy\" | \"escalationPolicy\"> {\n\n const routingPolicy: RoutingPolicyFn = (task, candidates) => {\n const eligible = candidates; // delegate elig check to coordinator\n return {\n selected: eligible[0],\n rationale: {\n policy_id: \"default\",\n hints_used: Object.keys(task.routing_hints ?? {}),\n summary: \"default policy: first eligible candidate\",\n alternatives_considered: eligible.slice(1).map(c => ({\n candidate: c, reason_excluded: \"not first eligible\",\n })),\n },\n };\n };\n\n const reviewDepthPolicy: ReviewDepthPolicyFn = (_task, hints) => {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n if (r >= 3) return { depth: \"full\",\n rationale: { policy_id: \"default\", summary: \"criticality=critical: full review\" }};\n if (r === 2 && conf < 0.7) return { depth: \"full\",\n rationale: { policy_id: \"default\", summary: \"criticality=high and confidence<0.7: full review\" }};\n if (r === 0 && conf >= 0.95) return { depth: \"skip\",\n rationale: { policy_id: \"default\", summary: \"very low criticality + very high confidence: skip\" }};\n if (r <= 1 && conf >= 0.85) return { depth: \"spot_check\", sampling_probability: 0.10,\n rationale: { policy_id: \"default\", summary: \"low criticality + high confidence: 10% sample\" }};\n return { depth: \"spot_check\", sampling_probability: 0.25,\n rationale: { policy_id: \"default\", summary: \"default mid-confidence: 25% sample\" }};\n };\n\n const escalationPolicy: EscalationPolicyFn = (_task, hints) => {\n const crit = (hints.criticality as string) ?? \"medium\";\n let conf = 1.0;\n try { conf = Number(hints.confidence ?? 1.0); } catch { conf = 1.0; }\n if (isNaN(conf)) conf = 1.0;\n const r = CRIT[crit] ?? 1;\n const escalate = (r >= 3) || (r >= 2 && conf < 0.6);\n return {\n escalate,\n to: escalate ? seniorTarget : undefined,\n triggered_rule: {\n rule_id: \"default-auto-esc\",\n summary: \"criticality=critical OR (criticality>=high AND confidence<0.6)\",\n hints_used: [\"criticality\", \"confidence\"],\n },\n };\n };\n\n return { routingPolicy, reviewDepthPolicy, escalationPolicy };\n}\n","/**\n * @brightbeamai/chap-coordinator/transports/wrap\n *\n * Inward integration helpers: turn an external tool/agent event into\n * a CHAP envelope landing in a workspace's audit log. Library\n * counterpart to the patterns described in\n * ``integrations/CHAP-with-MCP.md`` and ``integrations/CHAP-with-A2A.md``.\n *\n * The outward transports let external clients drive a CHAP workspace.\n * These helpers go the other direction: when work has already\n * happened outside CHAP, wrap it so the audit log carries a faithful,\n * citable record.\n *\n * Spec target: CHAP 0.2. MCP 2026-07-28. A2A 1.0.\n */\n\nimport { contentHash } from \"../canonical.js\";\nimport type { Coordinator } from \"../coordinator.js\";\n\nexport { contentHash } from \"../canonical.js\";\n\nexport interface WrapMcpToolCallOptions {\n /** Participant URI making the call. Must already be a workspace member. */\n caller: string;\n /** MCP tool name, e.g. ``\"github.create_issue\"``. */\n tool: string;\n /** Arguments passed to the MCP tool. */\n args: Record<string, unknown>;\n /** Return value from the MCP tool. */\n result: unknown;\n /** Optional MCP server identifier, e.g. \"github\". */\n server?: string;\n /** Override the default task kind ``\"mcp_call:<tool>\"``. */\n taskKind?: string;\n /** Optional routing hints attached to the CHAP task. */\n routingHints?: Record<string, unknown>;\n /** Optional confidence value attached to task.complete. */\n confidence?: number | string;\n}\n\nexport interface WrapResult {\n task_id: string;\n input_hash: string;\n output_hash: string;\n}\n\n/**\n * Wrap a completed MCP tool call as a CHAP task pair.\n *\n * Emits ``task.create`` + ``task.complete`` envelopes into the\n * workspace so the MCP call shows up as a first-class audit entry.\n * The result artefact is the MCP tool's return value, plus a\n * ``citations[]`` entry with the input/output hashes per\n * ``integrations/CHAP-with-MCP.md`` §2.\n */\nexport function wrapMcpToolCall(\n coord: Coordinator,\n workspace: string,\n options: WrapMcpToolCallOptions,\n): WrapResult {\n if (!workspace) throw new Error(\"workspace is required\");\n if (!options.caller) throw new Error(\"caller is required\");\n if (!options.tool) throw new Error(\"tool is required\");\n\n const inputHash = contentHash(options.args);\n const outputHash = contentHash(options.result);\n const kind = options.taskKind ?? `mcp_call:${options.tool}`;\n\n const citations = [{\n kind: \"mcp_tool_call\" as const,\n server: options.server ?? \"unknown\",\n tool: options.tool,\n input_hash: inputHash,\n output_hash: outputHash,\n }];\n\n const createParams: Record<string, unknown> = {\n workspace,\n from: options.caller,\n kind,\n assignee: options.caller,\n input: options.args,\n };\n if (options.routingHints) createParams.routing_hints = { ...options.routingHints };\n\n const createResp = coord.dispatch({\n jsonrpc: \"2.0\",\n id: `wrap-${options.tool}-create`,\n method: \"task.create\",\n params: createParams,\n });\n if (createResp.error) throw new Error(`task.create failed: ${JSON.stringify(createResp.error)}`);\n const taskId = (createResp.result as { task_id: string }).task_id;\n\n coord.dispatch({\n jsonrpc: \"2.0\",\n id: `wrap-${options.tool}-update`,\n method: \"task.update\",\n params: { workspace, from: options.caller, task_id: taskId, state: \"in_progress\" },\n });\n\n const completeParams: Record<string, unknown> = {\n workspace,\n from: options.caller,\n task_id: taskId,\n output: { result: options.result, citations },\n };\n if (options.confidence !== undefined) completeParams.confidence = options.confidence;\n\n const completeResp = coord.dispatch({\n jsonrpc: \"2.0\",\n id: `wrap-${options.tool}-complete`,\n method: \"task.complete\",\n params: completeParams,\n });\n if (completeResp.error) throw new Error(`task.complete failed: ${JSON.stringify(completeResp.error)}`);\n\n return { task_id: taskId, input_hash: inputHash, output_hash: outputHash };\n}\n\n// ============================================================\n\nexport interface WrapA2aExchangeOptions {\n /** URI of the local bridge participant. Must be a workspace member. */\n bridgeUri: string;\n /** Identifier of the remote A2A agent. Recorded in the citation. */\n remoteAgent: string;\n /** The A2A message body sent outbound. */\n sent: Record<string, unknown>;\n /** The A2A message body received in response. */\n received: Record<string, unknown>;\n /** CHAP task kind. Default ``\"a2a_exchange\"``. */\n taskKind?: string;\n /** Optional routing hints attached to the task. */\n routingHints?: Record<string, unknown>;\n /** Optional confidence value attached to task.complete. */\n confidence?: number | string;\n}\n\nexport interface WrapA2aResult {\n task_id: string;\n sent_hash: string;\n received_hash: string;\n}\n\n/**\n * Wrap a completed A2A message exchange as a CHAP task pair.\n *\n * Implements the bridge-participant pattern from\n * ``integrations/CHAP-with-A2A.md`` §3 as a library helper.\n */\nexport function wrapA2aMessageExchange(\n coord: Coordinator,\n workspace: string,\n options: WrapA2aExchangeOptions,\n): WrapA2aResult {\n if (!workspace) throw new Error(\"workspace is required\");\n if (!options.bridgeUri) throw new Error(\"bridgeUri is required\");\n if (!options.remoteAgent) throw new Error(\"remoteAgent is required\");\n\n const sentHash = contentHash(options.sent);\n const receivedHash = contentHash(options.received);\n const kind = options.taskKind ?? \"a2a_exchange\";\n\n const citation = {\n kind: \"a2a_exchange\" as const,\n remote_agent: options.remoteAgent,\n sent_hash: sentHash,\n received_hash: receivedHash,\n };\n\n const createParams: Record<string, unknown> = {\n workspace,\n from: options.bridgeUri,\n kind,\n assignee: options.bridgeUri,\n input: { remote_agent: options.remoteAgent, sent: options.sent },\n };\n if (options.routingHints) createParams.routing_hints = { ...options.routingHints };\n\n const createResp = coord.dispatch({\n jsonrpc: \"2.0\", id: \"wrap-a2a-create\",\n method: \"task.create\", params: createParams,\n });\n if (createResp.error) throw new Error(`task.create failed: ${JSON.stringify(createResp.error)}`);\n const taskId = (createResp.result as { task_id: string }).task_id;\n\n coord.dispatch({\n jsonrpc: \"2.0\", id: \"wrap-a2a-update\",\n method: \"task.update\",\n params: { workspace, from: options.bridgeUri,\n task_id: taskId, state: \"in_progress\" },\n });\n\n const completeParams: Record<string, unknown> = {\n workspace, from: options.bridgeUri, task_id: taskId,\n output: { received: options.received, citations: [citation] },\n };\n if (options.confidence !== undefined) completeParams.confidence = options.confidence;\n\n const completeResp = coord.dispatch({\n jsonrpc: \"2.0\", id: \"wrap-a2a-complete\",\n method: \"task.complete\", params: completeParams,\n });\n if (completeResp.error) throw new Error(`task.complete failed: ${JSON.stringify(complet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