@brightbeamai/chap-coordinator 0.3.1 → 0.3.2
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/{api-BkvwN42r.d.cts → api-59aU01Bs.d.cts} +48 -3
- package/dist/{api-Ddy9fqkY.d.ts → api-CxciGFHA.d.ts} +48 -3
- package/dist/api.d.cts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/index.cjs +535 -125
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +534 -125
- package/dist/index.js.map +1 -1
- package/dist/storage/sqlite.cjs +270 -34
- package/dist/storage/sqlite.cjs.map +1 -1
- package/dist/storage/sqlite.d.cts +60 -10
- package/dist/storage/sqlite.d.ts +60 -10
- package/dist/storage/sqlite.js +270 -34
- package/dist/storage/sqlite.js.map +1 -1
- package/dist/storage/store.cjs +150 -9
- package/dist/storage/store.cjs.map +1 -1
- package/dist/storage/store.d.cts +118 -40
- package/dist/storage/store.d.ts +118 -40
- package/dist/storage/store.js +143 -8
- package/dist/storage/store.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/canonical.ts","../src/catalogue.ts","../src/crypto.ts","../src/ids.ts","../src/jsonrpc.ts","../src/audit.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\n *\n * Public entry point. Re-exports the Coordinator class and the\n * supporting types so consumers can `import { Coordinator } from \"@brightbeamai/chap-coordinator\"`.\n *\n * Architecture:\n *\n * coordinator.ts The Coordinator class with Core + review/1.0 handlers\n * and the dispatch/registration infrastructure.\n * profiles/*.ts One module per optional profile, each registers its\n * method handlers on a Coordinator instance.\n * canonical.ts JCS canonicalisation (RFC 8785).\n * crypto.ts Ed25519 signing/verification (Node built-ins).\n * ids.ts ULID-format id generation.\n * jsonrpc.ts Error codes and helpers.\n * patch.ts RFC 6902 JSON Patch.\n * types.ts Wire and in-memory types.\n */\n\nexport { Coordinator, PRIVILEGED_METHODS } from \"./coordinator.js\";\nexport type {\n CoordinatorOptions,\n Handler,\n TokenVerifier,\n CredentialVerifier,\n ScittSubmitter,\n ScittReceiptVerifier,\n RoutingPolicyFn,\n ReviewDepthPolicyFn,\n EscalationPolicyFn,\n} from \"./coordinator.js\";\n\nexport { call, makeApi, CoordinatorError } from \"./api.js\";\nexport type { CoordinatorApi } from \"./api.js\";\nexport type {\n MethodName,\n MethodParams,\n MethodResult,\n MethodTable,\n} from \"./methods.js\";\n\nexport { entryCall, entryRecord, isRefusal, linkHash } from \"./audit.js\";\n\nexport { MemoryStore } from \"./storage/store.js\";\nexport type { Store, WorkspaceRecord } from \"./storage/store.js\";\n\nexport * from \"./types.js\";\nexport * from \"./jsonrpc.js\";\nexport * from \"./patch.js\";\nexport {\n canonicalize, sha256Hex, contentHash, ZERO_HASH,\n} from \"./canonical.js\";\nexport {\n deriveKeypair, deriveSeed, jwkFromPrivateKey,\n publicKeyBytes, publicKeyFromJwk, publicKeyFromRaw,\n signEnvelope, verifyEnvelope,\n} from \"./crypto.js\";\nexport type { Jwk as CryptoJwk } from \"./crypto.js\";\nexport { IdFactory } from \"./ids.js\";\nexport { makeDefaultPolicy } from \"./policy.js\";\n\nexport {\n wrapMcpToolCall,\n wrapA2aMessageExchange,\n} from \"./transports/wrap.js\";\nexport type {\n WrapMcpToolCallOptions,\n WrapA2aExchangeOptions,\n WrapResult,\n WrapA2aResult,\n} from \"./transports/wrap.js\";\n","/**\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\nconst LONE_SURROGATE_ERROR =\n \"CHAP canonical strings must be valid Unicode (I-JSON / RFC 7493); \" +\n \"unpaired UTF-16 surrogates are not permitted.\";\n\nfunction assertNoLoneSurrogate(s: string): void {\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c >= 0xd800 && c <= 0xdbff) {\n const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;\n if (next < 0xdc00 || next > 0xdfff) throw new Error(LONE_SURROGATE_ERROR);\n i++;\n } else if (c >= 0xdc00 && c <= 0xdfff) {\n throw new Error(LONE_SURROGATE_ERROR);\n }\n }\n}\n\nfunction canonicalString(s: string): string {\n assertNoLoneSurrogate(s);\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","// Generated by scripts/sync-method-catalogue.mjs. Do not edit.\n// Source: schemas/profiles/chap-methods.schema.json\n/**\n * Which profile owns which method, and which methods are never gated.\n *\n * SPECIFICATION 15.4: a Coordinator refuses a method whose owning profile the\n * workspace does not advertise.\n * The rule applies to each method, since a namespace can span profiles: audit\n * spans audit-scitt and core; escalate spans review and routing; review spans\n * review and routing; task spans core and routing.\n */\n\n/** The profile that introduces each method the references implement. */\nexport const OWNING_PROFILE: Readonly<Record<string, string>> = Object.freeze({\n \"abstain.declare\": \"review/1.0\",\n \"audit.read\": \"core/1.0\",\n \"audit.submit_to_scitt\": \"audit-scitt/1.0\",\n \"audit.verify_chain\": \"audit-scitt/1.0\",\n \"audit.verify_receipt\": \"audit-scitt/1.0\",\n \"control.cancel\": \"control/1.0\",\n \"control.pause\": \"control/1.0\",\n \"control.resume\": \"control/1.0\",\n \"control.rollback\": \"control/1.0\",\n \"control.set_mode_ceiling\":\"control/1.0\",\n \"control.snapshot\": \"control/1.0\",\n \"control.supersede\": \"control/1.0\",\n \"decide.approve\": \"review/1.0\",\n \"decide.override\": \"review/1.0\",\n \"decide.reject\": \"review/1.0\",\n \"deliberate.close\": \"deliberation/1.0\",\n \"deliberate.comment\": \"deliberation/1.0\",\n \"deliberate.open\": \"deliberation/1.0\",\n \"deliberate.vote\": \"deliberation/1.0\",\n \"escalate.auto\": \"routing/1.0\",\n \"escalate.raise\": \"review/1.0\",\n \"handoff.accept\": \"handoff/1.0\",\n \"handoff.decline\": \"handoff/1.0\",\n \"handoff.propose\": \"handoff/1.0\",\n \"participant.join\": \"core/1.0\",\n \"participant.leave\": \"core/1.0\",\n \"participant.revoke_key\": \"core/1.0\",\n \"participant.rotate_key\": \"core/1.0\",\n \"review.depth\": \"routing/1.0\",\n \"review.request\": \"review/1.0\",\n \"task.complete\": \"core/1.0\",\n \"task.create\": \"core/1.0\",\n \"task.route\": \"routing/1.0\",\n \"task.update\": \"core/1.0\",\n \"whisper.answer\": \"whisper/1.0\",\n \"whisper.ask\": \"whisper/1.0\",\n \"workspace.create\": \"core/1.0\",\n \"workspace.describe\": \"core/1.0\",\n \"workspace.set_profiles\": \"core/1.0\",\n});\n\n/**\n * Callable whatever the workspace advertises.\n *\n * Reads, because a workspace must always be able to ask what it is and to\n * check its own chain. Not the coordinator's read-only set: that holds\n * audit.submit_to_scitt, which reaches a transparency service and is a real\n * audit-scitt/1.0 capability.\n */\nexport const ALWAYS_AVAILABLE: ReadonlySet<string> = new Set([\n \"workspace.describe\",\n \"audit.read\",\n \"audit.verify_chain\",\n \"audit.verify_receipt\",\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/audit\n *\n * Audit entries, the chain link over them, and the rule for recording a\n * refusal (SPECIFICATION 10.1).\n *\n * An accepted call is recorded under `envelope`. A refused call that the rule\n * names is recorded under `request`, with an `outcome` beside it, so a reader\n * keyed on `envelope` passes it by instead of replaying it as effective. The\n * chain link hashes what the entry records: the envelope of an accepted call,\n * and the outcome together with the request of a refusal. Altering either\n * half of a refusal breaks the chain, moving its record under `envelope` fails\n * the shape check, and an entry with no outcome hashes exactly as it always\n * has, so every existing chain still verifies.\n */\nimport { canonicalize, sha256Hex } from \"./canonical.js\";\nimport { E } from \"./jsonrpc.js\";\nimport type { AuditEntry, Envelope } from \"./types.js\";\n\n/** The value an entry's chain link hashes. */\nexport function entryRecord(entry: AuditEntry): unknown {\n if (entry.outcome != null) return { outcome: entry.outcome, request: entry.request };\n return entry.envelope;\n}\n\n/** The call an entry records, whether it took effect or was refused. */\nexport function entryCall(entry: AuditEntry): Envelope | undefined {\n return entry.envelope ?? entry.request ?? undefined;\n}\n\n/** True when an entry records a refused call. */\nexport function isRefusal(entry: AuditEntry): boolean {\n return entry.outcome != null;\n}\n\n/** A JSON-RPC call: an object with `jsonrpc` \"2.0\" and a string `method`. */\nfunction isCall(value: unknown): boolean {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const v = value as Record<string, unknown>;\n return v.jsonrpc === \"2.0\" && typeof v.method === \"string\";\n}\n\n/**\n * An entry is well formed when it records an accepted call alone, under\n * `envelope`, or a refused call alone, under `request`, with an outcome of\n * status `refused` and an integer code. Requiring a JSON-RPC call on either\n * side is what stops a refusal's record being moved under `envelope`, where it\n * would hash to the same bytes and read as a call that took effect.\n */\nexport function entryIsWellFormed(entry: AuditEntry): boolean {\n const accepted = entry.envelope != null;\n const refused = entry.request != null;\n if (accepted === refused) return false;\n if (accepted) return isCall(entry.envelope) && entry.outcome == null;\n const o = entry.outcome as unknown as Record<string, unknown> | null | undefined;\n return isCall(entry.request) && o != null && typeof o === \"object\"\n && o.status === \"refused\" && Number.isInteger(o.code);\n}\n\n/** Whether a call carries a top-level signature (security-signed/1.0). */\nexport function isSigned(call: unknown): boolean {\n return call !== null && typeof call === \"object\" && typeof (call as { sig?: unknown }).sig === \"string\";\n}\n\n/**\n * The digest that identifies a signed call by what its sender signed: SHA-256\n * of the JCS of the call without its `sig`. Two encodings of one signature\n * give the same digest, so re-encoding a signature does not make a new call.\n */\nexport function signedDigest(call: Envelope): string {\n const signed: Record<string, unknown> = { ...call };\n delete signed.sig;\n return sha256Hex(canonicalize(signed));\n}\n\n/** chain_head = SHA-256( JCS(record) || prev_hash ). */\nexport function linkHash(record: unknown, prev: string): string {\n return sha256Hex(Buffer.concat([canonicalize(record), Buffer.from(prev, \"utf-8\")]));\n}\n\n/**\n * Refusals the log never records: a call that was malformed or invalid, a\n * fault in the Coordinator, and a call whose signature or key did not check\n * out.\n */\nconst UNRECORDED_CODES: ReadonlySet<number> = new Set([\n E.PARSE, E.REQUEST, E.PARAMS, E.INTERNAL,\n E.SIG_VERIFY_FAILED, E.SIG_KEY_NOT_FOUND, E.SIG_KEY_REVOKED, E.SIG_ROTATION_KEY_MISMATCH,\n]);\n\n/**\n * Methods whose refusals are never recorded. They run before the caller is\n * established as a member and are exempt from signature checks, so a refusal\n * of one proves nothing about who sent it.\n */\nconst UNRECORDED_METHODS: ReadonlySet<string> = new Set([\"workspace.create\", \"participant.join\"]);\n\n/**\n * Whether a refusal with this error is one the log records, before the test\n * that the caller is a member.\n *\n * `-32601` is recorded only when the profile gate refused a privileged method,\n * which is an attempt to pull an emergency brake the workspace has switched\n * off. The gate refusing an ordinary method, and a method that does not\n * exist, are not recorded.\n */\nexport function refusalIsRecorded(\n method: string,\n error: { code: number; data?: unknown },\n privileged: ReadonlySet<string>,\n): boolean {\n if (!Number.isInteger(error.code)) return false;\n if (UNRECORDED_METHODS.has(method)) return false;\n if (UNRECORDED_CODES.has(error.code)) return false;\n if (error.code === E.METHOD) {\n const data = error.data as { profile?: unknown } | undefined;\n return typeof data?.profile === \"string\" && privileged.has(method);\n }\n return true;\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\n// The JSON type name of a value. Python and JavaScript name their own types\n// differently (dict against object, list against object, str against string).\n// The refusal names the JSON type, which both references and the\n// specification share.\nfunction jsonType(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n switch (typeof value) {\n case \"object\": return \"object\";\n case \"string\": return \"string\";\n case \"number\": return \"number\";\n case \"boolean\": return \"boolean\";\n default: return \"null\";\n }\n}\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 ${jsonType(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 ${jsonType(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 // RFC 6901: \"-\" names the position after the last element, which no\n // element occupies, so only \"add\" can use it. Left as a string it slips\n // through a numeric range check and writes a \"-\" property on the array.\n const idx = key === \"-\" ? -1 : (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 ${jsonType(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 // RFC 6901: \"-\" names no existing element, so it cannot be removed.\n // Left as a string it passes the numeric range check and then splice\n // coerces it to zero, removing the first element instead.\n const idx = key === \"-\" ? -1 : (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 ${jsonType(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 produced_at: string;\n produced_by: ParticipantUri;\n content_hash: string;\n content: {\n workspace: WorkspaceId;\n audit_seq: number;\n label?: string;\n include: string[];\n state: Record<string, unknown>;\n };\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 paused_from?: TaskState;\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 /** The accepted call. Absent on a refusal entry. */\n envelope?: Envelope;\n /**\n * The refused call, as received. Present only on a refusal entry, and held\n * here rather than under `envelope` so a reader keyed on `envelope` passes\n * the refusal by instead of replaying it (SPECIFICATION 10.1).\n */\n request?: Envelope;\n /** Present only on a refusal entry. */\n outcome?: RefusalOutcome;\n prev_hash?: string;\n}\n\n/** Why a recorded call did not take effect. */\nexport interface RefusalOutcome {\n status: \"refused\";\n /** The error code the caller was answered with. */\n code: number;\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 { entryIsWellFormed, entryRecord, linkHash } from \"../audit.js\";\nimport { canonicalize, ZERO_HASH } from \"../canonical.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\n\n/** The head after a malformed entry, which no stored head can match. */\nconst MALFORMED = \"sha256:malformed\";\n\n/**\n * A statement's payload is what the entry's chain link hashes: the envelope\n * of an accepted call, or the outcome together with the request of a refusal.\n */\nfunction buildStatement(workspaceId: string, record: unknown, 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.3\",\n },\n payload: canonicalize(record).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, entryRecord(e), 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, entryRecord(entry), 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 let resync = false;\n for (const e of ws.audit.slice(start)) {\n // After a malformed entry the next link is taken as stored, so the\n // entries after it are judged on their own links. The chain is\n // reported broken either way.\n const expectedPrev = resync && typeof e.prev_hash === \"string\" ? e.prev_hash : prev;\n resync = false;\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 // An entry that records neither one accepted envelope nor one refused\n // request with its outcome has been altered, and cannot be linked.\n if (!entryIsWellFormed(e)) {\n errors.push(`seq ${e.seq}: malformed entry`);\n prev = MALFORMED;\n resync = true;\n continue;\n }\n prev = linkHash(entryRecord(e), expectedPrev);\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 { contentHash } from \"../canonical.js\";\nimport { modeLE } from \"../types.js\";\nimport type { Mode, SnapshotArtefact, Task, TaskState } 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 if (prior !== \"paused\") task.paused_from = prior;\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 const restored: TaskState = task.paused_from ?? \"in_progress\";\n task.paused_from = undefined;\n task.state = restored;\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: restored });\n return { result: { scope: \"task\", task_id: task.id, state: restored } };\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 if (Array.isArray(p.include) && p.include.length === 0) {\n return { error: rpcError(E.PARAMS, \"include must not be empty\") };\n }\n const include: string[] = Array.isArray(p.include)\n ? [...p.include as string[]]\n : [\"members\", \"open_tasks\", \"mode_ceiling\"];\n const state: Record<string, unknown> = {};\n if (include.includes(\"members\")) {\n const members = Array.from(ws.members.values()).map(m => ({\n uri: m.uri, type: m.type,\n ...(m.role ? { role: m.role } : {}),\n ...(m.scopes?.length ? { scopes: m.scopes } : {}),\n }));\n if (members.length) state.members = members;\n }\n if (include.includes(\"open_tasks\")) {\n const 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,\n ...(t.assignee ? { assignee: t.assignee } : {}),\n }));\n if (tasks.length) state.open_tasks = tasks;\n }\n if (include.includes(\"mode_ceiling\")) state.mode_ceiling = ws.mode_ceiling;\n if (include.includes(\"policy\") && ws.routing_policy_uri) state.routing_policy_uri = ws.routing_policy_uri;\n if (include.includes(\"audit\") || include.includes(\"all\")) state.audit_seq = ws.audit.length;\n\n // Store the same canonical artefact that is emitted on the wire. Copies\n // belong to this explicit capture boundary, never Coordinator.snapshot().\n const content: SnapshotArtefact[\"content\"] = structuredClone({\n workspace: ws.id,\n audit_seq: ws.audit.length,\n include,\n state,\n ...(p.label ? { label: p.label as string } : {}),\n });\n const snapId = coord.ids.artefactId();\n const snap: SnapshotArtefact = {\n id: snapId,\n kind: \"snapshot\",\n produced_at: coord.now(),\n produced_by: p.from as string,\n content_hash: contentHash(content),\n content,\n };\n ws.snapshots.set(snapId, snap);\n return {\n result: {\n snapshot_artefact_id: snapId,\n audit_seq: snap.content.audit_seq,\n artefact: structuredClone(snap),\n },\n };\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 if (Array.isArray(p.what_to_restore) && p.what_to_restore.length === 0) {\n return { error: rpcError(E.PARAMS, \"what_to_restore must not be empty\") };\n }\n const what: string[] = (p.what_to_restore as string[]) ?? snap.content.include;\n const restored: string[] = [];\n if (what.includes(\"mode_ceiling\") && snap.content.state.mode_ceiling) {\n ws.mode_ceiling = snap.content.state.mode_ceiling as Mode;\n restored.push(\"mode_ceiling\");\n }\n if (what.includes(\"members\") && Array.isArray(snap.content.state.members)) {\n const snapByUri = new Map<string, Record<string, unknown>>();\n for (const m of snap.content.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 = Array.isArray(snapM.scopes) ? [...snapM.scopes as string[]] : undefined;\n }\n }\n restored.push(\"members\");\n }\n return { result: {\n rolled_back_to: snapId, audit_seq: snap.content.audit_seq, restored,\n ...(p.reason ? { reason: p.reason as string } : {}),\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 (typeof assignee !== \"string\" || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"successor assignee not in workspace\") };\n }\n // The successor is a created task, so the participant-paused check\n // task.create applies has to apply here too. Without it, superseding is a\n // way to hand work to a participant whose work was stopped.\n if (ws.members.get(assignee)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${assignee} is paused`) };\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 if (newSpec.mode !== undefined && newSpec.mode !== null && typeof newSpec.mode !== \"string\") {\n return { error: rpcError(E.PARAMS, \"successor_task.mode must be a string\") };\n }\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 if (newSpec.review_required !== undefined && newSpec.review_required !== null\n && typeof newSpec.review_required !== \"boolean\") {\n return { error: rpcError(E.PARAMS, \"successor_task.review_required must be a boolean\") };\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 // A successor keeps the review requirement of the task it replaces, so\n // superseding never removes a required review. Trial forces review only\n // when the workspace opted into modes/1.0, matching task.create, since\n // mode is inert without the profile. Otherwise the spec's own setting\n // applies.\n if (old.review_required || (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && newTask.mode === \"trial\")) {\n newTask.review_required = true;\n } else if (\"review_required\" in newSpec) {\n newTask.review_required = !!newSpec.review_required;\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 // Accepting makes the acceptor the assignee. A paused participant is\n // assigned no new tasks (control/1.0), so it cannot take tasks this way.\n if (ws.members.get(acceptor)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Acceptor ${acceptor} is paused`) };\n }\n // Omission accepts all proposed tasks; an empty selection is not a handoff.\n if (Array.isArray(p.accepted_task_ids) && p.accepted_task_ids.length === 0) {\n return { error: rpcError(E.PARAMS, \"accepted_task_ids must not be empty\") };\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 if (p.candidates !== undefined && p.candidates !== null && !Array.isArray(p.candidates)) {\n return { error: rpcError(E.PARAMS, \"candidates must be a list\") };\n }\n const candidates = (p.candidates as string[] | null | undefined) ?? [];\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 // A paused participant is assigned no new tasks (control/1.0), so the\n // default policy passes over one as it passes over a non-member, and\n // names it among the alternatives with that reason.\n const memberOf = (c: unknown) => (typeof c === \"string\" ? ws.members.get(c) : undefined);\n const eligible = candidates.filter(c => { const m = memberOf(c); return !!m && !m.paused; });\n if (!eligible.length) {\n return { error: rpcError(E.ROUTING_NO_ELIGIBLE_ASSIGNEE, \"No candidate is a workspace member who is not paused\") };\n }\n selected = eligible[0];\n const alternatives: Array<{ candidate: string; reason_excluded: string }> = [];\n let chosen = false;\n for (const c of candidates) {\n const m = memberOf(c);\n if (!m) continue;\n if (m.paused) alternatives.push({ candidate: c, reason_excluded: \"paused\" });\n else if (!chosen) chosen = true;\n else alternatives.push({ candidate: c, reason_excluded: \"not first eligible\" });\n }\n rationale = {\n policy_id: \"default\",\n hints_used: Object.keys(task.routing_hints ?? {}),\n summary: \"default policy: first eligible candidate\",\n alternatives_considered: alternatives,\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 // An operator policy can pick a paused participant. Routing to one would\n // assign a task to a participant whose work was stopped, so it is refused\n // as task.create refuses a paused assignee.\n if (ws.members.get(selected)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${selected} is paused`) };\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 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 }\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 (coord.options.onAutoEscalate && to) {\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 { canonicalize } from \"../canonical.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\n/**\n * Whether an answer field holds anything, read as Python reads a value's\n * truth, so both references agree that an empty answer is no answer.\n */\nfunction present(v: unknown): boolean {\n if (v === undefined || v === null || v === false || v === 0 || v === \"\") return false;\n if (Array.isArray(v)) return v.length > 0;\n if (typeof v === \"object\") return Object.keys(v as object).length > 0;\n return true;\n}\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 if (p.options !== undefined && p.options !== null && !Array.isArray(p.options)) {\n return { error: rpcError(E.PARAMS, \"options must be a list\") };\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 // A null option is no option, and an empty answer no answer, as in Python.\n const answerOption = p.answer_option as string | undefined;\n const hasOption = answerOption !== undefined && answerOption !== null;\n const answerText = (present(p.answer) ? p.answer : p.answer_text) as string | undefined;\n if (prompt.options && prompt.options.length) {\n if (!hasOption) {\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 ${canonicalize(answerOption as never).toString(\"utf-8\")} not in option set`) };\n }\n } else if (!present(answerText) && !hasOption) {\n return { error: rpcError(E.PARAMS, \"answer or answer_option required\") };\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 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, ZERO_HASH } from \"./canonical.js\";\nimport { ALWAYS_AVAILABLE, OWNING_PROFILE } from \"./catalogue.js\";\nimport { publicKeyFromJwk, verifyEnvelope } from \"./crypto.js\";\nimport { IdFactory } from \"./ids.js\";\nimport { E, isValidEnvelope, rpcError } from \"./jsonrpc.js\";\nimport { entryCall, entryRecord, isSigned, linkHash, refusalIsRecorded, signedDigest } from \"./audit.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 SnapshotArtefact,\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// Methods outside the control, deliberate, handoff and whisper namespaces that\n// dispatch holds to the membership floor before the handler runs.\nconst MEMBER_ONLY_METHODS = new Set<string>([\n \"task.route\", \"review.depth\", \"escalate.auto\", \"participant.leave\",\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 // Submitting the chain to a transparency service reads it and sends it\n // onward. Recording the submission would append to the very log being\n // submitted, so the receipt would attest a chain one entry shorter.\n \"audit.submit_to_scitt\",\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\n// How deeply a request may nest, counting the envelope as level one. The\n// reference HTTP servers refuse deeper bodies before dispatch; the same limit\n// here means an in-process caller cannot send what the canonicaliser, the\n// copy of a recorded call and the two references handle differently.\nconst MAX_NESTING = 64;\n\nfunction withinNesting(value: unknown, limit: number): boolean {\n const stack: Array<[unknown, number]> = [[value, 1]];\n while (stack.length) {\n const [node, depth] = stack.pop()!;\n if (depth > limit) return false;\n if (Array.isArray(node)) {\n for (const v of node) stack.push([v, depth + 1]);\n } else if (node !== null && typeof node === \"object\") {\n for (const v of Object.values(node as Record<string, unknown>)) stack.push([v, depth + 1]);\n }\n }\n return true;\n}\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 onStoreError?: (err: unknown, record: { id: string; version: number }) => 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 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/** The signed calls on a log, keyed by `signedDigest`. */\ninterface SignedIndex {\n refused: Map<string, { seq: number; code: number }>;\n accepted: Set<string>;\n}\n\nfunction indexSigned(index: SignedIndex, entry: AuditEntry): void {\n const call = entryCall(entry);\n if (!isSigned(call)) return;\n let digest: string;\n try { digest = signedDigest(call as Envelope); }\n catch { return; /* an entry that cannot be canonicalised was altered; verify_chain reports it */ }\n if (entry.outcome != null) index.refused.set(digest, { seq: entry.seq, code: entry.outcome.code });\n else index.accepted.add(digest);\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\n// States in which a task has been deliberately stopped. review.request and\n// task.complete both refuse these, so neither can revive a terminated task nor\n// bypass a pause.\nconst REVIEW_REQUEST_STOPPED: string[] = [\"cancelled\", \"superseded\", \"paused\"];\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 saveChains = new Map<WorkspaceId, Promise<void>>();\n private clockMs?: number;\n private frozenNow?: string;\n private auditListeners: AuditListener[] = [];\n /**\n * The signed calls on each workspace's log, by what their senders signed:\n * recorded refusals with their seq and code, and accepted calls. Rebuilt\n * from the log when missing, so a snapshot never carries it.\n */\n private signedIndexes = new WeakMap<Workspace, SignedIndex>();\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 // One restore for every record: restore replaces the workspaces it\n // holds, so restoring record by record kept only the last.\n this.wsVersions.clear();\n this.restore(records.map(r => r.data));\n for (const r of records) this.wsVersions.set(r.id, r.version);\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 let record: WorkspaceRecord;\n try {\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 record = { id: ws.id, data, version: next, updated_at: this.now() };\n } catch {\n return;\n }\n\n const pending = this.saveChains.get(ws.id);\n if (pending) {\n this.trackSave(pending.then(() => this.store.save(record)), record);\n return;\n }\n let result: Promise<void> | void;\n try {\n result = this.store.save(record);\n } catch (err) {\n this.reportStoreError(err, record);\n return;\n }\n if (result instanceof Promise) {\n this.trackSave(result, record);\n }\n }\n\n private trackSave(save: Promise<void>, record: WorkspaceRecord): void {\n const guarded = save.catch(err => this.reportStoreError(err, record));\n this.saveChains.set(record.id, guarded);\n void guarded.then(() => {\n if (this.saveChains.get(record.id) === guarded) {\n this.saveChains.delete(record.id);\n }\n });\n }\n\n private reportStoreError(err: unknown, record: WorkspaceRecord): void {\n if (this.options.onStoreError) {\n try {\n this.options.onStoreError(err, { id: record.id, version: record.version });\n } catch {\n void 0;\n }\n }\n }\n\n async drainSaves(): Promise<void> {\n while (this.saveChains.size) {\n await Promise.allSettled([...this.saveChains.values()]);\n }\n }\n\n // -- lifecycle -----------------------------------------------------\n\n private advanceClock(): string {\n if (this.clockMs !== undefined) {\n this.clockMs += 1000;\n return nowIso(this.clockMs);\n }\n return nowIso();\n }\n\n now(): string {\n return this.frozenNow ?? this.advanceClock();\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 // A `from` that is not a string names nobody. It is answered in fixed\n // words, so both references refuse it alike whatever was sent.\n if (typeof sender !== \"string\") {\n return { error: rpcError(E.NOT_AUTHORISED, \"Not a workspace member: from is not a participant URI\") };\n }\n if (!ws.members.has(sender)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not a workspace member: ${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 // Normalize the former flat store representation only on restore.\n // New snapshots are stored and emitted in the canonical wire shape.\n const content = structuredClone((x.content ?? {\n workspace: x.workspace, audit_seq: x.audit_seq,\n include: x.include, state: x.state,\n ...(x.label ? { label: x.label } : {}),\n }) as SnapshotArtefact[\"content\"]);\n if (!x.content) {\n // Legacy in-memory projections can contain undefined optional\n // fields; full bodies from older stores are not snapshot slices.\n const oldState = content.state;\n const state: Record<string, unknown> = {};\n for (const key of [\"mode_ceiling\", \"routing_policy_uri\", \"audit_seq\"]) {\n if (oldState[key] != null && oldState[key] !== \"\") state[key] = oldState[key];\n }\n for (const [key, fields] of [\n [\"members\", [\"uri\", \"type\", \"role\", \"scopes\"]],\n [\"open_tasks\", [\"id\", \"kind\", \"state\", \"assignee\"]],\n ] as const) {\n const items = oldState[key];\n if (Array.isArray(items) && items.length) {\n state[key] = items.map(item => Object.fromEntries(fields\n .filter(field => item[field] != null && item[field] !== \"\"\n && (!Array.isArray(item[field]) || item[field].length > 0))\n .map(field => [field, item[field]])));\n }\n }\n content.state = state;\n }\n ws.snapshots.set(x.id, {\n id: x.id, kind: \"snapshot\",\n produced_by: (x.produced_by ?? x.by) as string,\n produced_at: (x.produced_at ?? x.ts) as string,\n content_hash: (x.content_hash as string | undefined) ?? contentHash(content),\n content,\n });\n }\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 this.frozenNow = this.advanceClock();\n try {\n const response = this._dispatch(envelope);\n if (response.error) this.recordRefusal(envelope, response.error);\n return response;\n } finally {\n this.frozenNow = undefined;\n }\n }\n\n private _dispatch(envelope: Envelope): Envelope {\n // SPECIFICATION 10.1 fixes the order of the checks below, because which\n // refusal a call receives decides whether it is recorded. First the\n // request itself, none of whose refusals is recorded.\n if (!isValidEnvelope(envelope) || typeof envelope.method !== \"string\" || !envelope.method) {\n return reply(envelope, { error: rpcError(E.REQUEST, \"Invalid JSON-RPC 2.0 request\") });\n }\n if (!withinNesting(envelope, MAX_NESTING)) {\n return reply(envelope, { error: rpcError(E.REQUEST, `Envelope nests deeper than ${MAX_NESTING} levels`) });\n }\n const maxBytes = this.options.maxEnvelopeBytes ?? DEFAULT_MAX_ENVELOPE_BYTES;\n // Canonicalised once: the length is what the size limit measures, and a\n // request that cannot be canonicalised is refused below, once its method\n // is known to exist.\n let size = 0;\n let canonicalError: unknown;\n try { size = canonicalize(envelope).length; } catch (e) { canonicalError = e; }\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 const handler = this.handlers.get(method);\n if (!handler) {\n return reply(envelope, { error: rpcError(E.METHOD, `Unknown method: ${method}`) });\n }\n if (canonicalError !== undefined) {\n const msg = canonicalError instanceof Error ? canonicalError.message : String(canonicalError);\n return reply(envelope, { error: rpcError(E.PARAMS, msg) });\n }\n\n // SPECIFICATION 10.1: a signed request whose signed content matches a\n // recorded refusal is answered with that refusal and not evaluated again.\n // The log publishes a refused request, signature and all, so without this\n // anyone who can read the log could send it again once whatever refused\n // it had changed, and it would take effect in its signer's name.\n if (isSigned(envelope)) {\n const wsId = params.workspace;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n if (ws) {\n const prior = this.signedIndex(ws).refused.get(signedDigest(envelope));\n if (prior) {\n return reply(envelope, { error: rpcError(prior.code,\n `Refused at seq ${prior.seq}; a refused request is not evaluated again`,\n { refused_at_seq: prior.seq }) });\n }\n }\n }\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 // SPECIFICATION 15.4: refuse a method whose owning profile the workspace\n // does not advertise. The refusal is -32601, the same answer a coordinator\n // that never implemented the method would give, so a deployment cannot\n // tell from outside which of the two it is talking to. The detail rides in\n // `data` for an operator reading the log.\n {\n const gate = this.profileGate(method, params);\n if (gate) return reply(envelope, { error: gate });\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 // The routing methods and participant.leave sit under the same floor\n // (SPECIFICATION 6.3.1): without it a non-member could reassign a task\n // with task.route, or write a leave to the log under any name.\n if (method.startsWith(\"control.\") || method.startsWith(\"deliberate.\") || method.startsWith(\"handoff.\") || method.startsWith(\"whisper.\") || MEMBER_ONLY_METHODS.has(method)) {\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 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. A refusal is weighed in dispatch(), once this\n // returns, against the rule in SPECIFICATION 10.1.\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 this.appendEntry(ws, { envelope: JSON.parse(JSON.stringify(envelope)) as Envelope });\n }\n\n /**\n * SPECIFICATION 10.1: record a refused call when it is a governed attempt.\n * The caller must be a member of an existing workspace, the call must be a\n * JSON-RPC call for a method that is not a read, and the refusal must be one\n * `refusalIsRecorded` names. The request is kept as it arrived, so a\n * signature on it still verifies. Every call that reaches a recorded refusal\n * has passed the canonical check, so it can be hashed into the chain.\n */\n private recordRefusal(envelope: Envelope, error: { code: number; data?: unknown }): void {\n if (!isValidEnvelope(envelope) || typeof envelope.method !== \"string\") return;\n const method = envelope.method;\n if (READ_ONLY_METHODS.has(method)) return;\n if (!refusalIsRecorded(method, error, PRIVILEGED_METHODS)) return;\n const raw = envelope.params;\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) return;\n const params = raw as Record<string, unknown>;\n const ws = typeof params.workspace === \"string\" ? this.workspaces.get(params.workspace) : undefined;\n if (!ws || typeof params.from !== \"string\" || !ws.members.has(params.from)) return;\n // A signed copy of a call already on the log is not a new attempt by its\n // signer. A copy of a refusal was answered with it, and a copy of a call\n // that took effect repeats a call its signer made once. Anyone who can\n // read the log can send either.\n if (isSigned(envelope)) {\n const index = this.signedIndex(ws);\n const digest = signedDigest(envelope);\n if (index.refused.has(digest) || index.accepted.has(digest)) return;\n }\n this.appendEntry(ws, {\n request: JSON.parse(JSON.stringify(envelope)) as Envelope,\n outcome: { status: \"refused\", code: error.code },\n });\n }\n\n /** The signed calls on this workspace's log, built from the log when missing. */\n private signedIndex(ws: Workspace): SignedIndex {\n let index = this.signedIndexes.get(ws);\n if (!index) {\n index = { refused: new Map(), accepted: new Set() };\n for (const entry of ws.audit) indexSigned(index, entry);\n this.signedIndexes.set(ws, index);\n }\n return index;\n }\n\n private appendEntry(ws: Workspace, record: Pick<AuditEntry, \"envelope\" | \"request\" | \"outcome\">): void {\n const entry: AuditEntry = { seq: ws.audit.length, arrived: this.now(), ...record };\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(entryRecord(entry), prev);\n }\n ws.audit.push(entry);\n const index = this.signedIndexes.get(ws);\n if (index) indexSigned(index, 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;\n const wsId = params.workspace;\n const rawTs = params.ts;\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. A `from` or `workspace` that is not a string names\n // nothing, so it counts as missing.\n if (typeof sender !== \"string\" || !sender || typeof wsId !== \"string\" || !wsId) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: missing from/workspace\");\n }\n // The key is chosen by the time the sender gives. A `ts` that is not a\n // string gives no time, so no key can be chosen for it.\n if (rawTs !== undefined && rawTs !== null && typeof rawTs !== \"string\") {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: ts must be a string\");\n }\n const ts = (rawTs as string | null | undefined) ?? this.now();\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 /**\n * The SPECIFICATION 15.4 check, per method rather than per namespace.\n *\n * Core is always present, so a core method is never gated. The reads in\n * ALWAYS_AVAILABLE are never gated either: a workspace must be able to ask\n * what it is and to check its own chain, and `audit.verify_chain` belongs to\n * `audit-scitt/1.0` while chaining also turns on through an option, so\n * gating it would let a workspace write a hash-linked chain it is refused\n * permission to verify.\n */\n private profileGate(method: string, params: Record<string, unknown>) {\n const owner = OWNING_PROFILE[method];\n if (owner === undefined || owner === \"core/1.0\" || ALWAYS_AVAILABLE.has(method)) return undefined;\n const wsId = params.workspace as string | undefined;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n if (!ws) return undefined;\n // Match on the profile name, so a workspace advertising a later minor\n // version of the owning profile still carries its methods.\n const name = owner.split(\"/\")[0];\n if (ws.profiles.some(p => p === name || p.startsWith(name + \"/\"))) return undefined;\n return rpcError(E.METHOD, `Unknown method: ${method}`,\n { profile: owner, advertised: [...ws.profiles] });\n }\n\n private checkStepUp(params: Record<string, unknown>): { code: number; message: string; data?: unknown } | null {\n // A `from` or `workspace` that is not a string names no member to hold to\n // step-up; the membership check answers such a call.\n const wsId = params.workspace;\n const sender = params.from;\n if (typeof wsId !== \"string\" || typeof sender !== \"string\" || !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\n // SPECIFICATION 15.4: the descriptor and the enforcement agree, and the\n // workspace boundary is where a disagreement surfaces.\n //\n // Advertising a security profile does not turn its enforcement on: that\n // would break every workspace advertising it today without signing, and\n // break it at the second call rather than at configuration time. The rule\n // runs the other way, where it costs nothing. Enforcement on adds the\n // profile, so the descriptor never understates what is enforced; the\n // profile advertised with enforcement off is a configuration error.\n for (const [profile, enforced, option] of [\n [\"security-signed/1.0\", !!this.options.requireSignatures, \"requireSignatures\"],\n [\"identity-oidc/1.0\", this.options.verifyOidcToken !== undefined, \"verifyOidcToken\"],\n ] as [string, boolean, string][]) {\n const name = profile.split(\"/\")[0];\n const advertised = profiles.some(x => x === name || x.startsWith(name + \"/\"));\n if (enforced && !advertised) profiles.push(profile);\n else if (advertised && !enforced) {\n return { error: rpcError(E.PARAMS,\n `${profile} is advertised but ${option} is not configured. ` +\n `A workspace that advertises it and does not enforce it ` +\n `describes a guarantee it does not give.`) };\n }\n }\n\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 // Omitted where the workspace has no chain, which is what the Python\n // reference now sends too: JSON.stringify drops an undefined value, so\n // the two answered the same call differently on the wire.\n ...(ws.chain_head ? { 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 const existing = ws.members.get(uri);\n let tokenVerified = false;\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 // A token binds only to the participant it belongs to. One naming\n // another participant is refused, and a join under an existing member's\n // name must carry a token for that member: the same subject, or, for a\n // member with no verified subject yet, a token naming the member.\n const boundUri = claims.chap_participant_uri;\n const sub = typeof claims.sub === \"string\" && claims.sub !== \"\" ? claims.sub : undefined;\n if (boundUri != null && boundUri !== uri) {\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token is bound to another participant\") };\n }\n if (existing) {\n if (existing.oidc_sub != null) {\n if (sub !== existing.oidc_sub) {\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token subject does not match the member\") };\n }\n } else if (boundUri !== uri) {\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token does not name this member\") };\n }\n }\n member.oidc_sub = sub;\n tokenVerified = true;\n const at = claims.auth_time;\n if (typeof at === \"number\") member.oidc_auth_time = at;\n member.oidc_acr = typeof claims.acr === \"string\" ? claims.acr : 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 && !Array.isArray(p.vc_presentation)) {\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 const holder = [subject.holder, subject.id].find(\n (h): h is string => typeof h === \"string\" && h !== \"\");\n // A join under an existing member's name binds a presentation only from\n // the member's own holder.\n if (existing && (existing.vc_holder == null || holder !== existing.vc_holder)) {\n return { error: rpcError(E.VC_HOLDER_BINDING_INVALID, \"Presentation holder does not match the member\") };\n }\n member.vc_holder = holder;\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 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 (tokenVerified) 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 (typeof assignee !== \"string\" || !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. A mode or review_required of the wrong type is\n // refused, so both references read the same task from the same call.\n if (p.mode !== undefined && p.mode !== null && typeof p.mode !== \"string\") {\n return { error: rpcError(E.PARAMS, \"mode must be a string\") };\n }\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 if (p.review_required !== undefined && p.review_required !== null && typeof p.review_required !== \"boolean\") {\n return { error: rpcError(E.PARAMS, \"review_required must be a boolean\") };\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 // Pausing and resuming both belong to control/1.0. A Core-only workspace\n // that could pause through task.update would hold a task nothing it\n // advertises can lift. A review opens with review.request, or with\n // task.complete on a task that requires one: task.update into\n // review_requested would leave the task under review with no review for a\n // decision to act on.\n const legal: Record<string, string[]> = {\n created: [\"in_progress\", \"declined\"],\n in_progress: [\"in_progress\", \"completed\", \"declined\"],\n review_requested: [\"in_progress\"],\n paused: [\"cancelled\"],\n };\n if (!legal[task.state]?.includes(newState)) {\n return { error: rpcError(E.PARAMS, `Illegal transition ${task.state} -> ${newState}`) };\n }\n // task.complete opens a review rather than completing when one is required.\n // task.update reaches the same state by another route and carries no\n // output, so completing here would record a finished task with nothing\n // reviewed and no decision on the chain.\n if (newState === \"completed\" && task.review_required) {\n return { error: rpcError(E.PARAMS,\n \"This task requires review. Submit the output with task.complete, which opens the review; a reviewer decision completes it.\") };\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 if (!task.review) {\n // review_required means a person has to see this. The producer must\n // not satisfy its own review, and neither must another agent: an agent\n // approving an agent leaves a decide.approve on the chain that reads\n // as human oversight and is not. So the implicit review is addressed\n // to the human members other than the completer and the assignee, and\n // where there are none the completion is refused rather than opening a\n // review no person can decide. An explicit review.request keeps its\n // own `to`, so a deliberate agent-reviews-agent flow is still\n // available.\n const producer = p.from as string;\n const eligible = [...ws.members.entries()]\n .filter(([uri, member]) => uri !== producer && uri !== task.assignee && member.type === \"human\")\n .map(([uri]) => uri);\n if (eligible.length === 0) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"Task requires review but has no eligible human reviewer (needs a human 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.pending_artefact = p.output;\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 {\n method?: string; from?: string; task_id?: string; outcome?: unknown;\n } | undefined) ?? {};\n if (filter.outcome != null && filter.outcome !== \"accepted\" && filter.outcome !== \"refused\") {\n return { error: rpcError(E.PARAMS, \"filter.outcome must be 'accepted' or 'refused'\") };\n }\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 // Filters read the call an entry records, accepted or refused, and\n // `outcome` narrows to one kind.\n const refused = entry.outcome != null;\n if (filter.outcome === \"accepted\" && refused) continue;\n if (filter.outcome === \"refused\" && !refused) continue;\n const call = entryCall(entry) ?? ({} as Envelope);\n const ep = (call.params ?? {}) as Record<string, unknown>;\n if (filter.method && call.method !== filter.method) continue;\n if (filter.from && ep.from !== filter.from) continue;\n if (filter.task_id) {\n let taskId = ep.task_id;\n if (call.method === \"whisper.answer\") {\n const prompt = ws.whispers.get(ep.whisper_id as string);\n taskId = prompt ? (prompt as { task_id?: string }).task_id : undefined;\n }\n if (taskId !== filter.task_id) continue;\n }\n const item: Record<string, unknown> = { seq: entry.seq, arrived: entry.arrived };\n if (refused) {\n item.request = entry.request;\n item.outcome = entry.outcome;\n } else {\n item.envelope = entry.envelope;\n }\n if (entry.prev_hash) item.prev_hash = entry.prev_hash;\n out.push(item);\n }\n // The next entry to read: the end of the range, or the end of the log\n // where the range runs past it, so a reader paging forward meets the\n // entries written after this read.\n return { result: { entries: out, next_seq: Math.min(toSeq, ws.audit.length) } };\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 // task.complete refuses a task that has been stopped, so that a completion\n // \"can neither revive a terminated task nor bypass a pause\". review.request\n // creates the same kind of state and had no such check, so it revived\n // cancelled and superseded tasks and pulled paused ones back into play. The\n // same three states are refused here.\n //\n // `completed` is deliberately still allowed. Requesting review on a\n // completed task is how every framework bridge submits a draft, and\n // 0.2.12's `review_required` is the route away from that, not this.\n if (REVIEW_REQUEST_STOPPED.includes(task.state)) {\n return { error: rpcError(E.NOT_REVIEWABLE, `Cannot request review for task in state: ${task.state}`) };\n }\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 declaredRule = p.rule as string | undefined;\n const rule = declaredRule || \"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 // Only a rule the caller actually supplied can be a change. Comparing\n // the resolved default instead refused the documented\n // widen-the-reviewer-set request whenever `rule` was omitted.\n if (declaredRule !== undefined && declaredRule !== 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 origId = p.original_task_id;\n const orig = typeof origId === \"string\" ? ws.tasks.get(origId) : undefined;\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 if (p.new_task === null || typeof p.new_task !== \"object\" || Array.isArray(p.new_task)) {\n return { error: rpcError(E.PARAMS, \"new_task must be an object\") };\n }\n const nt = p.new_task as Record<string, unknown>;\n const assignee = nt.assignee;\n if (typeof assignee !== \"string\" || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"Escalation assignee not in workspace\") };\n }\n const named = nt.mode;\n if (named !== undefined && named !== null && typeof named !== \"string\") {\n return { error: rpcError(E.PARAMS, \"new_task.mode must be a string\") };\n }\n // The successor is a created task, so it meets the checks task.create and\n // control.supersede apply: its assignee must not be paused, and its mode,\n // the one new_task names or else the original's, must be within the\n // ceiling in force now. Naming a lower mode is how work is escalated\n // after the ceiling has been lowered.\n if (ws.members.get(assignee)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${assignee} is paused`) };\n }\n const mode = ((named as Mode | null | undefined) || orig.mode) as Mode;\n if (!modeLE(mode, ws.mode_ceiling)) {\n return { error: rpcError(E.MODE_CEILING_EXCEEDED,\n `Requested mode ${mode} exceeds ceiling ${ws.mode_ceiling}`) };\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,\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 // Escalating hands the work on and keeps its review requirement. The\n // successor requires review when the original did, and a trial task\n // forces review under modes/1.0 as it does at task.create.\n if (orig.review_required || (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && newTask.mode === \"trial\")) {\n newTask.review_required = true;\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 * apply the same review-depth and escalation rules. Routing differs: this\n * routing policy takes the first candidate as given, so a first candidate\n * who is not a member is refused with -32510 and one who is paused with\n * -32063, where the built-in default passes over both. This factory exists\n * so that the legacy 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.3. 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 /** Optional id of the decision this call fulfils; recorded as a ``fulfils`` link on the result artefact. Asserted by the caller and not verified by the coordinator. */\n fulfils?: 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 output: Record<string, unknown> = { result: options.result, citations };\n if (options.fulfils) output.fulfils = options.fulfils;\n const completeParams: Record<string, unknown> = {\n workspace,\n from: options.caller,\n task_id: taskId,\n output,\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 /** Optional id of the decision this exchange fulfils; recorded as a ``fulfils`` link on the result artefact. Asserted by the caller and not verified by the coordinator. */\n fulfils?: 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 output: Record<string, unknown> = { received: options.received, citations: [citation] };\n if (options.fulfils) output.fulfils = options.fulfils;\n const completeParams: Record<string, unknown> = {\n workspace, from: options.bridgeUri, task_id: taskId,\n output,\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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBA,yBAA2B;AAEpB,IAAM,YAAY,YAAY,IAAI,OAAO,EAAE;AAElD,IAAM,oBACJ;AAEF,IAAM,qBACJ;AAGF,IAAM,uBACJ;AAGF,SAAS,sBAAsB,GAAiB;AAC9C,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AACjC,UAAM,IAAI,EAAE,WAAW,CAAC;AACxB,QAAI,KAAK,SAAU,KAAK,OAAQ;AAC9B,YAAM,OAAO,IAAI,IAAI,EAAE,SAAS,EAAE,WAAW,IAAI,CAAC,I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I,MAAM,yBAAyB,KAAK,UAAU,aAAa,KAAK,CAAC,EAAE;AAErG,SAAO,EAAE,SAAS,QAAQ,WAAW,UAAU,eAAe,aAAa;AAC7E;","names":["import_node_crypto","nodeSign","nodeVerify","call","call","wsId","CRIT"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/canonical.ts","../src/catalogue.ts","../src/crypto.ts","../src/ids.ts","../src/jsonrpc.ts","../src/audit.ts","../src/patch.ts","../src/storage/store.ts","../src/tracked.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\n *\n * Public entry point. Re-exports the Coordinator class and the\n * supporting types so consumers can `import { Coordinator } from \"@brightbeamai/chap-coordinator\"`.\n *\n * Architecture:\n *\n * coordinator.ts The Coordinator class with Core + review/1.0 handlers\n * and the dispatch/registration infrastructure.\n * profiles/*.ts One module per optional profile, each registers its\n * method handlers on a Coordinator instance.\n * canonical.ts JCS canonicalisation (RFC 8785).\n * crypto.ts Ed25519 signing/verification (Node built-ins).\n * ids.ts ULID-format id generation.\n * jsonrpc.ts Error codes and helpers.\n * patch.ts RFC 6902 JSON Patch.\n * types.ts Wire and in-memory types.\n */\n\nexport { Coordinator, PRIVILEGED_METHODS } from \"./coordinator.js\";\nexport type {\n CoordinatorOptions,\n Handler,\n TokenVerifier,\n CredentialVerifier,\n ScittSubmitter,\n ScittReceiptVerifier,\n RoutingPolicyFn,\n ReviewDepthPolicyFn,\n EscalationPolicyFn,\n} from \"./coordinator.js\";\n\nexport { call, makeApi, CoordinatorError } from \"./api.js\";\nexport type { CoordinatorApi } from \"./api.js\";\nexport type {\n MethodName,\n MethodParams,\n MethodResult,\n MethodTable,\n} from \"./methods.js\";\n\nexport { entryCall, entryRecord, isRefusal, linkHash } from \"./audit.js\";\n\nexport { MemoryStore, StoreConflictError } from \"./storage/store.js\";\nexport type { Store, StoreChange, WorkspaceRecord } from \"./storage/store.js\";\n\nexport * from \"./types.js\";\nexport * from \"./jsonrpc.js\";\nexport * from \"./patch.js\";\nexport {\n canonicalize, sha256Hex, contentHash, ZERO_HASH,\n} from \"./canonical.js\";\nexport {\n deriveKeypair, deriveSeed, jwkFromPrivateKey,\n publicKeyBytes, publicKeyFromJwk, publicKeyFromRaw,\n signEnvelope, verifyEnvelope,\n} from \"./crypto.js\";\nexport type { Jwk as CryptoJwk } from \"./crypto.js\";\nexport { IdFactory } from \"./ids.js\";\nexport { makeDefaultPolicy } from \"./policy.js\";\n\nexport {\n wrapMcpToolCall,\n wrapA2aMessageExchange,\n} from \"./transports/wrap.js\";\nexport type {\n WrapMcpToolCallOptions,\n WrapA2aExchangeOptions,\n WrapResult,\n WrapA2aResult,\n} from \"./transports/wrap.js\";\n","/**\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\nconst LONE_SURROGATE_ERROR =\n \"CHAP canonical strings must be valid Unicode (I-JSON / RFC 7493); \" +\n \"unpaired UTF-16 surrogates are not permitted.\";\n\nfunction assertNoLoneSurrogate(s: string): void {\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c >= 0xd800 && c <= 0xdbff) {\n const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;\n if (next < 0xdc00 || next > 0xdfff) throw new Error(LONE_SURROGATE_ERROR);\n i++;\n } else if (c >= 0xdc00 && c <= 0xdfff) {\n throw new Error(LONE_SURROGATE_ERROR);\n }\n }\n}\n\nfunction canonicalString(s: string): string {\n assertNoLoneSurrogate(s);\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","// Generated by scripts/sync-method-catalogue.mjs. Do not edit.\n// Source: schemas/profiles/chap-methods.schema.json\n/**\n * Which profile owns which method, and which methods are never gated.\n *\n * SPECIFICATION 15.4: a Coordinator refuses a method whose owning profile the\n * workspace does not advertise.\n * The rule applies to each method, since a namespace can span profiles: audit\n * spans audit-scitt and core; escalate spans review and routing; review spans\n * review and routing; task spans core and routing.\n */\n\n/** The profile that introduces each method the references implement. */\nexport const OWNING_PROFILE: Readonly<Record<string, string>> = Object.freeze({\n \"abstain.declare\": \"review/1.0\",\n \"audit.read\": \"core/1.0\",\n \"audit.submit_to_scitt\": \"audit-scitt/1.0\",\n \"audit.verify_chain\": \"audit-scitt/1.0\",\n \"audit.verify_receipt\": \"audit-scitt/1.0\",\n \"control.cancel\": \"control/1.0\",\n \"control.pause\": \"control/1.0\",\n \"control.resume\": \"control/1.0\",\n \"control.rollback\": \"control/1.0\",\n \"control.set_mode_ceiling\":\"control/1.0\",\n \"control.snapshot\": \"control/1.0\",\n \"control.supersede\": \"control/1.0\",\n \"decide.approve\": \"review/1.0\",\n \"decide.override\": \"review/1.0\",\n \"decide.reject\": \"review/1.0\",\n \"deliberate.close\": \"deliberation/1.0\",\n \"deliberate.comment\": \"deliberation/1.0\",\n \"deliberate.open\": \"deliberation/1.0\",\n \"deliberate.vote\": \"deliberation/1.0\",\n \"escalate.auto\": \"routing/1.0\",\n \"escalate.raise\": \"review/1.0\",\n \"handoff.accept\": \"handoff/1.0\",\n \"handoff.decline\": \"handoff/1.0\",\n \"handoff.propose\": \"handoff/1.0\",\n \"participant.join\": \"core/1.0\",\n \"participant.leave\": \"core/1.0\",\n \"participant.revoke_key\": \"core/1.0\",\n \"participant.rotate_key\": \"core/1.0\",\n \"review.depth\": \"routing/1.0\",\n \"review.request\": \"review/1.0\",\n \"task.complete\": \"core/1.0\",\n \"task.create\": \"core/1.0\",\n \"task.route\": \"routing/1.0\",\n \"task.update\": \"core/1.0\",\n \"whisper.answer\": \"whisper/1.0\",\n \"whisper.ask\": \"whisper/1.0\",\n \"workspace.create\": \"core/1.0\",\n \"workspace.describe\": \"core/1.0\",\n \"workspace.set_profiles\": \"core/1.0\",\n});\n\n/**\n * Callable whatever the workspace advertises.\n *\n * Reads, because a workspace must always be able to ask what it is and to\n * check its own chain. Not the coordinator's read-only set: that holds\n * audit.submit_to_scitt, which reaches a transparency service and is a real\n * audit-scitt/1.0 capability.\n */\nexport const ALWAYS_AVAILABLE: ReadonlySet<string> = new Set([\n \"workspace.describe\",\n \"audit.read\",\n \"audit.verify_chain\",\n \"audit.verify_receipt\",\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/audit\n *\n * Audit entries, the chain link over them, and the rule for recording a\n * refusal (SPECIFICATION 10.1).\n *\n * An accepted call is recorded under `envelope`. A refused call that the rule\n * names is recorded under `request`, with an `outcome` beside it, so a reader\n * keyed on `envelope` passes it by instead of replaying it as effective. The\n * chain link hashes what the entry records: the envelope of an accepted call,\n * and the outcome together with the request of a refusal. Altering either\n * half of a refusal breaks the chain, moving its record under `envelope` fails\n * the shape check, and an entry with no outcome hashes exactly as it always\n * has, so every existing chain still verifies.\n */\nimport { canonicalize, sha256Hex } from \"./canonical.js\";\nimport { E } from \"./jsonrpc.js\";\nimport type { AuditEntry, Envelope } from \"./types.js\";\n\n/** The value an entry's chain link hashes. */\nexport function entryRecord(entry: AuditEntry): unknown {\n if (entry.outcome != null) return { outcome: entry.outcome, request: entry.request };\n return entry.envelope;\n}\n\n/** The call an entry records, whether it took effect or was refused. */\nexport function entryCall(entry: AuditEntry): Envelope | undefined {\n return entry.envelope ?? entry.request ?? undefined;\n}\n\n/** True when an entry records a refused call. */\nexport function isRefusal(entry: AuditEntry): boolean {\n return entry.outcome != null;\n}\n\n/** A JSON-RPC call: an object with `jsonrpc` \"2.0\" and a string `method`. */\nfunction isCall(value: unknown): boolean {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const v = value as Record<string, unknown>;\n return v.jsonrpc === \"2.0\" && typeof v.method === \"string\";\n}\n\n/**\n * An entry is well formed when it records an accepted call alone, under\n * `envelope`, or a refused call alone, under `request`, with an outcome of\n * status `refused` and an integer code. Requiring a JSON-RPC call on either\n * side is what stops a refusal's record being moved under `envelope`, where it\n * would hash to the same bytes and read as a call that took effect.\n */\nexport function entryIsWellFormed(entry: AuditEntry): boolean {\n const accepted = entry.envelope != null;\n const refused = entry.request != null;\n if (accepted === refused) return false;\n if (accepted) return isCall(entry.envelope) && entry.outcome == null;\n const o = entry.outcome as unknown as Record<string, unknown> | null | undefined;\n return isCall(entry.request) && o != null && typeof o === \"object\"\n && o.status === \"refused\" && Number.isInteger(o.code);\n}\n\n/** Whether a call carries a top-level signature (security-signed/1.0). */\nexport function isSigned(call: unknown): boolean {\n return call !== null && typeof call === \"object\" && typeof (call as { sig?: unknown }).sig === \"string\";\n}\n\n/**\n * The digest that identifies a signed call by what its sender signed: SHA-256\n * of the JCS of the call without its `sig`. Two encodings of one signature\n * give the same digest, so re-encoding a signature does not make a new call.\n */\nexport function signedDigest(call: Envelope): string {\n const signed: Record<string, unknown> = { ...call };\n delete signed.sig;\n return sha256Hex(canonicalize(signed));\n}\n\n/** chain_head = SHA-256( JCS(record) || prev_hash ). */\nexport function linkHash(record: unknown, prev: string): string {\n return sha256Hex(Buffer.concat([canonicalize(record), Buffer.from(prev, \"utf-8\")]));\n}\n\n/**\n * Refusals the log never records: a call that was malformed or invalid, a\n * fault in the Coordinator, and a call whose signature or key did not check\n * out.\n */\nconst UNRECORDED_CODES: ReadonlySet<number> = new Set([\n E.PARSE, E.REQUEST, E.PARAMS, E.INTERNAL,\n E.SIG_VERIFY_FAILED, E.SIG_KEY_NOT_FOUND, E.SIG_KEY_REVOKED, E.SIG_ROTATION_KEY_MISMATCH,\n]);\n\n/**\n * Methods whose refusals are never recorded. They run before the caller is\n * established as a member and are exempt from signature checks, so a refusal\n * of one proves nothing about who sent it.\n */\nconst UNRECORDED_METHODS: ReadonlySet<string> = new Set([\"workspace.create\", \"participant.join\"]);\n\n/**\n * Whether a refusal with this error is one the log records, before the test\n * that the caller is a member.\n *\n * `-32601` is recorded only when the profile gate refused a privileged method,\n * which is an attempt to pull an emergency brake the workspace has switched\n * off. The gate refusing an ordinary method, and a method that does not\n * exist, are not recorded.\n */\nexport function refusalIsRecorded(\n method: string,\n error: { code: number; data?: unknown },\n privileged: ReadonlySet<string>,\n): boolean {\n if (!Number.isInteger(error.code)) return false;\n if (UNRECORDED_METHODS.has(method)) return false;\n if (UNRECORDED_CODES.has(error.code)) return false;\n if (error.code === E.METHOD) {\n const data = error.data as { profile?: unknown } | undefined;\n return typeof data?.profile === \"string\" && privileged.has(method);\n }\n return true;\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\n// The JSON type name of a value. Python and JavaScript name their own types\n// differently (dict against object, list against object, str against string).\n// The refusal names the JSON type, which both references and the\n// specification share.\nfunction jsonType(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n switch (typeof value) {\n case \"object\": return \"object\";\n case \"string\": return \"string\";\n case \"number\": return \"number\";\n case \"boolean\": return \"boolean\";\n default: return \"null\";\n }\n}\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 ${jsonType(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 ${jsonType(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 // RFC 6901: \"-\" names the position after the last element, which no\n // element occupies, so only \"add\" can use it. Left as a string it slips\n // through a numeric range check and writes a \"-\" property on the array.\n const idx = key === \"-\" ? -1 : (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 ${jsonType(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 // RFC 6901: \"-\" names no existing element, so it cannot be removed.\n // Left as a string it passes the numeric range check and then splice\n // coerces it to zero, removing the first element instead.\n const idx = key === \"-\" ? -1 : (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 ${jsonType(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 keeps workspace state between process restarts. The Coordinator\n * calls `store.load()` once at start, and writes after every call that adds\n * to a workspace's audit log.\n *\n * How the Coordinator writes depends on what the store implements:\n *\n * - `apply(change)`: the Coordinator sends what the call changed: the new\n * audit entries, the objects it touched and the workspace's own fields.\n * The cost of a write stays flat as the log grows; it grows with the\n * objects a call changes, such as a task with a long history. MemoryStore\n * and SqliteStore implement it.\n * - `save(record)` alone: the Coordinator sends the whole workspace on every\n * write, as releases before 0.3.2 did, so the cost of a write grows with\n * the log. Stores written for earlier releases keep working this way.\n *\n * MemoryStore is the default and keeps nothing across processes. SqliteStore\n * keeps state in a SQLite file through better-sqlite3. Third-party stores\n * (Postgres, Redis and so on) implement this interface.\n *\n * Concurrency model\n * -----------------\n *\n * A Coordinator is a **single-writer** component: dispatch is serial,\n * workspace state is held in memory, and each chain link is computed from the\n * head the instance holds. Run one Coordinator per workspace.\n *\n * Every change names the number of audit entries the Coordinator expects the\n * store to hold already (`base`). MemoryStore and SqliteStore refuse a change\n * whose base differs from what they hold: they throw a StoreConflictError and\n * write nothing. A second Coordinator writing the same workspace is refused\n * and reported, and the entries already stored stay as they are. The refused\n * instance's memory no longer matches the store; restart it to reload.\n *\n * `save` makes no such check: it replaces what the store holds for the\n * workspace. A store that implements only `save` therefore still loses\n * entries silently when two instances write one workspace.\n *\n * To run more than one instance, partition workspaces so that no workspace is\n * ever written by two, or hold an external lock. See SPECIFICATION.md 10.3.\n *\n * Production deployments that need rich queries over the log can project it\n * into their own analytics store with the `onAudit` listener.\n */\n\n/** The workspace maps a store keeps object by object. */\nexport const COLLECTIONS = [\n \"members\", \"tasks\", \"overrides\", \"whispers\",\n \"deliberations\", \"handoffs\", \"snapshots\", \"route_decisions\",\n] as const;\n\n/** task.create idempotency keys, kept as one more collection of key to task id. */\nexport const IDEMPOTENCY_KEYS = \"idempotency_keys\";\n\nexport interface WorkspaceRecord {\n /** Workspace identifier. */\n id: string;\n /** JSON-serialisable payload in the shape `Coordinator.snapshot()` produces. */\n data: unknown;\n /**\n * For `save`, a counter the Coordinator increments on each write. For a\n * record a store loads after `apply`, the number of audit entries. Recorded\n * for diagnostics; `save` does not check it.\n */\n version: number;\n /** Wall-clock timestamp of the last write, ISO-8601. */\n updated_at: string;\n}\n\n/** One write to one workspace: what one or more calls changed. */\nexport interface StoreChange {\n /** Workspace identifier. */\n id: string;\n /**\n * Audit entries the store must already hold for this workspace. A store\n * that holds a different number refuses the change with a\n * StoreConflictError and writes nothing. Not checked when `replace` is set.\n */\n base: number;\n /** Audit entries the store holds after the change: `base + entries.length`. */\n version: number;\n /** Wall-clock timestamp of the write, ISO-8601. */\n updated_at: string;\n /** The workspace's own fields: everything except its collections and log. */\n meta: Record<string, unknown>;\n /** New audit entries in order. The first has seq `base`. */\n entries: unknown[];\n /**\n * Objects written, by collection and then by key. A null value removes the\n * object. The collections are those in COLLECTIONS and IDEMPOTENCY_KEYS.\n */\n objects: Record<string, Record<string, unknown>>;\n /**\n * Replace everything the store holds for this workspace with this change,\n * which then carries the whole workspace from seq 0.\n */\n replace?: boolean;\n}\n\n/**\n * A change whose base does not match the audit entries the store holds.\n * Usually a second Coordinator writing the same workspace.\n */\nexport class StoreConflictError extends Error {\n readonly workspace: string;\n /** Audit entries the store holds. */\n readonly held: number;\n /** Audit entries the change expected. */\n readonly base: number;\n\n constructor(workspace: string, held: number, base: number) {\n super(\n `The store holds ${held} audit entries for workspace ${workspace} and ` +\n `this write expected ${base}, so nothing was written. Another ` +\n `coordinator may be writing to this workspace, the store may have been ` +\n `changed outside this coordinator, or this coordinator could not load ` +\n `the workspace when it started. Restart this coordinator to reload.`,\n );\n this.name = \"StoreConflictError\";\n this.workspace = workspace;\n this.held = held;\n this.base = base;\n }\n\n /**\n * Matched by name, so `instanceof` holds across the package's entry points,\n * each of which is bundled with its own copy of this class.\n */\n static [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === \"StoreConflictError\";\n }\n}\n\nexport interface Store {\n /** Load all workspace records. Called once when the Coordinator starts. */\n load(): Promise<WorkspaceRecord[]> | WorkspaceRecord[];\n\n /**\n * Replace what the store holds for one workspace. The Coordinator calls it\n * after every write when the store has no `apply`.\n */\n save(record: WorkspaceRecord): Promise<void> | void;\n\n /**\n * Write one change. Optional; when present the Coordinator calls it in\n * place of `save`. It must be atomic: the whole change is written, or\n * nothing is. The change refers to the Coordinator's live objects, so\n * serialise or copy everything before returning, including in an async\n * store. Refuse a change whose `base` differs from the entries held, unless\n * `replace` is set, by throwing (or rejecting with) a StoreConflictError.\n */\n apply?(change: StoreChange): Promise<void> | void;\n\n /** Remove one workspace. */\n delete(id: string): Promise<void> | void;\n\n /** Release resources. Idempotent. */\n close?(): Promise<void> | void;\n}\n\nfunction isCollection(name: string): boolean {\n return (COLLECTIONS as readonly string[]).includes(name);\n}\n\n/** The key an object is stored under in its collection. */\nexport function objectKey(collection: string, item: unknown): string | undefined {\n if (item === null || typeof item !== \"object\") return undefined;\n const o = item as Record<string, unknown>;\n const key = collection === \"members\" ? (o.uri ?? o.id) : (o.id ?? o.uri);\n return typeof key === \"string\" ? key : undefined;\n}\n\n/**\n * A collection as a snapshot holds it, keyed. The TypeScript snapshot holds\n * arrays and the Python snapshot holds objects keyed by id; both are read.\n */\nfunction keyed(collection: string, value: unknown): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const key = objectKey(collection, item);\n if (key !== undefined) out[key] = item;\n }\n } else if (value !== null && typeof value === \"object\") {\n Object.assign(out, value);\n }\n return out;\n}\n\n/** A whole-workspace snapshot as a change that replaces what the store holds. */\nexport function changeFromRecord(record: WorkspaceRecord): StoreChange {\n const data = (record.data !== null && typeof record.data === \"object\"\n ? record.data : {}) as Record<string, unknown>;\n const meta: Record<string, unknown> = {};\n const objects: Record<string, Record<string, unknown>> = {};\n let entries: unknown[] = [];\n for (const [name, value] of Object.entries(data)) {\n if (name === \"audit\") entries = Array.isArray(value) ? value : [];\n else if (name === IDEMPOTENCY_KEYS || isCollection(name)) objects[name] = keyed(name, value);\n else meta[name] = value;\n }\n if (meta.id === undefined) meta.id = record.id;\n return {\n id: record.id, base: 0, version: record.version, updated_at: record.updated_at,\n meta, entries, objects, replace: true,\n };\n}\n\n/**\n * Rows read back from a store, assembled into the snapshot shape\n * `Coordinator.restore()` reads: arrays for the collections, an object for\n * the idempotency keys, and the log in seq order.\n */\nexport function assembleSnapshot(\n meta: Record<string, unknown>,\n entries: unknown[],\n objects: Iterable<[collection: string, key: string, value: unknown]>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = { ...meta };\n for (const name of COLLECTIONS) data[name] = [];\n const keys: Record<string, unknown> = {};\n data[IDEMPOTENCY_KEYS] = keys;\n for (const [collection, key, value] of objects) {\n if (collection === IDEMPOTENCY_KEYS) {\n keys[key] = value;\n } else {\n const list = (Array.isArray(data[collection]) ? data[collection] : (data[collection] = [])) as unknown[];\n list.push(value);\n }\n }\n data.audit = entries;\n return data;\n}\n\ninterface Held {\n meta: string;\n version: number;\n updated_at: string;\n entries: string[];\n objects: Map<string, Map<string, string>>;\n}\n\n/**\n * In-memory store. The default: it keeps nothing across processes. Like a\n * database it keeps each row as JSON text, so a Coordinator restarted on it\n * sees what was written and nothing changed later.\n */\nexport class MemoryStore implements Store {\n private held = new Map<string, Held>();\n\n load(): WorkspaceRecord[] {\n const out: WorkspaceRecord[] = [];\n for (const [id, h] of this.held) {\n const objects: Array<[string, string, unknown]> = [];\n for (const [collection, items] of h.objects) {\n for (const [key, value] of items) objects.push([collection, key, JSON.parse(value)]);\n }\n out.push({\n id,\n data: assembleSnapshot(JSON.parse(h.meta), h.entries.map(e => JSON.parse(e)), objects),\n version: h.version,\n updated_at: h.updated_at,\n });\n }\n return out;\n }\n\n save(record: WorkspaceRecord): void {\n this.apply(changeFromRecord(record));\n }\n\n apply(change: StoreChange): void {\n // Serialised before anything is held, so a change that cannot be written\n // leaves the store as it was.\n const meta = JSON.stringify(change.meta);\n const entries = change.entries.map(e => JSON.stringify(e));\n const objects = Object.entries(change.objects).map(([collection, items]) =>\n [collection, Object.entries(items).map(([key, value]) =>\n [key, value === null || value === undefined ? null : JSON.stringify(value)] as const)] as const);\n let h = this.held.get(change.id);\n if (!change.replace) {\n const holds = h ? h.entries.length : 0;\n if (holds !== change.base) throw new StoreConflictError(change.id, holds, change.base);\n }\n if (!h || change.replace) {\n h = { meta: \"{}\", version: 0, updated_at: \"\", entries: [], objects: new Map() };\n }\n for (const entry of entries) h.entries.push(entry);\n for (const [collection, items] of objects) {\n let held = h.objects.get(collection);\n if (!held) h.objects.set(collection, (held = new Map()));\n for (const [key, value] of items) {\n if (value === null) held.delete(key);\n else held.set(key, value);\n }\n }\n h.meta = meta;\n h.version = change.version;\n h.updated_at = change.updated_at;\n this.held.set(change.id, h);\n }\n\n delete(id: string): void {\n this.held.delete(id);\n }\n}\n","/**\n * Change tracking for a workspace's maps.\n *\n * When the store implements `apply`, the Coordinator writes only the objects\n * a call changed. A TrackedMap records which keys may hold a changed object\n * since the last write: every key set or deleted, and, while a call is being\n * handled, every key read with `get` or reached by iterating, because a\n * handler changes an object in place after reading it. Reads outside a call,\n * such as an application listing tasks, record nothing.\n */\n\nexport interface Tracker {\n /** Whether anything is recorded: true when the store implements `apply`. */\n enabled: boolean;\n /** Calls being handled. Reads are recorded while it is above zero. */\n depth: number;\n}\n\nexport class TrackedMap<K, V> extends Map<K, V> {\n /** Keys whose objects may have changed since the last write. */\n readonly dirty = new Set<K>();\n readonly tracker: Tracker;\n\n constructor(tracker: Tracker) {\n super();\n this.tracker = tracker;\n }\n\n private reading(): boolean {\n return this.tracker.enabled && this.tracker.depth > 0;\n }\n\n private touchAll(): void {\n if (this.reading()) for (const key of super.keys()) this.dirty.add(key);\n }\n\n override get(key: K): V | undefined {\n const value = super.get(key);\n if (value !== undefined && this.reading()) this.dirty.add(key);\n return value;\n }\n\n override set(key: K, value: V): this {\n if (this.tracker.enabled) this.dirty.add(key);\n return super.set(key, value);\n }\n\n override delete(key: K): boolean {\n const had = super.delete(key);\n if (had && this.tracker.enabled) this.dirty.add(key);\n return had;\n }\n\n override clear(): void {\n if (this.tracker.enabled) for (const key of super.keys()) this.dirty.add(key);\n super.clear();\n }\n\n override values(): MapIterator<V> {\n this.touchAll();\n return super.values();\n }\n\n override entries(): MapIterator<[K, V]> {\n this.touchAll();\n return super.entries();\n }\n\n override [Symbol.iterator](): MapIterator<[K, V]> {\n this.touchAll();\n return super[Symbol.iterator]();\n }\n\n override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {\n this.touchAll();\n super.forEach(callback, thisArg);\n }\n\n /** Read one value without recording it. */\n peek(key: K): V | undefined {\n return super.get(key);\n }\n}\n\n/** Every value of a map, read without recording, whatever kind of map it is. */\nexport function rawValues<V>(map: Map<unknown, V>): IterableIterator<V> {\n return Map.prototype.values.call(map) as IterableIterator<V>;\n}\n\n/** Every entry of a map, read without recording, whatever kind of map it is. */\nexport function rawEntries<K, V>(map: Map<K, V>): IterableIterator<[K, V]> {\n return Map.prototype.entries.call(map) as IterableIterator<[K, V]>;\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 produced_at: string;\n produced_by: ParticipantUri;\n content_hash: string;\n content: {\n workspace: WorkspaceId;\n audit_seq: number;\n label?: string;\n include: string[];\n state: Record<string, unknown>;\n };\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 paused_from?: TaskState;\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 /** The accepted call. Absent on a refusal entry. */\n envelope?: Envelope;\n /**\n * The refused call, as received. Present only on a refusal entry, and held\n * here rather than under `envelope` so a reader keyed on `envelope` passes\n * the refusal by instead of replaying it (SPECIFICATION 10.1).\n */\n request?: Envelope;\n /** Present only on a refusal entry. */\n outcome?: RefusalOutcome;\n prev_hash?: string;\n}\n\n/** Why a recorded call did not take effect. */\nexport interface RefusalOutcome {\n status: \"refused\";\n /** The error code the caller was answered with. */\n code: number;\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 { entryIsWellFormed, entryRecord, linkHash } from \"../audit.js\";\nimport { canonicalize, ZERO_HASH } from \"../canonical.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\n\n/** The head after a malformed entry, which no stored head can match. */\nconst MALFORMED = \"sha256:malformed\";\n\n/**\n * A statement's payload is what the entry's chain link hashes: the envelope\n * of an accepted call, or the outcome together with the request of a refusal.\n */\nfunction buildStatement(workspaceId: string, record: unknown, 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.3\",\n },\n payload: canonicalize(record).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, entryRecord(e), 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, entryRecord(entry), 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 let resync = false;\n for (const e of ws.audit.slice(start)) {\n // After a malformed entry the next link is taken as stored, so the\n // entries after it are judged on their own links. The chain is\n // reported broken either way.\n const expectedPrev = resync && typeof e.prev_hash === \"string\" ? e.prev_hash : prev;\n resync = false;\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 // An entry that records neither one accepted envelope nor one refused\n // request with its outcome has been altered, and cannot be linked.\n if (!entryIsWellFormed(e)) {\n errors.push(`seq ${e.seq}: malformed entry`);\n prev = MALFORMED;\n resync = true;\n continue;\n }\n prev = linkHash(entryRecord(e), expectedPrev);\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 { contentHash } from \"../canonical.js\";\nimport { rawValues } from \"../tracked.js\";\nimport { modeLE } from \"../types.js\";\nimport type { Mode, SnapshotArtefact, Task, TaskState } 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 if (prior !== \"paused\") task.paused_from = prior;\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 const restored: TaskState = task.paused_from ?? \"in_progress\";\n task.paused_from = undefined;\n task.state = restored;\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: restored });\n return { result: { scope: \"task\", task_id: task.id, state: restored } };\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 if (Array.isArray(p.include) && p.include.length === 0) {\n return { error: rpcError(E.PARAMS, \"include must not be empty\") };\n }\n const include: string[] = Array.isArray(p.include)\n ? [...p.include as string[]]\n : [\"members\", \"open_tasks\", \"mode_ceiling\"];\n const state: Record<string, unknown> = {};\n if (include.includes(\"members\")) {\n // Read-only projections: read without recording a change.\n const members = Array.from(rawValues(ws.members)).map(m => ({\n uri: m.uri, type: m.type,\n ...(m.role ? { role: m.role } : {}),\n ...(m.scopes?.length ? { scopes: m.scopes } : {}),\n }));\n if (members.length) state.members = members;\n }\n if (include.includes(\"open_tasks\")) {\n const tasks = Array.from(rawValues(ws.tasks))\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,\n ...(t.assignee ? { assignee: t.assignee } : {}),\n }));\n if (tasks.length) state.open_tasks = tasks;\n }\n if (include.includes(\"mode_ceiling\")) state.mode_ceiling = ws.mode_ceiling;\n if (include.includes(\"policy\") && ws.routing_policy_uri) state.routing_policy_uri = ws.routing_policy_uri;\n if (include.includes(\"audit\") || include.includes(\"all\")) state.audit_seq = ws.audit.length;\n\n // Store the same canonical artefact that is emitted on the wire. Copies\n // belong to this explicit capture boundary, never Coordinator.snapshot().\n const content: SnapshotArtefact[\"content\"] = structuredClone({\n workspace: ws.id,\n audit_seq: ws.audit.length,\n include,\n state,\n ...(p.label ? { label: p.label as string } : {}),\n });\n const snapId = coord.ids.artefactId();\n const snap: SnapshotArtefact = {\n id: snapId,\n kind: \"snapshot\",\n produced_at: coord.now(),\n produced_by: p.from as string,\n content_hash: contentHash(content),\n content,\n };\n ws.snapshots.set(snapId, snap);\n return {\n result: {\n snapshot_artefact_id: snapId,\n audit_seq: snap.content.audit_seq,\n artefact: structuredClone(snap),\n },\n };\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 if (Array.isArray(p.what_to_restore) && p.what_to_restore.length === 0) {\n return { error: rpcError(E.PARAMS, \"what_to_restore must not be empty\") };\n }\n const what: string[] = (p.what_to_restore as string[]) ?? snap.content.include;\n const restored: string[] = [];\n if (what.includes(\"mode_ceiling\") && snap.content.state.mode_ceiling) {\n ws.mode_ceiling = snap.content.state.mode_ceiling as Mode;\n restored.push(\"mode_ceiling\");\n }\n if (what.includes(\"members\") && Array.isArray(snap.content.state.members)) {\n const snapByUri = new Map<string, Record<string, unknown>>();\n for (const m of snap.content.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 = Array.isArray(snapM.scopes) ? [...snapM.scopes as string[]] : undefined;\n }\n }\n restored.push(\"members\");\n }\n return { result: {\n rolled_back_to: snapId, audit_seq: snap.content.audit_seq, restored,\n ...(p.reason ? { reason: p.reason as string } : {}),\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 (typeof assignee !== \"string\" || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"successor assignee not in workspace\") };\n }\n // The successor is a created task, so the participant-paused check\n // task.create applies has to apply here too. Without it, superseding is a\n // way to hand work to a participant whose work was stopped.\n if (ws.members.get(assignee)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${assignee} is paused`) };\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 if (newSpec.mode !== undefined && newSpec.mode !== null && typeof newSpec.mode !== \"string\") {\n return { error: rpcError(E.PARAMS, \"successor_task.mode must be a string\") };\n }\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 if (newSpec.review_required !== undefined && newSpec.review_required !== null\n && typeof newSpec.review_required !== \"boolean\") {\n return { error: rpcError(E.PARAMS, \"successor_task.review_required must be a boolean\") };\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 // A successor keeps the review requirement of the task it replaces, so\n // superseding never removes a required review. Trial forces review only\n // when the workspace opted into modes/1.0, matching task.create, since\n // mode is inert without the profile. Otherwise the spec's own setting\n // applies.\n if (old.review_required || (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && newTask.mode === \"trial\")) {\n newTask.review_required = true;\n } else if (\"review_required\" in newSpec) {\n newTask.review_required = !!newSpec.review_required;\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 // Accepting makes the acceptor the assignee. A paused participant is\n // assigned no new tasks (control/1.0), so it cannot take tasks this way.\n if (ws.members.get(acceptor)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Acceptor ${acceptor} is paused`) };\n }\n // Omission accepts all proposed tasks; an empty selection is not a handoff.\n if (Array.isArray(p.accepted_task_ids) && p.accepted_task_ids.length === 0) {\n return { error: rpcError(E.PARAMS, \"accepted_task_ids must not be empty\") };\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 if (p.candidates !== undefined && p.candidates !== null && !Array.isArray(p.candidates)) {\n return { error: rpcError(E.PARAMS, \"candidates must be a list\") };\n }\n const candidates = (p.candidates as string[] | null | undefined) ?? [];\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 // A paused participant is assigned no new tasks (control/1.0), so the\n // default policy passes over one as it passes over a non-member, and\n // names it among the alternatives with that reason.\n const memberOf = (c: unknown) => (typeof c === \"string\" ? ws.members.get(c) : undefined);\n const eligible = candidates.filter(c => { const m = memberOf(c); return !!m && !m.paused; });\n if (!eligible.length) {\n return { error: rpcError(E.ROUTING_NO_ELIGIBLE_ASSIGNEE, \"No candidate is a workspace member who is not paused\") };\n }\n selected = eligible[0];\n const alternatives: Array<{ candidate: string; reason_excluded: string }> = [];\n let chosen = false;\n for (const c of candidates) {\n const m = memberOf(c);\n if (!m) continue;\n if (m.paused) alternatives.push({ candidate: c, reason_excluded: \"paused\" });\n else if (!chosen) chosen = true;\n else alternatives.push({ candidate: c, reason_excluded: \"not first eligible\" });\n }\n rationale = {\n policy_id: \"default\",\n hints_used: Object.keys(task.routing_hints ?? {}),\n summary: \"default policy: first eligible candidate\",\n alternatives_considered: alternatives,\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 // An operator policy can pick a paused participant. Routing to one would\n // assign a task to a participant whose work was stopped, so it is refused\n // as task.create refuses a paused assignee.\n if (ws.members.get(selected)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${selected} is paused`) };\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 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 }\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 (coord.options.onAutoEscalate && to) {\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 { canonicalize } from \"../canonical.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\n/**\n * Whether an answer field holds anything, read as Python reads a value's\n * truth, so both references agree that an empty answer is no answer.\n */\nfunction present(v: unknown): boolean {\n if (v === undefined || v === null || v === false || v === 0 || v === \"\") return false;\n if (Array.isArray(v)) return v.length > 0;\n if (typeof v === \"object\") return Object.keys(v as object).length > 0;\n return true;\n}\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 if (p.options !== undefined && p.options !== null && !Array.isArray(p.options)) {\n return { error: rpcError(E.PARAMS, \"options must be a list\") };\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 // A null option is no option, and an empty answer no answer, as in Python.\n const answerOption = p.answer_option as string | undefined;\n const hasOption = answerOption !== undefined && answerOption !== null;\n const answerText = (present(p.answer) ? p.answer : p.answer_text) as string | undefined;\n if (prompt.options && prompt.options.length) {\n if (!hasOption) {\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 ${canonicalize(answerOption as never).toString(\"utf-8\")} not in option set`) };\n }\n } else if (!present(answerText) && !hasOption) {\n return { error: rpcError(E.PARAMS, \"answer or answer_option required\") };\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 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 // Set again so the change is written: a lapse check runs outside any\n // call, where reading the prompt records nothing.\n ws.whispers.set(prompt.id, prompt);\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, ZERO_HASH } from \"./canonical.js\";\nimport { ALWAYS_AVAILABLE, OWNING_PROFILE } from \"./catalogue.js\";\nimport { publicKeyFromJwk, verifyEnvelope } from \"./crypto.js\";\nimport { IdFactory } from \"./ids.js\";\nimport { E, isValidEnvelope, rpcError } from \"./jsonrpc.js\";\nimport { entryCall, entryRecord, isSigned, linkHash, refusalIsRecorded, signedDigest } from \"./audit.js\";\nimport { applyJsonPatch } from \"./patch.js\";\nimport type { Store, StoreChange, WorkspaceRecord } from \"./storage/store.js\";\nimport { COLLECTIONS, IDEMPOTENCY_KEYS, MemoryStore } from \"./storage/store.js\";\nimport { TrackedMap, rawEntries, rawValues, type Tracker } from \"./tracked.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 SnapshotArtefact,\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// Methods outside the control, deliberate, handoff and whisper namespaces that\n// dispatch holds to the membership floor before the handler runs.\nconst MEMBER_ONLY_METHODS = new Set<string>([\n \"task.route\", \"review.depth\", \"escalate.auto\", \"participant.leave\",\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 // Submitting the chain to a transparency service reads it and sends it\n // onward. Recording the submission would append to the very log being\n // submitted, so the receipt would attest a chain one entry shorter.\n \"audit.submit_to_scitt\",\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\n// How deeply a request may nest, counting the envelope as level one. The\n// reference HTTP servers refuse deeper bodies before dispatch; the same limit\n// here means an in-process caller cannot send what the canonicaliser, the\n// copy of a recorded call and the two references handle differently.\nconst MAX_NESTING = 64;\n\nfunction withinNesting(value: unknown, limit: number): boolean {\n const stack: Array<[unknown, number]> = [[value, 1]];\n while (stack.length) {\n const [node, depth] = stack.pop()!;\n if (depth > limit) return false;\n if (Array.isArray(node)) {\n for (const v of node) stack.push([v, depth + 1]);\n } else if (node !== null && typeof node === \"object\") {\n for (const v of Object.values(node as Record<string, unknown>)) stack.push([v, depth + 1]);\n }\n }\n return true;\n}\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 /**\n * Called when a write to the store fails, with the workspace and the\n * version the write would have reached. When unset, the failure is written\n * to stderr. The call itself has already succeeded in memory; the next\n * write to the workspace carries what this one did not.\n */\n onStoreError?: (err: unknown, record: { id: string; version: number }) => 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 when it starts, and after each call that adds to a\n * workspace's log it calls `store.apply()` with what changed, or\n * `store.save()` with the whole workspace when the store has no `apply`.\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 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/** The signed calls on a log, keyed by `signedDigest`. */\ninterface SignedIndex {\n refused: Map<string, { seq: number; code: number }>;\n accepted: Set<string>;\n}\n\nfunction indexSigned(index: SignedIndex, entry: AuditEntry): void {\n const call = entryCall(entry);\n if (!isSigned(call)) return;\n let digest: string;\n try { digest = signedDigest(call as Envelope); }\n catch { return; /* an entry that cannot be canonicalised was altered; verify_chain reports it */ }\n if (entry.outcome != null) index.refused.set(digest, { seq: entry.seq, code: entry.outcome.code });\n else index.accepted.add(digest);\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\nfunction isThenable(value: unknown): value is PromiseLike<void> {\n return typeof (value as PromiseLike<void> | undefined)?.then === \"function\";\n}\n\n/** A deep copy where the value can be cloned, else the value itself. */\nfunction ownCopy<T>(value: T): T {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n\n// States in which a task has been deliberately stopped. review.request and\n// task.complete both refuse these, so neither can revive a terminated task nor\n// bypass a pause.\nconst REVIEW_REQUEST_STOPPED: string[] = [\"cancelled\", \"superseded\", \"paused\"];\n\n/** What the store holds of one workspace, as far as a Coordinator knows. */\ninterface Persisted {\n /** Audit entries the store holds. */\n seq: number;\n /** Write the whole workspace next: the store's copy is unknown. */\n replace: boolean;\n /** Idempotency keys written or removed since the last write. */\n keys: Set<string>;\n /** The time to stamp on the next write. */\n updatedAt?: string;\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 saveChains = new Map<WorkspaceId, Promise<void>>();\n /** Records which objects change, for stores that implement `apply`. */\n private readonly tracker: Tracker;\n /** What the store holds of each workspace, as far as this instance knows. */\n private persisted = new WeakMap<Workspace, Persisted>();\n /** Workspaces with entries not yet written in the call being handled. */\n private unflushed = new Set<Workspace>();\n /** Workspaces with a write queued behind an async write in flight. */\n private flushQueued = new Set<Workspace>();\n private clockMs?: number;\n private frozenNow?: string;\n private auditListeners: AuditListener[] = [];\n /**\n * The signed calls on each workspace's log, by what their senders signed:\n * recorded refusals with their seq and code, and accepted calls. Rebuilt\n * from the log when missing, so a snapshot never carries it.\n */\n private signedIndexes = new WeakMap<Workspace, SignedIndex>();\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.tracker = { enabled: typeof this.store.apply === \"function\", depth: 0 };\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 (!isThenable(loaded)) {\n this.applyRecords(loaded as WorkspaceRecord[]);\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 // One restore for every record: restore replaces the workspaces it\n // holds, so restoring record by record kept only the last.\n this.wsVersions.clear();\n this.restore(records.map(r => r.data));\n for (const r of records) this.wsVersions.set(r.id, r.version);\n // What was just loaded is what the store holds.\n for (const ws of this.workspaces.values()) this.markWritten(ws);\n }\n\n /** A map for a workspace collection, tracked for stores that implement `apply`. */\n private newMap<K, V>(): Map<K, V> {\n return new TrackedMap<K, V>(this.tracker);\n }\n\n /** Record that the store holds this workspace exactly as it is in memory. */\n private markWritten(ws: Workspace): void {\n for (const name of COLLECTIONS) {\n const map = ws[name];\n if (map instanceof TrackedMap) map.dirty.clear();\n }\n this.persisted.set(ws, { seq: ws.audit.length, replace: false, keys: new Set() });\n }\n\n /**\n * What the store holds of a workspace. A workspace this instance did not\n * create or load, such as one an application put in `workspaces` itself,\n * or one whose maps an application replaced, is tracked from here on and\n * written whole once.\n */\n private persistedOf(ws: Workspace): Persisted {\n let p = this.persisted.get(ws);\n let untracked = false;\n for (const name of COLLECTIONS) {\n const map = ws[name] as Map<string, unknown>;\n if (map instanceof TrackedMap && map.tracker === this.tracker) continue;\n untracked = true;\n const tracked = new TrackedMap<string, unknown>(this.tracker);\n for (const [key, value] of Map.prototype.entries.call(map) as IterableIterator<[string, unknown]>) {\n tracked.set(key, value);\n }\n (ws as unknown as Record<string, unknown>)[name] = tracked;\n }\n if (!p || untracked) {\n p = { seq: p?.seq ?? 0, replace: true, keys: new Set(), updatedAt: p?.updatedAt };\n this.persisted.set(ws, p);\n }\n return p;\n }\n\n /** Record that a task.create idempotency key was written or removed. */\n private markKey(ws: Workspace, key: string): void {\n if (this.tracker.enabled) this.persistedOf(ws).keys.add(key);\n }\n\n /** After an entry is appended: write now, or when the call being handled ends. */\n private persist(ws: Workspace): void {\n if (!this.tracker.enabled) {\n this.persistSnapshot(ws);\n return;\n }\n // One clock reading per entry, where earlier releases read it to stamp\n // the snapshot, so a deterministic clock gives the same times as before.\n this.persistedOf(ws).updatedAt = this.now();\n if (this.tracker.depth > 0) this.unflushed.add(ws);\n else this.flush(ws);\n }\n\n private flushUnflushed(): void {\n if (!this.unflushed.size) return;\n const list = [...this.unflushed];\n this.unflushed.clear();\n for (const ws of list) this.flush(ws);\n }\n\n /** Write what changed in one workspace since its last write. */\n private flush(ws: Workspace): void {\n const pending = this.saveChains.get(ws.id);\n if (pending) {\n // An async write is in flight. One more write follows it, built when it\n // runs, so it carries everything that changed until then.\n if (this.flushQueued.has(ws)) return;\n this.flushQueued.add(ws);\n this.chainWrite(ws.id, pending.then(() => {\n this.flushQueued.delete(ws);\n return this.writeChange(ws);\n }));\n return;\n }\n const result = this.writeChange(ws);\n if (result) this.chainWrite(ws.id, result);\n }\n\n private chainWrite(id: WorkspaceId, work: Promise<void>): void {\n // writeChange reports its own failures; this only keeps the chain alive.\n const guarded = work.catch(() => undefined);\n this.saveChains.set(id, guarded);\n void guarded.then(() => {\n if (this.saveChains.get(id) === guarded) this.saveChains.delete(id);\n });\n }\n\n private writeChange(ws: Workspace): Promise<void> | void {\n const p = this.persistedOf(ws);\n let change: StoreChange | undefined;\n try {\n change = this.takeChange(ws, p);\n } catch (err) {\n // What was taken is unknown, so the next write carries the whole workspace.\n p.replace = true;\n this.reportStoreError(err, { id: ws.id, version: ws.audit.length });\n return;\n }\n if (!change) return;\n const taken = change;\n const done = () => {\n p.seq = taken.version;\n if (taken.replace) p.replace = false;\n };\n const failed = (err: unknown) => {\n this.giveBack(ws, p, taken);\n this.reportStoreError(err, { id: taken.id, version: taken.version });\n };\n let result: PromiseLike<void> | void;\n try {\n result = this.store.apply!(taken);\n } catch (err) {\n failed(err);\n return;\n }\n if (isThenable(result)) return Promise.resolve(result).then(done, failed);\n done();\n }\n\n /** The change since the last write, taking the recorded keys with it. */\n private takeChange(ws: Workspace, p: Persisted): StoreChange | undefined {\n const replace = p.replace;\n const objects: Record<string, Record<string, unknown>> = {};\n for (const name of COLLECTIONS) {\n const map = ws[name] as unknown as TrackedMap<string, unknown>;\n if (replace) {\n const all: Record<string, unknown> = {};\n for (const [key, value] of Map.prototype.entries.call(map) as IterableIterator<[string, unknown]>) {\n all[key] = value;\n }\n objects[name] = all;\n } else if (map.dirty.size) {\n const changed: Record<string, unknown> = {};\n for (const key of map.dirty) changed[key] = map.peek(key) ?? null;\n objects[name] = changed;\n }\n map.dirty.clear();\n }\n if (replace) {\n objects[IDEMPOTENCY_KEYS] = { ...ws.idempotency_keys };\n } else if (p.keys.size) {\n const changed: Record<string, unknown> = {};\n for (const key of p.keys) changed[key] = ws.idempotency_keys[key] ?? null;\n objects[IDEMPOTENCY_KEYS] = changed;\n }\n p.keys.clear();\n const entries = ws.audit.slice(replace ? 0 : p.seq);\n if (!replace && !entries.length && !Object.keys(objects).length) return undefined;\n return {\n id: ws.id,\n base: replace ? 0 : p.seq,\n version: ws.audit.length,\n updated_at: p.updatedAt ?? ws.audit[ws.audit.length - 1]?.arrived ?? ws.created,\n meta: this.metaOf(ws),\n entries,\n objects,\n ...(replace ? { replace: true } : {}),\n };\n }\n\n /** A failed write's keys go back, so the next write carries them again. */\n private giveBack(ws: Workspace, p: Persisted, change: StoreChange): void {\n if (change.replace) {\n p.replace = true;\n return;\n }\n for (const [name, items] of Object.entries(change.objects)) {\n if (name === IDEMPOTENCY_KEYS) {\n for (const key of Object.keys(items)) p.keys.add(key);\n continue;\n }\n const map = (ws as unknown as Record<string, unknown>)[name];\n if (map instanceof TrackedMap) for (const key of Object.keys(items)) map.dirty.add(key);\n }\n }\n\n /** Persist the whole workspace, for a store that implements only `save`. */\n private persistSnapshot(ws: Workspace): void {\n const next = (this.wsVersions.get(ws.id) ?? 0) + 1;\n this.wsVersions.set(ws.id, next);\n let record: WorkspaceRecord;\n try {\n record = { id: ws.id, data: this.snapshotOf(ws), version: next, updated_at: this.now() };\n } catch {\n return;\n }\n\n const pending = this.saveChains.get(ws.id);\n if (pending) {\n this.trackSave(pending.then(() => this.store.save(record)), record);\n return;\n }\n let result: PromiseLike<void> | void;\n try {\n result = this.store.save(record);\n } catch (err) {\n this.reportStoreError(err, record);\n return;\n }\n if (isThenable(result)) {\n this.trackSave(Promise.resolve(result), record);\n }\n }\n\n private trackSave(save: Promise<void>, record: WorkspaceRecord): void {\n const guarded = save.catch(err => this.reportStoreError(err, record));\n this.saveChains.set(record.id, guarded);\n void guarded.then(() => {\n if (this.saveChains.get(record.id) === guarded) {\n this.saveChains.delete(record.id);\n }\n });\n }\n\n private reportStoreError(err: unknown, record: { id: string; version: number }): void {\n if (this.options.onStoreError) {\n try {\n this.options.onStoreError(err, { id: record.id, version: record.version });\n } catch {\n void 0;\n }\n return;\n }\n const message = err instanceof Error ? err.message : String(err);\n console.error(`chap coordinator: writing workspace ${record.id} to the store failed: ${message}`);\n }\n\n async drainSaves(): Promise<void> {\n while (this.saveChains.size) {\n await Promise.allSettled([...this.saveChains.values()]);\n }\n }\n\n // -- lifecycle -----------------------------------------------------\n\n private advanceClock(): string {\n if (this.clockMs !== undefined) {\n this.clockMs += 1000;\n return nowIso(this.clockMs);\n }\n return nowIso();\n }\n\n now(): string {\n return this.frozenNow ?? this.advanceClock();\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 // A `from` that is not a string names nobody. It is answered in fixed\n // words, so both references refuse it alike whatever was sent.\n if (typeof sender !== \"string\") {\n return { error: rpcError(E.NOT_AUTHORISED, \"Not a workspace member: from is not a participant URI\") };\n }\n if (!ws.members.has(sender)) {\n return { error: rpcError(E.NOT_AUTHORISED, `Not a workspace member: ${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()) out.push(this.snapshotOf(ws));\n return out;\n }\n\n /** The workspace's own fields: everything except its collections and log. */\n private metaOf(ws: Workspace): Record<string, unknown> {\n return {\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 chain_head: ws.chain_head,\n chain_enabled: ws.chain_enabled,\n };\n }\n\n /** One workspace as `snapshot()` holds it. Reads nothing as a change. */\n private snapshotOf(ws: Workspace): Record<string, unknown> {\n const { chain_head, chain_enabled, ...own } = this.metaOf(ws);\n return {\n ...own,\n members: Array.from(rawValues(ws.members)),\n tasks: Array.from(rawValues(ws.tasks)),\n overrides: Array.from(rawValues(ws.overrides)),\n whispers: Array.from(rawValues(ws.whispers)),\n deliberations: Array.from(rawValues(ws.deliberations)),\n handoffs: Array.from(rawValues(ws.handoffs)),\n snapshots: Array.from(rawValues(ws.snapshots)),\n route_decisions: Array.from(rawValues(ws.route_decisions)),\n idempotency_keys: { ...ws.idempotency_keys },\n audit: ws.audit,\n chain_head,\n chain_enabled,\n };\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 this.unflushed.clear();\n if (!Array.isArray(data)) return;\n for (const w of data as Array<Record<string, unknown>>) {\n // One workspace that cannot be rebuilt is skipped, with a warning, so\n // the others still load.\n let ws: Workspace;\n try {\n ws = this.rebuild(w);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn(`chap coordinator: workspace ${String(w?.id)} could not be restored: ${message}`);\n continue;\n }\n this.workspaces.set(ws.id, ws);\n // Restored from data the store may not hold: the next write replaces\n // the store's copy whole. Loading from the store marks it written.\n for (const name of COLLECTIONS) (ws[name] as TrackedMap<unknown, unknown>).dirty.clear();\n this.persisted.set(ws, { seq: 0, replace: true, keys: new Set() });\n }\n }\n\n /** One workspace from a snapshot entry, its maps tracked. */\n private rebuild(w: Record<string, unknown>): Workspace {\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: this.newMap(),\n tasks: this.newMap(),\n overrides: this.newMap(),\n whispers: this.newMap(),\n deliberations: this.newMap(),\n handoffs: this.newMap(),\n snapshots: this.newMap(),\n route_decisions: this.newMap(),\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 // Normalize the former flat store representation only on restore.\n // New snapshots are stored and emitted in the canonical wire shape.\n const content = structuredClone((x.content ?? {\n workspace: x.workspace, audit_seq: x.audit_seq,\n include: x.include, state: x.state,\n ...(x.label ? { label: x.label } : {}),\n }) as SnapshotArtefact[\"content\"]);\n if (!x.content) {\n // Legacy in-memory projections can contain undefined optional\n // fields; full bodies from older stores are not snapshot slices.\n const oldState = content.state;\n const state: Record<string, unknown> = {};\n for (const key of [\"mode_ceiling\", \"routing_policy_uri\", \"audit_seq\"]) {\n if (oldState[key] != null && oldState[key] !== \"\") state[key] = oldState[key];\n }\n for (const [key, fields] of [\n [\"members\", [\"uri\", \"type\", \"role\", \"scopes\"]],\n [\"open_tasks\", [\"id\", \"kind\", \"state\", \"assignee\"]],\n ] as const) {\n const items = oldState[key];\n if (Array.isArray(items) && items.length) {\n state[key] = items.map(item => Object.fromEntries(fields\n .filter(field => item[field] != null && item[field] !== \"\"\n && (!Array.isArray(item[field]) || item[field].length > 0))\n .map(field => [field, item[field]])));\n }\n }\n content.state = state;\n }\n ws.snapshots.set(x.id, {\n id: x.id, kind: \"snapshot\",\n produced_by: (x.produced_by ?? x.by) as string,\n produced_at: (x.produced_at ?? x.ts) as string,\n content_hash: (x.content_hash as string | undefined) ?? contentHash(content),\n content,\n });\n }\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 return ws;\n }\n\n // -- dispatch ------------------------------------------------------\n\n dispatch(envelope: Envelope): Envelope {\n this.frozenNow = this.advanceClock();\n this.tracker.depth++;\n try {\n const response = this._dispatch(envelope);\n if (response.error) this.recordRefusal(envelope, response.error);\n return response;\n } finally {\n // One write per call, with everything the call changed, made before\n // dispatch returns.\n if (--this.tracker.depth === 0) this.flushUnflushed();\n this.frozenNow = undefined;\n }\n }\n\n private _dispatch(envelope: Envelope): Envelope {\n // SPECIFICATION 10.1 fixes the order of the checks below, because which\n // refusal a call receives decides whether it is recorded. First the\n // request itself, none of whose refusals is recorded.\n if (!isValidEnvelope(envelope) || typeof envelope.method !== \"string\" || !envelope.method) {\n return reply(envelope, { error: rpcError(E.REQUEST, \"Invalid JSON-RPC 2.0 request\") });\n }\n if (!withinNesting(envelope, MAX_NESTING)) {\n return reply(envelope, { error: rpcError(E.REQUEST, `Envelope nests deeper than ${MAX_NESTING} levels`) });\n }\n const maxBytes = this.options.maxEnvelopeBytes ?? DEFAULT_MAX_ENVELOPE_BYTES;\n // Canonicalised once: the length is what the size limit measures, and a\n // request that cannot be canonicalised is refused below, once its method\n // is known to exist.\n let size = 0;\n let canonicalError: unknown;\n try { size = canonicalize(envelope).length; } catch (e) { canonicalError = e; }\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 const handler = this.handlers.get(method);\n if (!handler) {\n return reply(envelope, { error: rpcError(E.METHOD, `Unknown method: ${method}`) });\n }\n if (canonicalError !== undefined) {\n const msg = canonicalError instanceof Error ? canonicalError.message : String(canonicalError);\n return reply(envelope, { error: rpcError(E.PARAMS, msg) });\n }\n\n // SPECIFICATION 10.1: a signed request whose signed content matches a\n // recorded refusal is answered with that refusal and not evaluated again.\n // The log publishes a refused request, signature and all, so without this\n // anyone who can read the log could send it again once whatever refused\n // it had changed, and it would take effect in its signer's name.\n if (isSigned(envelope)) {\n const wsId = params.workspace;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n if (ws) {\n const prior = this.signedIndex(ws).refused.get(signedDigest(envelope));\n if (prior) {\n return reply(envelope, { error: rpcError(prior.code,\n `Refused at seq ${prior.seq}; a refused request is not evaluated again`,\n { refused_at_seq: prior.seq }) });\n }\n }\n }\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 // SPECIFICATION 15.4: refuse a method whose owning profile the workspace\n // does not advertise. The refusal is -32601, the same answer a coordinator\n // that never implemented the method would give, so a deployment cannot\n // tell from outside which of the two it is talking to. The detail rides in\n // `data` for an operator reading the log.\n {\n const gate = this.profileGate(method, params);\n if (gate) return reply(envelope, { error: gate });\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 // The routing methods and participant.leave sit under the same floor\n // (SPECIFICATION 6.3.1): without it a non-member could reassign a task\n // with task.route, or write a leave to the log under any name.\n if (method.startsWith(\"control.\") || method.startsWith(\"deliberate.\") || method.startsWith(\"handoff.\") || method.startsWith(\"whisper.\") || MEMBER_ONLY_METHODS.has(method)) {\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 let out: { result?: unknown; error?: { code: number; message: string; data?: unknown } };\n try {\n // The handler works on its own copy of what the caller sent, and the\n // caller gets a copy of the result, so no object is shared between the\n // workspace and the caller. A caller that reused or changed one later\n // would change the workspace outside any call, where no change is\n // recorded for the store.\n out = handler(ownCopy(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. A refusal is weighed in dispatch(), once this\n // returns, against the rule in SPECIFICATION 10.1.\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: ownCopy(out.result) });\n }\n\n // -- audit ---------------------------------------------------------\n\n recordAudit(ws: Workspace, envelope: Envelope): void {\n this.appendEntry(ws, { envelope: JSON.parse(JSON.stringify(envelope)) as Envelope });\n }\n\n /**\n * SPECIFICATION 10.1: record a refused call when it is a governed attempt.\n * The caller must be a member of an existing workspace, the call must be a\n * JSON-RPC call for a method that is not a read, and the refusal must be one\n * `refusalIsRecorded` names. The request is kept as it arrived, so a\n * signature on it still verifies. Every call that reaches a recorded refusal\n * has passed the canonical check, so it can be hashed into the chain.\n */\n private recordRefusal(envelope: Envelope, error: { code: number; data?: unknown }): void {\n if (!isValidEnvelope(envelope) || typeof envelope.method !== \"string\") return;\n const method = envelope.method;\n if (READ_ONLY_METHODS.has(method)) return;\n if (!refusalIsRecorded(method, error, PRIVILEGED_METHODS)) return;\n const raw = envelope.params;\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) return;\n const params = raw as Record<string, unknown>;\n const ws = typeof params.workspace === \"string\" ? this.workspaces.get(params.workspace) : undefined;\n if (!ws || typeof params.from !== \"string\" || !ws.members.has(params.from)) return;\n // A signed copy of a call already on the log is not a new attempt by its\n // signer. A copy of a refusal was answered with it, and a copy of a call\n // that took effect repeats a call its signer made once. Anyone who can\n // read the log can send either.\n if (isSigned(envelope)) {\n const index = this.signedIndex(ws);\n const digest = signedDigest(envelope);\n if (index.refused.has(digest) || index.accepted.has(digest)) return;\n }\n this.appendEntry(ws, {\n request: JSON.parse(JSON.stringify(envelope)) as Envelope,\n outcome: { status: \"refused\", code: error.code },\n });\n }\n\n /** The signed calls on this workspace's log, built from the log when missing. */\n private signedIndex(ws: Workspace): SignedIndex {\n let index = this.signedIndexes.get(ws);\n if (!index) {\n index = { refused: new Map(), accepted: new Set() };\n for (const entry of ws.audit) indexSigned(index, entry);\n this.signedIndexes.set(ws, index);\n }\n return index;\n }\n\n private appendEntry(ws: Workspace, record: Pick<AuditEntry, \"envelope\" | \"request\" | \"outcome\">): void {\n const entry: AuditEntry = { seq: ws.audit.length, arrived: this.now(), ...record };\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(entryRecord(entry), prev);\n }\n ws.audit.push(entry);\n const index = this.signedIndexes.get(ws);\n if (index) indexSigned(index, entry);\n for (const l of this.auditListeners) {\n try { l(ws, entry); } catch { /* listeners never break dispatch */ }\n }\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;\n const wsId = params.workspace;\n const rawTs = params.ts;\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. A `from` or `workspace` that is not a string names\n // nothing, so it counts as missing.\n if (typeof sender !== \"string\" || !sender || typeof wsId !== \"string\" || !wsId) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: missing from/workspace\");\n }\n // The key is chosen by the time the sender gives. A `ts` that is not a\n // string gives no time, so no key can be chosen for it.\n if (rawTs !== undefined && rawTs !== null && typeof rawTs !== \"string\") {\n return rpcError(E.SIG_VERIFY_FAILED, \"Cannot verify signature: ts must be a string\");\n }\n const ts = (rawTs as string | null | undefined) ?? this.now();\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 /**\n * The SPECIFICATION 15.4 check, per method rather than per namespace.\n *\n * Core is always present, so a core method is never gated. The reads in\n * ALWAYS_AVAILABLE are never gated either: a workspace must be able to ask\n * what it is and to check its own chain, and `audit.verify_chain` belongs to\n * `audit-scitt/1.0` while chaining also turns on through an option, so\n * gating it would let a workspace write a hash-linked chain it is refused\n * permission to verify.\n */\n private profileGate(method: string, params: Record<string, unknown>) {\n const owner = OWNING_PROFILE[method];\n if (owner === undefined || owner === \"core/1.0\" || ALWAYS_AVAILABLE.has(method)) return undefined;\n const wsId = params.workspace as string | undefined;\n const ws = typeof wsId === \"string\" ? this.workspaces.get(wsId) : undefined;\n if (!ws) return undefined;\n // Match on the profile name, so a workspace advertising a later minor\n // version of the owning profile still carries its methods.\n const name = owner.split(\"/\")[0];\n if (ws.profiles.some(p => p === name || p.startsWith(name + \"/\"))) return undefined;\n return rpcError(E.METHOD, `Unknown method: ${method}`,\n { profile: owner, advertised: [...ws.profiles] });\n }\n\n private checkStepUp(params: Record<string, unknown>): { code: number; message: string; data?: unknown } | null {\n // A `from` or `workspace` that is not a string names no member to hold to\n // step-up; the membership check answers such a call.\n const wsId = params.workspace;\n const sender = params.from;\n if (typeof wsId !== \"string\" || typeof sender !== \"string\" || !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\n // SPECIFICATION 15.4: the descriptor and the enforcement agree, and the\n // workspace boundary is where a disagreement surfaces.\n //\n // Advertising a security profile does not turn its enforcement on: that\n // would break every workspace advertising it today without signing, and\n // break it at the second call rather than at configuration time. The rule\n // runs the other way, where it costs nothing. Enforcement on adds the\n // profile, so the descriptor never understates what is enforced; the\n // profile advertised with enforcement off is a configuration error.\n for (const [profile, enforced, option] of [\n [\"security-signed/1.0\", !!this.options.requireSignatures, \"requireSignatures\"],\n [\"identity-oidc/1.0\", this.options.verifyOidcToken !== undefined, \"verifyOidcToken\"],\n ] as [string, boolean, string][]) {\n const name = profile.split(\"/\")[0];\n const advertised = profiles.some(x => x === name || x.startsWith(name + \"/\"));\n if (enforced && !advertised) profiles.push(profile);\n else if (advertised && !enforced) {\n return { error: rpcError(E.PARAMS,\n `${profile} is advertised but ${option} is not configured. ` +\n `A workspace that advertises it and does not enforce it ` +\n `describes a guarantee it does not give.`) };\n }\n }\n\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: this.newMap(),\n tasks: this.newMap(),\n overrides: this.newMap(),\n whispers: this.newMap(),\n deliberations: this.newMap(),\n handoffs: this.newMap(),\n snapshots: this.newMap(),\n route_decisions: this.newMap(),\n idempotency_keys: {},\n audit: [],\n chain_enabled: chainEnabled,\n chain_head: chainEnabled ? ZERO_HASH : undefined,\n };\n this.workspaces.set(id, ws);\n // New here, so the store holds nothing of it yet.\n this.persisted.set(ws, { seq: 0, replace: false, keys: new Set() });\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(rawValues(ws.members)).map(memberToDict),\n audit_count: ws.audit.length,\n task_count: ws.tasks.size,\n override_count: ws.overrides.size,\n // Omitted where the workspace has no chain, which is what the Python\n // reference now sends too: JSON.stringify drops an undefined value, so\n // the two answered the same call differently on the wire.\n ...(ws.chain_head ? { 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 const existing = ws.members.get(uri);\n let tokenVerified = false;\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 // A token binds only to the participant it belongs to. One naming\n // another participant is refused, and a join under an existing member's\n // name must carry a token for that member: the same subject, or, for a\n // member with no verified subject yet, a token naming the member.\n const boundUri = claims.chap_participant_uri;\n const sub = typeof claims.sub === \"string\" && claims.sub !== \"\" ? claims.sub : undefined;\n if (boundUri != null && boundUri !== uri) {\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token is bound to another participant\") };\n }\n if (existing) {\n if (existing.oidc_sub != null) {\n if (sub !== existing.oidc_sub) {\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token subject does not match the member\") };\n }\n } else if (boundUri !== uri) {\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token does not name this member\") };\n }\n }\n member.oidc_sub = sub;\n tokenVerified = true;\n const at = claims.auth_time;\n if (typeof at === \"number\") member.oidc_auth_time = at;\n member.oidc_acr = typeof claims.acr === \"string\" ? claims.acr : 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 && !Array.isArray(p.vc_presentation)) {\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 const holder = [subject.holder, subject.id].find(\n (h): h is string => typeof h === \"string\" && h !== \"\");\n // A join under an existing member's name binds a presentation only from\n // the member's own holder.\n if (existing && (existing.vc_holder == null || holder !== existing.vc_holder)) {\n return { error: rpcError(E.VC_HOLDER_BINDING_INVALID, \"Presentation holder does not match the member\") };\n }\n member.vc_holder = holder;\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 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 (tokenVerified) 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 (typeof assignee !== \"string\" || !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. A mode or review_required of the wrong type is\n // refused, so both references read the same task from the same call.\n if (p.mode !== undefined && p.mode !== null && typeof p.mode !== \"string\") {\n return { error: rpcError(E.PARAMS, \"mode must be a string\") };\n }\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 if (p.review_required !== undefined && p.review_required !== null && typeof p.review_required !== \"boolean\") {\n return { error: rpcError(E.PARAMS, \"review_required must be a boolean\") };\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 this.markKey(ws, p.idempotency_key);\n const keys = Object.keys(ws.idempotency_keys);\n if (keys.length > MAX_IDEMPOTENCY_KEYS) {\n delete ws.idempotency_keys[keys[0]];\n this.markKey(ws, keys[0]);\n }\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 // Pausing and resuming both belong to control/1.0. A Core-only workspace\n // that could pause through task.update would hold a task nothing it\n // advertises can lift. A review opens with review.request, or with\n // task.complete on a task that requires one: task.update into\n // review_requested would leave the task under review with no review for a\n // decision to act on.\n const legal: Record<string, string[]> = {\n created: [\"in_progress\", \"declined\"],\n in_progress: [\"in_progress\", \"completed\", \"declined\"],\n review_requested: [\"in_progress\"],\n paused: [\"cancelled\"],\n };\n if (!legal[task.state]?.includes(newState)) {\n return { error: rpcError(E.PARAMS, `Illegal transition ${task.state} -> ${newState}`) };\n }\n // task.complete opens a review rather than completing when one is required.\n // task.update reaches the same state by another route and carries no\n // output, so completing here would record a finished task with nothing\n // reviewed and no decision on the chain.\n if (newState === \"completed\" && task.review_required) {\n return { error: rpcError(E.PARAMS,\n \"This task requires review. Submit the output with task.complete, which opens the review; a reviewer decision completes it.\") };\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 if (!task.review) {\n // review_required means a person has to see this. The producer must\n // not satisfy its own review, and neither must another agent: an agent\n // approving an agent leaves a decide.approve on the chain that reads\n // as human oversight and is not. So the implicit review is addressed\n // to the human members other than the completer and the assignee, and\n // where there are none the completion is refused rather than opening a\n // review no person can decide. An explicit review.request keeps its\n // own `to`, so a deliberate agent-reviews-agent flow is still\n // available.\n const producer = p.from as string;\n const eligible = [...rawEntries(ws.members)]\n .filter(([uri, member]) => uri !== producer && uri !== task.assignee && member.type === \"human\")\n .map(([uri]) => uri);\n if (eligible.length === 0) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"Task requires review but has no eligible human reviewer (needs a human 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.pending_artefact = p.output;\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 {\n method?: string; from?: string; task_id?: string; outcome?: unknown;\n } | undefined) ?? {};\n if (filter.outcome != null && filter.outcome !== \"accepted\" && filter.outcome !== \"refused\") {\n return { error: rpcError(E.PARAMS, \"filter.outcome must be 'accepted' or 'refused'\") };\n }\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 // Filters read the call an entry records, accepted or refused, and\n // `outcome` narrows to one kind.\n const refused = entry.outcome != null;\n if (filter.outcome === \"accepted\" && refused) continue;\n if (filter.outcome === \"refused\" && !refused) continue;\n const call = entryCall(entry) ?? ({} as Envelope);\n const ep = (call.params ?? {}) as Record<string, unknown>;\n if (filter.method && call.method !== filter.method) continue;\n if (filter.from && ep.from !== filter.from) continue;\n if (filter.task_id) {\n let taskId = ep.task_id;\n if (call.method === \"whisper.answer\") {\n const prompt = ws.whispers.get(ep.whisper_id as string);\n taskId = prompt ? (prompt as { task_id?: string }).task_id : undefined;\n }\n if (taskId !== filter.task_id) continue;\n }\n const item: Record<string, unknown> = { seq: entry.seq, arrived: entry.arrived };\n if (refused) {\n item.request = entry.request;\n item.outcome = entry.outcome;\n } else {\n item.envelope = entry.envelope;\n }\n if (entry.prev_hash) item.prev_hash = entry.prev_hash;\n out.push(item);\n }\n // The next entry to read: the end of the range, or the end of the log\n // where the range runs past it, so a reader paging forward meets the\n // entries written after this read.\n return { result: { entries: out, next_seq: Math.min(toSeq, ws.audit.length) } };\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 // task.complete refuses a task that has been stopped, so that a completion\n // \"can neither revive a terminated task nor bypass a pause\". review.request\n // creates the same kind of state and had no such check, so it revived\n // cancelled and superseded tasks and pulled paused ones back into play. The\n // same three states are refused here.\n //\n // `completed` is deliberately still allowed. Requesting review on a\n // completed task is how every framework bridge submits a draft, and\n // 0.2.12's `review_required` is the route away from that, not this.\n if (REVIEW_REQUEST_STOPPED.includes(task.state)) {\n return { error: rpcError(E.NOT_REVIEWABLE, `Cannot request review for task in state: ${task.state}`) };\n }\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 declaredRule = p.rule as string | undefined;\n const rule = declaredRule || \"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 // Only a rule the caller actually supplied can be a change. Comparing\n // the resolved default instead refused the documented\n // widen-the-reviewer-set request whenever `rule` was omitted.\n if (declaredRule !== undefined && declaredRule !== 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 origId = p.original_task_id;\n const orig = typeof origId === \"string\" ? ws.tasks.get(origId) : undefined;\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 if (p.new_task === null || typeof p.new_task !== \"object\" || Array.isArray(p.new_task)) {\n return { error: rpcError(E.PARAMS, \"new_task must be an object\") };\n }\n const nt = p.new_task as Record<string, unknown>;\n const assignee = nt.assignee;\n if (typeof assignee !== \"string\" || !ws.members.has(assignee)) {\n return { error: rpcError(E.PARAMS, \"Escalation assignee not in workspace\") };\n }\n const named = nt.mode;\n if (named !== undefined && named !== null && typeof named !== \"string\") {\n return { error: rpcError(E.PARAMS, \"new_task.mode must be a string\") };\n }\n // The successor is a created task, so it meets the checks task.create and\n // control.supersede apply: its assignee must not be paused, and its mode,\n // the one new_task names or else the original's, must be within the\n // ceiling in force now. Naming a lower mode is how work is escalated\n // after the ceiling has been lowered.\n if (ws.members.get(assignee)!.paused) {\n return { error: rpcError(E.CONTROL_WORKSPACE_PAUSED, `Assignee ${assignee} is paused`) };\n }\n const mode = ((named as Mode | null | undefined) || orig.mode) as Mode;\n if (!modeLE(mode, ws.mode_ceiling)) {\n return { error: rpcError(E.MODE_CEILING_EXCEEDED,\n `Requested mode ${mode} exceeds ceiling ${ws.mode_ceiling}`) };\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,\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 // Escalating hands the work on and keeps its review requirement. The\n // successor requires review when the original did, and a trial task\n // forces review under modes/1.0 as it does at task.create.\n if (orig.review_required || (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && newTask.mode === \"trial\")) {\n newTask.review_required = true;\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 * apply the same review-depth and escalation rules. Routing differs: this\n * routing policy takes the first candidate as given, so a first candidate\n * who is not a member is refused with -32510 and one who is paused with\n * -32063, where the built-in default passes over both. This factory exists\n * so that the legacy 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.3. 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 /** Optional id of the decision this call fulfils; recorded as a ``fulfils`` link on the result artefact. Asserted by the caller and not verified by the coordinator. */\n fulfils?: 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 output: Record<string, unknown> = { result: options.result, citations };\n if (options.fulfils) output.fulfils = options.fulfils;\n const completeParams: Record<string, unknown> = {\n workspace,\n from: options.caller,\n task_id: taskId,\n output,\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 /** Optional id of the decision this exchange fulfils; recorded as a ``fulfils`` link on the result artefact. Asserted by the caller and not verified by the coordinator. */\n fulfils?: 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 output: Record<string, unknown> = { received: options.received, citations: [citation] };\n if (options.fulfils) output.fulfils = options.fulfils;\n const completeParams: Record<string, unknown> = {\n workspace, from: options.bridgeUri, task_id: taskId,\n output,\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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBA,yBAA2B;AAEpB,IAAM,YAAY,YAAY,IAAI,OAAO,EAAE;AAElD,IAAM,oBACJ;AAEF,IAAM,qBACJ;AAGF,IAAM,uBACJ;AAGF,SAAS,sBAAsB,GAAiB;AAC9C,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AACjC,UAAM,IAAI,EAAE,WAAW,CAAC;AACxB,QAAI,KAAK,SAAU,KAAK,OAAQ;AAC9B,YAAM,OAAO,IAA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