@brightbeamai/chap-coordinator 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +54 -8
  2. package/dist/{api-59aU01Bs.d.cts → api-CjZQnj63.d.cts} +128 -14
  3. package/dist/{api-CxciGFHA.d.ts → api-DG0VFGVr.d.ts} +128 -14
  4. package/dist/api.cjs +3 -1
  5. package/dist/api.cjs.map +1 -1
  6. package/dist/api.d.cts +1 -1
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +3 -1
  9. package/dist/api.js.map +1 -1
  10. package/dist/index.cjs +1578 -276
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +20 -6
  13. package/dist/index.d.ts +20 -6
  14. package/dist/index.js +1577 -276
  15. package/dist/index.js.map +1 -1
  16. package/dist/jsonrpc.cjs +1 -0
  17. package/dist/jsonrpc.cjs.map +1 -1
  18. package/dist/jsonrpc.d.cts +1 -0
  19. package/dist/jsonrpc.d.ts +1 -0
  20. package/dist/jsonrpc.js +1 -0
  21. package/dist/jsonrpc.js.map +1 -1
  22. package/dist/methods.cjs.map +1 -1
  23. package/dist/methods.d.cts +36 -3
  24. package/dist/methods.d.ts +36 -3
  25. package/dist/patch.cjs +195 -61
  26. package/dist/patch.cjs.map +1 -1
  27. package/dist/patch.d.cts +16 -2
  28. package/dist/patch.d.ts +16 -2
  29. package/dist/patch.js +194 -61
  30. package/dist/patch.js.map +1 -1
  31. package/dist/storage/sqlite.cjs +81 -19
  32. package/dist/storage/sqlite.cjs.map +1 -1
  33. package/dist/storage/sqlite.d.cts +19 -9
  34. package/dist/storage/sqlite.d.ts +19 -9
  35. package/dist/storage/sqlite.js +81 -19
  36. package/dist/storage/sqlite.js.map +1 -1
  37. package/dist/storage/store.cjs +20 -15
  38. package/dist/storage/store.cjs.map +1 -1
  39. package/dist/storage/store.d.cts +24 -6
  40. package/dist/storage/store.d.ts +24 -6
  41. package/dist/storage/store.js +20 -15
  42. package/dist/storage/store.js.map +1 -1
  43. package/dist/types.cjs.map +1 -1
  44. package/dist/types.d.cts +56 -1
  45. package/dist/types.d.ts +56 -1
  46. package/dist/types.js.map +1 -1
  47. package/package.json +2 -2
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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/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 (err) {\n // Nothing was written. The next save builds the whole workspace again.\n this.reportStoreError(err, { id: ws.id, version: next });\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":";AAkBA,SAAS,kBAAkB;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,IAAI;AACtD,UAAI,OAAO,SAAU,OAAO,MAAQ,OAAM,IAAI,MAAM,oBAAoB;AACxE;AAAA,IACF,WAAW,KAAK,SAAU,KAAK,OAAQ;AACrC,YAAM,IAAI,MAAM,oBAAoB;AAAA,IACtC;AAAA,EACF;AACF;AAEA,SAAS,gBAAgB,GAAmB;AAC1C,wBAAsB,CAAC;A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,UAAU,WAAW,CAAC,QAAQ,EAAE;AAC5F,MAAI,QAAQ,QAAS,QAAO,UAAU,QAAQ;AAC9C,QAAM,iBAA0C;AAAA,IAC9C;AAAA,IAAW,MAAM,QAAQ;AAAA,IAAW,SAAS;AAAA,IAC7C;AAAA,EACF;AACA,MAAI,QAAQ,eAAe,OAAW,gBAAe,aAAa,QAAQ;AAE1E,QAAM,eAAe,MAAM,SAAS;AAAA,IAClC,SAAS;AAAA,IAAO,IAAI;AAAA,IACpB,QAAQ;AAAA,IAAiB,QAAQ;AAAA,EACnC,CAAC;AACD,MAAI,aAAa,MAAO,OAAM,IAAI,MAAM,yBAAyB,KAAK,UAAU,aAAa,KAAK,CAAC,EAAE;AAErG,SAAO,EAAE,SAAS,QAAQ,WAAW,UAAU,eAAe,aAAa;AAC7E;","names":["createHash","call","call","wsId","CRIT"]}
1
+ {"version":3,"sources":["../src/canonical.ts","../src/catalogue.ts","../src/crypto.ts","../src/ids.ts","../src/jsonrpc.ts","../src/params.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/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 <= 2^53 - 1); 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.acknowledge\": \"review/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.invite\": \"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/**\n * The profiles a workspace may advertise, each at its current version. A\n * profile id names one of them at its major version (SPECIFICATION 6.5).\n */\nexport const PROFILE_VERSIONS: Readonly<Record<string, string>> = Object.freeze({\n \"audit-scitt\": \"1.0\",\n \"control\": \"1.0\",\n \"core\": \"1.0\",\n \"deliberation\": \"1.0\",\n \"handoff\": \"1.0\",\n \"identity-oidc\": \"1.0\",\n \"identity-vc\": \"1.0\",\n \"modes\": \"1.0\",\n \"review\": \"1.0\",\n \"routing\": \"1.0\",\n \"security-signed\": \"1.0\",\n \"whisper\": \"1.0\",\n});\n","/**\n * @brightbeamai/chap-coordinator/crypto\n *\n * Ed25519 signing/verification for the security-signed/1.0 profile, and\n * verification of WebAuthn assertions, the signatures a browser's\n * authenticator makes with a P-256 key.\n *\n * Uses Node's built-in crypto (no external dependencies). Keys are\n * represented as RFC 7517 JWKs.\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\";\nimport { canonicalize } from \"./canonical.js\";\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/**\n * The bytes a standard base64 string encodes, or undefined where it is not\n * the one canonical encoding of them: standard alphabet, padded, and nothing\n * else, so a signature has one spelling in every language.\n */\nexport function strictBase64(s: string): Buffer | undefined {\n const bytes = Buffer.from(s, \"base64\");\n return bytes.toString(\"base64\") === s ? bytes : undefined;\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 sig = strictBase64(parts[parts.length - 1]);\n if (sig === undefined) return false;\n try {\n return nodeVerify(null, canonical, publicKey, sig);\n } catch {\n return false;\n }\n}\n\n/** Whether a JWK is an Ed25519 public key: OKP on Ed25519 with a 32-byte x. */\nexport function isEd25519Key(jwk: unknown): boolean {\n if (jwk === null || typeof jwk !== \"object\" || Array.isArray(jwk)) return false;\n const key = jwk as Record<string, unknown>;\n return key.kty === \"OKP\" && key.crv === \"Ed25519\" && typeof key.x === \"string\" && COORDINATE.test(key.x);\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/**\n * The RFC 7638 thumbprint of a public JWK: SHA-256 over the JSON of its\n * required members in lexicographic order, base64url without padding.\n * The members are {crv, kty, x} for an OKP key and {crv, kty, x, y} for an\n * EC key, and for any other key, or one whose members are not strings,\n * there is none.\n */\nexport function jwkThumbprint(jwk: unknown): string | undefined {\n if (jwk === null || typeof jwk !== \"object\" || Array.isArray(jwk)) return undefined;\n const key = jwk as Record<string, unknown>;\n const names = key.kty === \"OKP\" ? [\"crv\", \"kty\", \"x\"] : key.kty === \"EC\" ? [\"crv\", \"kty\", \"x\", \"y\"] : undefined;\n if (!names || names.some((n) => typeof key[n] !== \"string\")) return undefined;\n const members = Object.fromEntries(names.map((n) => [n, key[n]]));\n return b64urlNoPad(createHash(\"sha256\").update(canonicalize(members)).digest());\n}\n\n/** A WebAuthn assertion, as the last part of a `webauthn:` tag carries it. */\nexport interface WebAuthnAssertion {\n authenticatorData: Buffer;\n clientDataJSON: Buffer;\n signature: Buffer;\n}\n\n// Unpadded base64url. A length of 1 more than a multiple of 4 encodes no\n// whole byte, and is refused here, since Node and Python decode it apart.\nconst B64URL = /^[A-Za-z0-9_-]+$/;\n\n/**\n * The assertion in `<authenticatorData>.<clientDataJSON>.<signature>`, each\n * part unpadded base64url, or undefined where the part is not that.\n */\nexport function parseWebAuthnAssertion(part: string): WebAuthnAssertion | undefined {\n const pieces = part.split(\".\");\n if (pieces.length !== 3 || pieces.some((p) => !B64URL.test(p) || p.length % 4 === 1)) return undefined;\n const [authenticatorData, clientDataJSON, signature] = pieces.map((p) => Buffer.from(p, \"base64url\"));\n return { authenticatorData, clientDataJSON, signature };\n}\n\n// A P-256 coordinate: 32 bytes, unpadded base64url.\nconst COORDINATE = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * Whether a JWK is a WebAuthn key: a P-256 key for ES256 with a `webauthn`\n * member naming its `rp_id`, and, where it limits them, its `origins`.\n */\nexport function isWebAuthnKey(jwk: unknown): boolean {\n if (jwk === null || typeof jwk !== \"object\" || Array.isArray(jwk)) return false;\n const key = jwk as Record<string, unknown>;\n const w = key.webauthn as Record<string, unknown> | null | undefined;\n return key.kty === \"EC\" && key.crv === \"P-256\"\n && typeof key.x === \"string\" && COORDINATE.test(key.x) && typeof key.y === \"string\" && COORDINATE.test(key.y)\n && (key.alg === undefined || key.alg === \"ES256\")\n && w !== null && typeof w === \"object\" && !Array.isArray(w)\n && typeof w.rp_id === \"string\" && w.rp_id !== \"\"\n && (w.origins === undefined || (Array.isArray(w.origins) && w.origins.every((o) => typeof o === \"string\")));\n}\n\nconst UTF8 = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\n/** How deeply a client data object may nest, as an envelope may (64 levels). */\nconst MAX_CLIENT_DATA_NESTING = 64;\n\n/**\n * How deeply JSON text nests, read from its brackets outside strings, so a\n * text too deep for one language's parser is refused the same way by both.\n */\nfunction jsonDepth(text: string): number {\n let depth = 0;\n let deepest = 0;\n let inString = false;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (ch === \"\\\\\") i++;\n else if (ch === '\"') inString = false;\n } else if (ch === '\"') {\n inString = true;\n } else if (ch === \"{\" || ch === \"[\") {\n deepest = Math.max(deepest, ++depth);\n } else if (ch === \"}\" || ch === \"]\") {\n depth--;\n }\n }\n return deepest;\n}\n\n// The authenticator data's flags: user present, user verified, backup\n// eligible, backed up, attested credential data and extension data.\nconst UP = 0x01, UV = 0x04, BE = 0x08, BS = 0x10, AT = 0x40, ED = 0x80;\n\n/**\n * Why a WebAuthn assertion does not sign a request, or null when it does.\n * `canonical` is the JCS form of the request without its `sig`, and `jwk`\n * a key isWebAuthnKey accepts. The checks are the relying party's in the\n * WebAuthn assertion procedure: the key names the origins it signs for; the\n * client data says it is an assertion, over this request, from one of those\n * origins, made in no other origin's frame; the authenticator data is for\n * the key's relying party, with the user present and verified, its backup\n * flags consistent, and nothing after its counter but the extensions its\n * flags announce; and the ES256 signature covers the authenticator data and\n * the hash of the client data.\n */\nexport function webAuthnFailure(canonical: Buffer, assertion: WebAuthnAssertion,\n jwk: Record<string, unknown>): string | null {\n const w = jwk.webauthn as { rp_id: string; origins?: string[] };\n if (!Array.isArray(w.origins) || w.origins.length === 0) return \"WebAuthn key lists no origin\";\n let text: string | undefined;\n try { text = UTF8.decode(assertion.clientDataJSON); } catch { text = undefined; }\n if (text !== undefined && jsonDepth(text) > MAX_CLIENT_DATA_NESTING) {\n return `WebAuthn clientDataJSON nests deeper than ${MAX_CLIENT_DATA_NESTING} levels`;\n }\n let client: unknown;\n try { client = text === undefined ? undefined : JSON.parse(text); } catch { client = undefined; }\n if (client === null || typeof client !== \"object\" || Array.isArray(client)) {\n return \"WebAuthn clientDataJSON is not a JSON object\";\n }\n const data = client as Record<string, unknown>;\n if (data.type !== \"webauthn.get\") return \"WebAuthn clientDataJSON type is not webauthn.get\";\n if (data.challenge !== b64urlNoPad(createHash(\"sha256\").update(canonical).digest())) {\n return \"WebAuthn challenge is not the digest of this request\";\n }\n if (!w.origins.includes(data.origin as string)) return \"WebAuthn origin is not one the key allows\";\n if (data.crossOrigin === true || data.topOrigin !== undefined) {\n return \"WebAuthn assertion was made in a cross-origin frame\";\n }\n const auth = assertion.authenticatorData;\n if (auth.length < 37) return \"WebAuthn authenticatorData is too short\";\n if (!auth.subarray(0, 32).equals(createHash(\"sha256\").update(w.rp_id, \"utf-8\").digest())) {\n return \"WebAuthn rpIdHash does not match the key's rp_id\";\n }\n const flags = auth[32];\n if ((flags & (UP | UV)) !== (UP | UV)) return \"WebAuthn assertion lacks user presence or verification\";\n if ((flags & BS) && !(flags & BE)) return \"WebAuthn assertion is backed up but not backup eligible\";\n // An assertion carries no attested credential data, and extension data\n // only where its flag says so.\n if (flags & AT) return \"WebAuthn assertion carries attested credential data\";\n if ((flags & ED) ? auth.length === 37 : auth.length !== 37) {\n return \"WebAuthn authenticatorData does not end where its flags say\";\n }\n try {\n const key = createPublicKey({ key: { kty: \"EC\", crv: \"P-256\", x: jwk.x as string, y: jwk.y as string },\n format: \"jwk\" });\n const signed = Buffer.concat([auth, createHash(\"sha256\").update(assertion.clientDataJSON).digest()]);\n return nodeVerify(\"sha256\", signed, { key, dsaEncoding: \"der\" }, assertion.signature)\n ? null : \"Signature failed verification\";\n } catch {\n return \"Signature failed verification\";\n }\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 SIG_ALREADY_ACCEPTED: -32075,\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 * Type checks for the params a method reads.\n *\n * A param of the wrong type would reach code written for the right one, and\n * the two references would do different things with it: JavaScript reads\n * `[]` and `{}` as true where Python reads them as false, a Python dict\n * cannot be looked up with a list, and a value written into a message reads\n * one way in each language. Checking the type first gives both the same\n * refusal. packages/coordinator-py/chap_coordinator/params.py is the mirror.\n */\nimport { E, rpcError } from \"./jsonrpc.js\";\n\n/** What a param must be when it is present and not null. */\nexport type ParamKind = \"string\" | \"strings\" | \"boolean\" | \"object\" | \"list\" | \"integer\";\n\nconst NAMES: Record<ParamKind, string> = {\n string: \"a string\",\n strings: \"a list of strings\",\n boolean: \"a boolean\",\n object: \"an object\",\n list: \"a list\",\n integer: \"an integer\",\n};\n\nfunction isKind(value: unknown, kind: ParamKind): boolean {\n switch (kind) {\n case \"string\": return typeof value === \"string\";\n case \"strings\": return Array.isArray(value) && value.every((v) => typeof v === \"string\");\n case \"boolean\": return typeof value === \"boolean\";\n case \"object\": return typeof value === \"object\" && value !== null && !Array.isArray(value);\n case \"list\": return Array.isArray(value);\n case \"integer\": return typeof value === \"number\" && Number.isInteger(value);\n }\n}\n\n/**\n * The refusal for the first param in `checks` that holds a value of another\n * kind, or null when every one is absent, null or of its kind.\n * `checks` names params of `params`, or of an object inside it as\n * `outer.inner`.\n */\nexport function paramsError(\n params: Record<string, unknown>,\n checks: ReadonlyArray<readonly [string, ParamKind]>,\n): { error: ReturnType<typeof rpcError> } | null {\n for (const [name, kind] of checks) {\n let value: unknown = params;\n for (const part of name.split(\".\")) {\n value = typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)[part] : undefined;\n }\n if (value !== undefined && value !== null && !isKind(value, kind)) {\n return { error: rpcError(E.PARAMS, `${name} must be ${NAMES[kind]}`) };\n }\n }\n return null;\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, a call whose signature or key did not check out,\n * and a signed copy of a call the log already holds as accepted.\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 E.SIG_ALREADY_ACCEPTED,\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\n/**\n * Puts `value`, which the document owns from here on, at `path`. A copied\n * value counts towards what the patch carries. A moved value is counted\n * already: `movedFrom` is the number of segments of the place it left, and\n * only its key, a value it replaces and how deep it now reaches change the\n * count. A move to a deeper place, or onto the whole document, costs a pass\n * over the value, so it counts towards what the patch carries as well.\n */\nfunction addAt(doc: any, path: string, value: unknown, size: Size | undefined,\n copied = false, movedFrom?: number): any {\n const parts = splitPath(path);\n if (parts.length === 0) {\n if (size) {\n size.reset(value);\n if (copied || movedFrom !== undefined) size.carry(size);\n }\n return value; // replace whole document\n }\n const [parent, key] = navigate(doc, parts);\n let newKey: string | undefined;\n if (Array.isArray(parent)) {\n if (key === \"-\") {\n parent.push(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, value);\n }\n } else if (parent !== null && typeof parent === \"object\") {\n if (Object.prototype.hasOwnProperty.call(parent, key)) size?.take(parent[key as string]);\n else newKey = key as string;\n parent[key as string] = value;\n } else {\n throw new PatchError(`Cannot add into ${jsonType(parent)}`);\n }\n if (size) {\n if (movedFrom === undefined) {\n const inserted = size.insert(value, parts.length, newKey);\n if (copied) size.carry(inserted);\n } else {\n if (newKey !== undefined) size.bytes += utf8Length(newKey);\n if (parts.length > movedFrom) {\n // A move to a deeper place costs a pass over the value, for its depth.\n const moved = sizeOf(value);\n size.depth = Math.max(size.depth, parts.length + moved.depth);\n size.carry(moved);\n }\n }\n }\n return doc;\n}\n\n/** Removes the value at `path`. A moved value goes back in elsewhere, so only its key leaves the count. */\nfunction removeAt(doc: any, path: string, size: Size | undefined, moved = false): any {\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 if (size && !moved) size.take(parent[idx]);\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 if (size) {\n if (moved) size.bytes -= utf8Length(key as string);\n else size.take(parent[key as string], key as string);\n }\n delete parent[key as string];\n } else {\n throw new PatchError(`Cannot remove from ${jsonType(parent)}`);\n }\n return doc;\n}\n\nfunction applyOne(doc: any, op: JsonPatchOp, size?: Size): 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 // A copy, so an operation on the inserted value leaves the patch as it\n // was sent.\n return addAt(doc, path, clone(op.value), size);\n }\n\n if (kind === \"replace\") {\n if (!(\"value\" in op)) throw new PatchError(\"'replace' requires 'value'\");\n const parts = splitPath(path);\n const value = clone(op.value);\n if (parts.length === 0) {\n size?.reset(value);\n return value;\n }\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 size?.take(parent[idx]);\n parent[idx] = 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 size?.take(parent[key as string]);\n parent[key as string] = value;\n } else {\n throw new PatchError(`Cannot replace in ${jsonType(parent)}`);\n }\n size?.insert(value, parts.length);\n return doc;\n }\n\n if (kind === \"remove\") {\n return removeAt(doc, path, size);\n }\n\n if (kind === \"copy\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'copy' requires 'from'\");\n return addAt(doc, path, clone(getAt(doc, src)), size, true);\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 // The remove detaches the value, so it moves as it is, uncopied.\n const value = getAt(doc, src);\n doc = removeAt(doc, src, size, true);\n return addAt(doc, path, value, size, false, splitPath(src).length);\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\n/**\n * How deeply a patched document may nest, counting the document as level one,\n * as the coordinator counts a request's nesting. Each operation's value comes\n * within the request's limit, and a patch that puts one value inside another\n * would otherwise nest the document without limit.\n */\nconst MAX_DOCUMENT_DEPTH = 64;\n\n/**\n * How much a patch's copies, and its moves to a deeper place or onto the whole\n * document, may carry between them, as a multiple of the document's limits.\n * Each costs a pass over the value it carries, so a patch that copied the same\n * large value back and forth could otherwise keep a coordinator busy for\n * seconds.\n */\nconst MAX_CARRIED_TIMES = 3;\n\n/**\n * The default cap on the string and key text a patched document may hold, in\n * UTF-8 bytes: the default `max_envelope_bytes`. An artefact that arrives in a\n * request holds no more text than the request's size. The node cap alone does\n * not bound size: a `copy` of the root doubles the document, long strings\n * included, so fifteen of them grow 64 KiB to about 2 GiB within 100,000\n * nodes.\n */\nexport const DEFAULT_MAX_PATCHED_BYTES = 1_048_576;\n\n/** Limits a caller can set on {@link applyJsonPatch}. */\nexport interface PatchLimits {\n /** The most UTF-8 bytes of string and key text the result may hold. */\n maxStringBytes?: number;\n}\n\n/**\n * UTF-8 length of a string: Buffer's count where Node provides it, and the\n * same count by hand elsewhere, so the module runs anywhere. A lone surrogate\n * counts three bytes either way, as does Python's\n * `len(s.encode(\"utf-8\", \"surrogatepass\"))`, which keeps the two references\n * refusing the same patches.\n */\nfunction utf8Length(s: string): number {\n const buffer = (globalThis as { Buffer?: unknown }).Buffer;\n if (typeof buffer === \"function\") {\n return (buffer as unknown as { byteLength(s: string, encoding: \"utf8\"): number }).byteLength(s, \"utf8\");\n }\n let n = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) n += 1;\n else if (c < 0x800) n += 2;\n else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const d = s.charCodeAt(i + 1);\n if (d >= 0xdc00 && d <= 0xdfff) { n += 4; i++; } else n += 3;\n } else n += 3;\n }\n return n;\n}\n\ninterface Measured { nodes: number; bytes: number; depth: number }\n\n/**\n * A value's count of values, the UTF-8 bytes of its strings and keys, and its\n * depth, counting the value itself as level one, in one pass that does not\n * recurse.\n */\nfunction sizeOf(value: unknown): Measured {\n if (value === null || typeof value !== \"object\") {\n return { nodes: 1, bytes: typeof value === \"string\" ? utf8Length(value) : 0, depth: 1 };\n }\n let nodes = 0;\n let bytes = 0;\n let depth = 0;\n const values: object[] = [value];\n const levels: number[] = [1];\n // A scalar child is counted where it is found, which saves a trip through\n // the stack.\n const visit = (x: unknown, level: number): void => {\n if (x !== null && typeof x === \"object\") {\n values.push(x);\n levels.push(level);\n return;\n }\n nodes += 1;\n if (level > depth) depth = level;\n if (typeof x === \"string\") bytes += utf8Length(x);\n };\n while (values.length > 0) {\n const v = values.pop()!;\n const level = levels.pop()!;\n nodes += 1;\n if (level > depth) depth = level;\n if (Array.isArray(v)) {\n for (const x of v) visit(x, level + 1);\n } else {\n const o = v as Record<string, unknown>;\n for (const k of Object.keys(o)) {\n bytes += utf8Length(k);\n visit(o[k], level + 1);\n }\n }\n }\n return { nodes, bytes, depth };\n}\n\n/**\n * What the working document holds, kept in step by each operation. The values\n * and the bytes are exact: each operation counts what it puts in and what it\n * takes out, so a patch costs what it changes, whatever the document's size.\n * The depth is a bound, raised by what each operation puts in; it passes the\n * limit when the document does, or when the document started deeper.\n */\nclass Size implements Measured {\n nodes = 0;\n bytes = 0;\n depth = 0;\n /** What copies, and moves to a deeper place or onto the whole document, have carried. */\n carriedNodes = 0;\n carriedBytes = 0;\n\n constructor(doc: unknown) {\n this.reset(doc);\n }\n\n reset(doc: unknown): void {\n const s = sizeOf(doc);\n this.nodes = s.nodes;\n this.bytes = s.bytes;\n this.depth = s.depth;\n }\n\n /** `value` goes in `segments` levels below the top, under a new `key`. */\n insert(value: unknown, segments: number, key?: string): Measured {\n const s = sizeOf(value);\n this.nodes += s.nodes;\n this.bytes += s.bytes + (key === undefined ? 0 : utf8Length(key));\n this.depth = Math.max(this.depth, segments + s.depth);\n return s;\n }\n\n carry(s: Measured): void {\n this.carriedNodes += s.nodes;\n this.carriedBytes += s.bytes;\n }\n\n /** `value` comes out, with its `key`. */\n take(value: unknown, key?: string): void {\n const s = sizeOf(value);\n this.nodes -= s.nodes;\n this.bytes -= s.bytes + (key === undefined ? 0 : utf8Length(key));\n }\n}\n\nexport function applyJsonPatch(doc: unknown, ops: JsonPatchOp[], limits: PatchLimits = {}): unknown {\n const maxBytes = limits.maxStringBytes ?? DEFAULT_MAX_PATCHED_BYTES;\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 const size = new Size(out);\n for (const op of ops) {\n out = applyOne(out, op, size);\n if (size.depth > MAX_DOCUMENT_DEPTH) size.depth = sizeOf(out).depth;\n if (size.nodes > MAX_DOCUMENT_NODES) {\n throw new PatchError(`Patched document exceeds the node limit (${MAX_DOCUMENT_NODES})`);\n }\n if (size.bytes > maxBytes) {\n throw new PatchError(`Patched document exceeds the size limit (${maxBytes} bytes of strings and keys)`);\n }\n if (size.depth > MAX_DOCUMENT_DEPTH) {\n throw new PatchError(`Patched document nests deeper than ${MAX_DOCUMENT_DEPTH} levels`);\n }\n if (size.carriedNodes > MAX_CARRIED_TIMES * MAX_DOCUMENT_NODES || size.carriedBytes > MAX_CARRIED_TIMES * maxBytes) {\n throw new PatchError(`Patch copies or moves more than its limit (${MAX_CARRIED_TIMES * MAX_DOCUMENT_NODES} values or ${MAX_CARRIED_TIMES * maxBytes} bytes of strings and keys)`);\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 the entries already stored stay as they are.\n *\n * A store that also implements `version` and `loadOne` lets a Coordinator\n * keep up with another writer: before each call it compares the entries the\n * store holds for the call's workspace with the entries it last wrote, and\n * reloads the workspace when they differ. A synchronous write that fails or\n * conflicts answers its call with -32603 and `data: {reason: \"store\"}`; the\n * Coordinator then reloads the workspace, and refuses calls on it the same\n * way until a reload succeeds. An asynchronous write that fails is reported,\n * and the next write carries its change again.\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 on a store without `version`, partition\n * workspaces so that no workspace is ever written by two, or hold an\n * 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\", \"invitations\",\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, or the store may have ` +\n `been changed outside this coordinator. A coordinator reloads the ` +\n `workspace and answers the call as failed, and the call may be sent ` +\n `again.`,\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 /**\n * The number of audit entries the store holds for one workspace, or\n * undefined when it holds none. Optional; see the concurrency model above.\n */\n version?(id: string): number | undefined;\n\n /** One workspace's record, or undefined when the store holds none. Optional. */\n loadOne?(id: string): WorkspaceRecord | undefined;\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 return [...this.held.keys()].map((id) => this.loadOne(id)!);\n }\n\n loadOne(id: string): WorkspaceRecord | undefined {\n const h = this.held.get(id);\n if (!h) return undefined;\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 return {\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\n version(id: string): number | undefined {\n return this.held.get(id)?.entries.length;\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 invite: (p: MethodParams<\"workspace.invite\">) => c(\"workspace.invite\", 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 acknowledge: (p: MethodParams<\"review.acknowledge\">) => c(\"review.acknowledge\", 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\";\n\n/**\n * Which calls a workspace that requires signatures verifies: every call, or\n * every call except an unsigned one from an agent member.\n */\nexport type SignaturePolicy = \"all\" | \"humans\";\n/**\n * Who may join a workspace: anyone (\"open\"), or only a participant an admin\n * invited with workspace.invite, and the first member (\"invite\").\n */\nexport type JoinPolicy = \"open\" | \"invite\";\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 * An admin's invitation to join (workspace.invite), held until the invitee\n * joins. The member takes its type and role; where it pins keys, the join's\n * keys are among them and the member holds them; where it names an OIDC\n * subject, the invitee joins with a token for that subject.\n */\nexport interface Invitation {\n uri: ParticipantUri;\n type: ParticipantType;\n role?: string;\n jwks?: { keys: Jwk[] };\n oidc_sub?: string;\n invited_by: ParticipantUri;\n invited_at: 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 * Who made the work under review: the task's assignee, then the member\n * that completed it. None of them may decide the review.\n */\n authors: ParticipantUri[];\n /**\n * The reviewers who have said they began this round, in the order they\n * did (review.acknowledge). A new round starts with none.\n */\n acknowledgements: { reviewer: ParticipantUri; ts: string }[];\n };\n history: { ts: string; from: ParticipantUri; state: TaskState; note?: string }[];\n /**\n * The authors of the work carried on from before: those of the task a\n * successor replaces, through escalate.raise or control.supersede, and\n * the members task.route or handoff.accept moved the task from. They\n * count among the authors of any review of this task.\n */\n prior_authors?: ParticipantUri[];\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 /** Which calls are verified where the workspace requires signatures. */\n signature_policy: SignaturePolicy;\n /** Who may join. */\n join_policy: JoinPolicy;\n /** The rule of a review that opens on task.complete; any_one_approves when unset. */\n review_rule?: string;\n members: Map<ParticipantUri, Member>;\n /** Invitations not yet taken up, by the URI each admits. */\n invitations: Map<ParticipantUri, Invitation>;\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\";\nimport { paramsError } from \"../params.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 bad = paramsError(p, [\n [\"range\", \"object\"], [\"range.from_seq\", \"integer\"], [\"range.to_seq\", \"integer\"], [\"issuer\", \"string\"],\n ]);\n if (bad) return bad;\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 || Array.isArray(receipt)) {\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 // Worded alike in both references, which name the option differently.\n return { error: rpcError(E.SCITT_RECEIPT_INVALID, \"No receipt verifier is 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 != null || p.to_seq != null) {\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 { paramsError } from \"../params.js\";\nimport { contentHash } from \"../canonical.js\";\nimport { rawValues } from \"../tracked.js\";\nimport { modeLE } from \"../types.js\";\nimport { openRequiredReviewAuthors, successorAuthors } from \"../coordinator.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\"]);\nconst SCOPE_ERROR = \"scope must be task, participant or 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 bad = paramsError(p, [\n [\"scope\", \"string\"], [\"participant_uri\", \"string\"], [\"uri\", \"string\"], [\"in_flight_policy\", \"string\"],\n ]);\n if (bad) return bad;\n const scope = (p.scope as string) || \"task\";\n if (!VALID_SCOPES.has(scope)) {\n return { error: rpcError(E.PARAMS, SCOPE_ERROR) };\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) return { error: rpcError(E.PARAMS, \"participant_uri is required\") };\n if (!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 bad = paramsError(p, [[\"scope\", \"string\"], [\"participant_uri\", \"string\"], [\"uri\", \"string\"]]);\n if (bad) return bad;\n const scope = (p.scope as string) || \"task\";\n if (!VALID_SCOPES.has(scope)) {\n return { error: rpcError(E.PARAMS, SCOPE_ERROR) };\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) return { error: rpcError(E.PARAMS, \"participant_uri is required\") };\n if (!ws.members.has(uri)) return { error: rpcError(E.PARAMS, `Unknown participant: ${uri}`) };\n // A pause holds until someone else lifts it: the paused member lifting\n // its own would make the pause its to keep or drop.\n if (uri === p.from) return { error: rpcError(E.NOT_AUTHORISED, \"A paused participant does not lift its own pause\") };\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 // A review a task requires ends with a decision. Its authors pulling the\n // emergency brake on it would end it with none; other members still can.\n if (openRequiredReviewAuthors(ws, task).includes(p.from as string)) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"The authors of the work under review cannot end its review without a decision\") };\n }\n task.state = \"cancelled\";\n task.updated_at = coord.now();\n task.history.push({ ts: task.updated_at, from: p.from as string, state: \"cancelled\", note: p.reason as string | undefined });\n return { result: { state: \"cancelled\" } };\n });\n\n coord.handlers.set(\"control.snapshot\", (p) => {\n const ws = coord.workspaces.get(p.workspace as string);\n if (!ws) return { error: rpcError(E.PARAMS, \"Unknown workspace\") };\n const bad = paramsError(p, [[\"include\", \"strings\"], [\"label\", \"string\"]]);\n if (bad) return bad;\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 bad = paramsError(p, [\n [\"to_snapshot_artefact_id\", \"string\"], [\"snapshot_artefact_id\", \"string\"], [\"snapshot_id\", \"string\"],\n [\"what_to_restore\", \"strings\"], [\"reason\", \"string\"],\n ]);\n if (bad) return bad;\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 // The admin role is granted by an admin (SPECIFICATION 6.3), and a\n // rollback, which any member may call, neither grants nor removes it.\n const role = (snapM.role as string) ?? cur.role;\n if (role !== \"admin\" && cur.role !== \"admin\") cur.role = 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 if (openRequiredReviewAuthors(ws, old).includes(p.from as string)) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"The authors of the work under review cannot end its review without a decision\") };\n }\n const newSpec = (p.successor_task as Record<string, unknown>) ?? {};\n if (typeof newSpec.kind !== \"string\" || !newSpec.kind) {\n return { error: rpcError(E.PARAMS, \"successor_task must include kind\") };\n }\n const bad = paramsError(p, [[\"successor_task.assignee\", \"string\"], [\"reason\", \"string\"]]);\n if (bad) return bad;\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 // Whoever made the work it replaces is an author of the successor's\n // review too, so superseding does not make its author a reviewer of it.\n newTask.prior_authors = successorAuthors(old, p.from);\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: {\n superseded_task_id: old.id, new_task_id: newId,\n ...(p.reason != null ? { reason: p.reason as string } : {}),\n } };\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 bad = paramsError(p, [[\"reason\", \"string\"]]);\n if (bad) return bad;\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 or production\") };\n }\n ws.mode_ceiling = m;\n return { result: { mode_ceiling: ws.mode_ceiling, ...(p.reason != null ? { reason: p.reason as string } : {}) } };\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 { paramsError } from \"../params.js\";\nimport type { Deliberation } from \"../types.js\";\n\n// Names a supplied id cannot take: JavaScript gives them special meaning as\n// object keys, and the patch engine refuses them as path segments too.\nconst RESERVED_IDS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n// A rule's argument is read by these patterns alone, so both references read\n// the same number from it: parseFloat and Python's float() each take forms\n// the other refuses, such as \"1.5x\", \"1_0\" and \"inf\".\nconst QUORUM_ARG = /^[0-9]+$/;\nconst THRESHOLD_ARG = /^[0-9]+(\\.[0-9]+)?$/;\n\nfunction parseRule(rule: string): { kind: string; params: Record<string, number> } {\n const colon = rule.indexOf(\":\");\n if (colon >= 0) {\n const kind = rule.slice(0, colon);\n const arg = rule.slice(colon + 1);\n if (kind === \"quorum\" && QUORUM_ARG.test(arg)) return { kind, params: { n: parseInt(arg, 10) } };\n if ((kind === \"weighted_vote\" || kind === \"weighted_vote_with_veto\") && THRESHOLD_ARG.test(arg)) {\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 for (const name of [\"to\", \"participants\"]) {\n const v = p[name];\n if (v != null && typeof v !== \"string\" && !(Array.isArray(v) && v.every((x) => typeof x === \"string\"))) {\n return { error: rpcError(E.PARAMS, `${name} must be a string or a list of strings`) };\n }\n }\n if (typeof p.rule !== \"string\") return { error: rpcError(E.PARAMS, \"rule must be a string\") };\n const bad = paramsError(p, [[\"weights\", \"object\"], [\"veto\", \"object\"]]);\n if (bad) return bad;\n // Weights are summed and vetoes read as true or false when the vote is\n // counted, so they are checked when it opens.\n const weights = (p.weights ?? {}) as Record<string, unknown>;\n if (!Object.values(weights).every((w) => typeof w === \"number\" && Number.isInteger(w))) {\n return { error: rpcError(E.PARAMS, \"weights must map participants to integers\") };\n }\n const veto = (p.veto ?? {}) as Record<string, unknown>;\n if (!Object.values(veto).every((v) => typeof v === \"boolean\")) {\n return { error: rpcError(E.PARAMS, \"veto must map participants to booleans\") };\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 // A supplied id names a new deliberation. One already in use was stored\n // over the existing object, which reopened, reset or replaced it.\n const suppliedDeliberationId = p.deliberation_id;\n if (suppliedDeliberationId !== undefined && suppliedDeliberationId !== null && suppliedDeliberationId !== \"\") {\n if (typeof suppliedDeliberationId !== \"string\") {\n return { error: rpcError(E.PARAMS, \"deliberation_id must be a string\") };\n }\n // The id is a key in the stored state, and a JavaScript object given\n // the key __proto__ drops it, so the object would be lost on a restart.\n if (RESERVED_IDS.has(suppliedDeliberationId)) {\n return { error: rpcError(E.PARAMS, `deliberation_id cannot be ${JSON.stringify(suppliedDeliberationId)}`) };\n }\n if (ws.deliberations.has(suppliedDeliberationId)) {\n return { error: rpcError(E.PARAMS, `deliberation_id already in use: ${suppliedDeliberationId}`) };\n }\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 const bad = paramsError(p, [[\"comment\", \"string\"], [\"text\", \"string\"]]);\n if (bad) return bad;\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 bad = paramsError(p, [[\"veto_invoked\", \"boolean\"]]);\n if (bad) return bad;\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 { heldBy, unionOf } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport { paramsError } from \"../params.js\";\nimport type { Handoff, HandoffTaskItem } from \"../types.js\";\n\n// Names a supplied id cannot take: JavaScript gives them special meaning as\n// object keys, and the patch engine refuses them as path segments too.\nconst RESERVED_IDS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\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 // The recipient is compared and looked up when the handoff is resolved.\n if (typeof p.to !== \"string\") return { error: rpcError(E.PARAMS, \"to must be a string\") };\n const bad = paramsError(p, [[\"context_links\", \"strings\"]]);\n if (bad) return bad;\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 if (t === null || typeof t !== \"object\" || Array.isArray(t) || typeof t.task_id !== \"string\") {\n return { error: rpcError(E.PARAMS, \"each entry in tasks must be an object with a string task_id\") };\n }\n const badItem = paramsError(t, [[\"blockers\", \"strings\"]]);\n if (badItem) return badItem;\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 // A supplied id names a new handoff. One already in use was stored\n // over the existing object, which reopened, reset or replaced it.\n const suppliedHandoffId = p.handoff_id;\n if (suppliedHandoffId !== undefined && suppliedHandoffId !== null && suppliedHandoffId !== \"\") {\n if (typeof suppliedHandoffId !== \"string\") {\n return { error: rpcError(E.PARAMS, \"handoff_id must be a string\") };\n }\n // The id is a key in the stored state, and a JavaScript object given\n // the key __proto__ drops it, so the object would be lost on a restart.\n if (RESERVED_IDS.has(suppliedHandoffId)) {\n return { error: rpcError(E.PARAMS, `handoff_id cannot be ${JSON.stringify(suppliedHandoffId)}`) };\n }\n if (ws.handoffs.has(suppliedHandoffId)) {\n return { error: rpcError(E.PARAMS, `handoff_id already in use: ${suppliedHandoffId}`) };\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 const bad = paramsError(p, [[\"accepted_task_ids\", \"strings\"]]);\n if (bad) return bad;\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 // The proposer offered tasks it held. One routed, superseded or handed\n // to someone else since is no longer the proposer's to give, and taking\n // it would move it away from whoever holds it now.\n for (const tid of acceptedIds) {\n if (ws.tasks.get(tid)?.assignee !== ho.proposer) {\n return { error: rpcError(E.HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER,\n `Task ${tid} is not currently assigned to ${ho.proposer}`) };\n }\n }\n const now = coord.now();\n for (const tid of acceptedIds) {\n const task = ws.tasks.get(tid)!;\n // The proposer, which holds the task and hands it on, stays among the\n // authors of the work (review/1.0 §3.1), so it cannot hand its work on\n // and then review it.\n if (acceptor !== task.assignee) task.prior_authors = unionOf(task.prior_authors ?? [], heldBy(task, ho.proposer));\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 { heldBy, unionOf } from \"../coordinator.js\";\nimport { E, rpcError } from \"../jsonrpc.js\";\nimport { paramsError } from \"../params.js\";\nimport type { RouteDecisionArtefact, Task } from \"../types.js\";\n\nconst CRIT: Record<string, number> = { low: 0, medium: 1, high: 2, critical: 3 };\nconst DECIMAL = /^-?[0-9]+(\\.[0-9]+)?$/;\n\n/**\n * The confidence a hint gives, 1.0 where it gives none. Read from an integer\n * or a decimal string alone, so both references read the same number:\n * Number() and Python's float() each take forms the other refuses, such as\n * \"\", \"0x10\" and \"inf\".\n */\nexport function confidenceOf(hints: Record<string, unknown>): number {\n const v = hints.confidence;\n if (typeof v === \"number\" && Number.isInteger(v)) return v;\n if (typeof v === \"string\" && DECIMAL.test(v)) return Number(v);\n return 1.0;\n}\n\n/** The rank of a hint's criticality, medium where it names none of the four. */\nexport function criticalityOf(hints: Record<string, unknown>): number {\n const crit = hints.criticality ?? \"medium\";\n return typeof crit === \"string\" && Object.prototype.hasOwnProperty.call(CRIT, crit) ? CRIT[crit] : 1;\n}\n\nfunction defaultDepth(hints: Record<string, unknown>): {\n depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n sampling?: number;\n summary: string;\n} {\n const conf = confidenceOf(hints);\n const r = criticalityOf(hints);\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 // The member the task leaves stays among the authors of its work where it\n // routes the task on itself (review/1.0 §3.1), so it cannot route its\n // work on and then review it.\n const leaving = heldBy(task, p.from);\n if (selected !== task.assignee && leaving.length) task.prior_authors = unionOf(task.prior_authors ?? [], leaving);\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 bad = paramsError(p, [[\"artefact_routing_hints\", \"object\"]]);\n if (bad) return bad;\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 bad = paramsError(p, [[\"default_escalation_target\", \"string\"]]);\n if (bad) return bad;\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 conf = confidenceOf(hints);\n const r = criticalityOf(hints);\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 { paramsError } from \"../params.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 // Both are written into the refusals below, where null reads one way in\n // each language.\n for (const f of [\"from\", \"old_kid\"]) {\n if (typeof p[f] !== \"string\") return { error: rpcError(E.PARAMS, `${f} must be a string`) };\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 // Keys are found by kid, so a new key under a kid the member holds would\n // be closed with the old one, or shadowed by it.\n if (member.keys.some((k) => k.kid === newJwk.kid)) {\n return { error: rpcError(E.PARAMS, `${p.from} already holds a key ${newJwk.kid}; a new key takes a kid of its own`) };\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 // Both are written into the refusals below, where null reads one way in\n // each language.\n for (const f of [\"target_uri\", \"kid\"]) {\n if (typeof p[f] !== \"string\") return { error: rpcError(E.PARAMS, `${f} must be a string`) };\n }\n const bad = paramsError(p, [[\"from\", \"string\"], [\"reason\", \"string\"]]);\n if (bad) return bad;\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 { paramsError } from \"../params.js\";\nimport { rawValues } from \"../tracked.js\";\nimport type { WhisperPrompt, Envelope } from \"../types.js\";\n\n// Names a supplied id cannot take: JavaScript gives them special meaning as\n// object keys, and the patch engine refuses them as path segments too.\nconst RESERVED_IDS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\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 const bad = paramsError(p, [[\"options\", \"list\"], [\"urgency\", \"string\"]]);\n if (bad) return bad;\n // The deadline is required, and a number of milliseconds.\n if (typeof p.deadline_ms !== \"number\" || !Number.isInteger(p.deadline_ms)) {\n return { error: rpcError(E.PARAMS, \"deadline_ms must be an integer\") };\n }\n const to = p.to;\n const askee: string[] = Array.isArray(to) ? (to as string[]) : [to as string];\n // A supplied id names a new whisper. One already in use was stored\n // over the existing object, which reopened, reset or replaced it.\n const suppliedWhisperId = p.whisper_id;\n if (suppliedWhisperId !== undefined && suppliedWhisperId !== null && suppliedWhisperId !== \"\") {\n if (typeof suppliedWhisperId !== \"string\") {\n return { error: rpcError(E.PARAMS, \"whisper_id must be a string\") };\n }\n // The id is a key in the stored state, and a JavaScript object given\n // the key __proto__ drops it, so the object would be lost on a restart.\n if (RESERVED_IDS.has(suppliedWhisperId)) {\n return { error: rpcError(E.PARAMS, `whisper_id cannot be ${JSON.stringify(suppliedWhisperId)}`) };\n }\n if (ws.whispers.has(suppliedWhisperId)) {\n return { error: rpcError(E.PARAMS, `whisper_id already in use: ${suppliedWhisperId}`) };\n }\n }\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 // An option that is not an object offers no id, as in Python.\n const valid = new Set(prompt.options\n .filter((o) => o !== null && typeof o === \"object\" && !Array.isArray(o))\n .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. A check runs\n // outside any call, under the rules a call keeps: it waits for a held\n // workspace, and a lapse whose write fails is undone and reported to nobody.\n coord.checkWhisperLapses = (workspaceId: string, now?: string): Envelope[] =>\n coord.outsideCall(workspaceId, () => lapse(workspaceId, now));\n\n function lapse(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 rawValues(ws.whispers)) {\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 // The prompts are read without being recorded, so each that lapses is\n // set again to be written.\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, sha256Hex, ZERO_HASH } from \"./canonical.js\";\nimport { ALWAYS_AVAILABLE, OWNING_PROFILE, PROFILE_VERSIONS } from \"./catalogue.js\";\nimport {\n isEd25519Key, isWebAuthnKey, jwkThumbprint, parseWebAuthnAssertion, publicKeyFromJwk, verifyEnvelope,\n webAuthnFailure,\n} from \"./crypto.js\";\nimport { IdFactory } from \"./ids.js\";\nimport { E, isValidEnvelope, rpcError } from \"./jsonrpc.js\";\nimport { paramsError } from \"./params.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, StoreConflictError } 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 Invitation,\n JoinPolicy,\n Jwk,\n Member,\n Mode,\n OverrideArtefact,\n SignaturePolicy,\n ParticipantUri,\n SnapshotArtefact,\n Task,\n TaskId,\n TaskState,\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\", \"workspace.invite\",\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 /**\n * Require signatures on every workspace, as advertising\n * `security-signed/1.0` does on one.\n */\n requireSignatures?: boolean;\n /**\n * The signature policy of a workspace whose `workspace.create` names none:\n * \"all\" (the default) verifies every call, and \"humans\" takes an unsigned\n * call from an agent member.\n */\n signaturePolicy?: SignaturePolicy;\n /**\n * The join policy of a workspace whose `workspace.create` names none:\n * \"open\" (the default) admits anyone, and \"invite\" admits only a\n * participant an admin invited, and the first member.\n */\n joinPolicy?: JoinPolicy;\n enforceStepUp?: boolean;\n requireReadMembership?: boolean;\n /** Largest envelope accepted (default 1 MiB), published in the descriptor. */\n maxEnvelopeBytes?: number;\n /** Told of each audit entry once the store has taken it. */\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. What happens to the call is `storeErrors`'s to say.\n */\n onStoreError?: (err: unknown, record: { id: string; version: number }) => void;\n /**\n * What a failed synchronous write does to the call that made it. \"raise\"\n * (the default): the call is answered with -32603 and\n * `data: { reason: \"store\" }`, and the workspace goes back to what the\n * store holds. \"log\": the call is answered as it was, and the next write\n * carries its change again. A write another writer got to first is\n * answered as \"raise\" says under either, and the call may be sent again.\n * An asynchronous write's call was answered already, and the next write\n * to the workspace carries what this one did not.\n */\n storeErrors?: \"raise\" | \"log\";\n /**\n * Called when a handler throws, with the error and the call's method and\n * workspace. The caller is answered with -32603 and no detail. When unset,\n * the error is written to stderr.\n */\n onInternalError?: (err: unknown, call: { method: string; workspace?: string }) => 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\nconst MODES = new Set<string>([\"shadow\", \"trial\", \"production\"]);\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\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\n/** Whether a workspace advertises a profile, matched by name as the gate matches it. */\nfunction advertises(ws: Workspace, name: string): boolean {\n return ws.profiles.some((p) => p === name || p.startsWith(name + \"/\"));\n}\n\n/**\n * Whether a profile id names a profile the catalogue lists, at its major\n * version: `<name>/<major>.<minor>` in ASCII digits (SPECIFICATION 6.5). A\n * later minor version is the same profile (SPECIFICATION 15.4).\n */\nfunction knownProfile(id: string): boolean {\n const m = /^([a-z][a-z0-9-]*)\\/(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$/.exec(id);\n if (!m || !Object.prototype.hasOwnProperty.call(PROFILE_VERSIONS, m[1])) return false;\n return PROFILE_VERSIONS[m[1]].split(\".\")[0] === m[2];\n}\n\n/** Profiles that cannot be removed once advertised: each states a guarantee about every later call. */\nconst LASTING_PROFILES = [\"security-signed\", \"identity-oidc\", \"identity-vc\"];\n\n/** The refusal of a profile list naming a profile the catalogue does not list, or null. */\nfunction profilesError(profiles: string[]): { error: ReturnType<typeof rpcError> } | null {\n const unknown = profiles.find((x) => !knownProfile(x));\n if (unknown === undefined) return null;\n return { error: rpcError(E.PARAMS,\n `Unknown profile ${JSON.stringify(unknown)}: a profile id is <name>/<major>.<minor> for a profile the catalogue lists`) };\n}\n\n/** Names a task.create idempotency key cannot take (SPECIFICATION 12.3). */\nconst RESERVED_KEYS = [\"__proto__\", \"constructor\", \"prototype\"];\n\n/** The participant types SPECIFICATION 5.1 names, each the scheme of its URIs. */\nconst PARTICIPANT_TYPES = [\"human\", \"agent\", \"service\", \"group\", \"workspace\"];\n\n/** The types that may hold the admin role (SPECIFICATION 6.3). */\nconst ADMIN_TYPES = [\"human\", \"service\"];\n\n/**\n * Why `uri` cannot name a participant of this type, or null: the type is one\n * of the five, and the URI's scheme names it (SPECIFICATION 5.1). `field` is\n * the param that holds the URI.\n */\nfunction participantError(type: string, uri: string, field: string): { error: ReturnType<typeof rpcError> } | null {\n if (!PARTICIPANT_TYPES.includes(type)) {\n return { error: rpcError(E.PARAMS, \"type must be human, agent, service, group or workspace\") };\n }\n if (!uri.startsWith(`${type}:`)) {\n return { error: rpcError(E.PARAMS, `${field} must start with \"${type}:\" for type ${type}`) };\n }\n // A group: or workspace: URI addresses everyone it covers, as a review's\n // `to` does, so it names no one who could join and act.\n if (type === \"group\" || type === \"workspace\") {\n return { error: rpcError(E.PARAMS, \"group: and workspace: URIs name address scopes, which cannot join\") };\n }\n return null;\n}\n\n/** Whether a key may sign now: neither revoked nor past its validity. */\nfunction inForce(key: KeyRecord, now: string): boolean {\n return !(key.revoked_at !== undefined && now >= key.revoked_at)\n && !(key.valid_until !== undefined && now >= key.valid_until);\n}\n\n/**\n * Whether two JWKs are the same key: the same kid and the same RFC 7638\n * thumbprint, or, for a key with no thumbprint, the same JSON throughout.\n */\nfunction sameKey(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n const material = (k: Record<string, unknown>) => jwkThumbprint(k) ?? canonicalize(k).toString(\"utf-8\");\n return a.kid === b.kid && material(a) === material(b);\n}\n\n/**\n * The keys a credential binds for a join: its confirmation key, named by its\n * kid or else by its RFC 7638 thumbprint, or, where it carries none, the\n * join's keys whose thumbprint its nonce is (SPECIFICATION 5.4). Every key\n * the join carries must be a bound one: null where one is not. Undefined\n * where the credential binds no key.\n */\nfunction credentialKeys(cnf: unknown, nonce: unknown, joinKeys: Array<Record<string, unknown> & { kid: string }>):\n Array<Record<string, unknown> & { kid: string }> | null | undefined {\n if (isObject(cnf)) {\n const kid = typeof cnf.kid === \"string\" && cnf.kid !== \"\" ? cnf.kid : jwkThumbprint(cnf);\n if (kid === undefined) return null;\n const key = { ...cnf, kid };\n return joinKeys.every((j) => sameKey(key, j)) ? [key] : null;\n }\n if (typeof nonce === \"string\") return joinKeys.every((j) => jwkThumbprint(j) === nonce) ? joinKeys : null;\n return undefined;\n}\n\n/** An invitation, read without recording it as changed. */\nfunction rawInvitation(ws: Workspace, uri: string): Invitation | undefined {\n return Map.prototype.get.call(ws.invitations, uri) as Invitation | undefined;\n}\n\n/**\n * Whether nobody has joined the workspace yet: it holds no member and its log\n * holds no accepted participant.join. A workspace whose members have all left\n * has had its first member.\n */\nfunction awaitsFirstMember(ws: Workspace): boolean {\n if (ws.members.size > 0) return false;\n return !ws.audit.some((e) => e.outcome == null && entryCall(e)?.method === \"participant.join\");\n}\n\n/** The keys of a join's `jwks` a signature can name: objects with a non-empty string kid. */\nfunction signingKeys(jwks: unknown): Array<Record<string, unknown> & { kid: string }> {\n const keys = isObject(jwks) && Array.isArray(jwks.keys) ? jwks.keys : [];\n return keys.filter((j): j is Record<string, unknown> & { kid: string } =>\n isObject(j) && typeof j.kid === \"string\" && j.kid !== \"\");\n}\n\n/**\n * A call as the log holds it. A participant.join keeps its credentials off\n * the chain: an `oidc_token` is recorded as the SHA-256 of its UTF-8 bytes\n * and a `vc_presentation` as the SHA-256 of its JCS form, so the log shows\n * which credential a member joined with and never holds one a reader could\n * present again.\n */\nfunction recordedForm(envelope: Envelope): Envelope {\n if (envelope.method !== \"participant.join\" || !isObject(envelope.params)) return envelope;\n const params = { ...envelope.params };\n if (typeof params.oidc_token === \"string\") params.oidc_token = sha256Hex(params.oidc_token);\n if (isObject(params.vc_presentation)) params.vc_presentation = contentHash(params.vc_presentation);\n return { ...envelope, params };\n}\n\n/** The answer to a call whose workspace the store could not be brought in line with. */\nfunction storeFailed() {\n return rpcError(E.INTERNAL, \"Internal error\", { reason: \"store\" });\n}\n\n/** The workspace a call names, where it names one. */\nfunction targetOf(envelope: unknown): WorkspaceId | undefined {\n const params = isObject(envelope) ? envelope.params : undefined;\n const id = isObject(params) ? params.workspace : undefined;\n return typeof id === \"string\" && id !== \"\" ? id : undefined;\n}\n\n/**\n * The fields that keep a null. A whisper's default_if_lapsed is required, and\n * null is the default a lapse applies and records.\n */\nconst KEPT_NULLS: Readonly<Record<string, readonly string[]>> = { whispers: [\"default_if_lapsed\"] };\n\n/** Deletes the fields of `o` that hold null, but those named in `keep`. */\nfunction dropNulls(o: Record<string, unknown>, keep: readonly string[] = []): void {\n for (const key of Object.keys(o)) if (o[key] === null && !keep.includes(key)) delete o[key];\n}\n\n/**\n * Puts one object of a workspace's collection in the shape this coordinator\n * stores and restores, in place, whichever coordinator made it. Called on\n * copies only: the objects a workspace holds keep what its handlers put in\n * them, and every read treats a field holding null as one left out. A field\n * with no value is left out: the Python coordinator writes it as null, and a\n * call that gives a param as null gives it no value, as both coordinators\n * read params. The Python coordinator also names a history entry's sender\n * `from_` and keeps a route decision's fields of its kind in `extra`; this\n * one names the sender `from` and keeps those fields beside `kind`. What an\n * input, an output or an artefact holds is kept as it is.\n */\nfunction shapeObject(name: string, item: Record<string, unknown>): Record<string, unknown> {\n if (name === \"route_decisions\") {\n const extra = item.extra;\n delete item.extra;\n if (isObject(extra)) Object.assign(item, extra);\n item.kind = \"route_decision\";\n }\n dropNulls(item, KEPT_NULLS[name]);\n const each = (o: Record<string, unknown>, field: string, f?: (x: Record<string, unknown>) => void) => {\n if (!Array.isArray(o[field])) return;\n for (const x of o[field] as unknown[]) {\n if (isObject(x)) {\n dropNulls(x);\n f?.(x);\n }\n }\n };\n if (name === \"members\") each(item, \"keys\");\n if (name === \"tasks\") {\n each(item, \"history\", (h) => {\n if (h.from === undefined && typeof h.from_ === \"string\") h.from = h.from_;\n delete h.from_;\n });\n if (isObject(item.review)) {\n dropNulls(item.review);\n each(item.review, \"decisions\");\n }\n }\n if (name === \"deliberations\") each(item, \"votes\");\n if (name === \"handoffs\") {\n each(item, \"tasks\");\n if (Array.isArray(item.accepted_task_ids) && item.accepted_task_ids.length === 0) delete item.accepted_task_ids;\n }\n return item;\n}\n\n/** A copy of one object of a collection, in the shape this coordinator stores. */\nfunction storedCopy(name: string, item: Record<string, unknown>): Record<string, unknown> {\n return shapeObject(name, structuredClone(item));\n}\n\n/**\n * A workspace snapshot in this coordinator's shape, whichever coordinator\n * wrote it: its own fields with no value left out, and a copy of each object\n * of its collections put in shape. The snapshot itself is not changed.\n */\nfunction shapeSnapshot(w: Record<string, unknown>): Record<string, unknown> {\n const out = { ...w };\n dropNulls(out);\n for (const name of COLLECTIONS) {\n if (Array.isArray(out[name])) {\n out[name] = (out[name] as unknown[]).map((x) => (isObject(x) ? storedCopy(name, x) : x));\n }\n }\n return out;\n}\n\n/**\n * Whether a task's work must be decided by a person: it carries\n * review_required, or it runs in trial on a workspace advertising modes/1.0.\n */\nexport function reviewRequired(ws: Workspace, task: Task): boolean {\n return task.review_required === true || (task.mode === \"trial\" && advertises(ws, \"modes\"));\n}\n\n/** A member, read without recording it as changed. */\nfunction rawMember(ws: Workspace, uri: unknown): Member | undefined {\n return typeof uri === \"string\" ? Map.prototype.get.call(ws.members, uri) as Member | undefined : undefined;\n}\n\n/** The members of the lists in order, each once. */\nexport function unionOf(...lists: ReadonlyArray<ParticipantUri>[]): ParticipantUri[] {\n const out: ParticipantUri[] = [];\n for (const list of lists) for (const uri of list) if (!out.includes(uri)) out.push(uri);\n return out;\n}\n\n/**\n * Who made the work: the task's assignee, then whoever completed it, then\n * the authors it carries from a task it replaces, once each.\n */\nexport function authorsOf(task: Task, completer: unknown): ParticipantUri[] {\n const authors: ParticipantUri[] = [task.assignee];\n if (typeof completer === \"string\" && completer !== task.assignee) authors.push(completer);\n return unionOf(authors, Array.isArray(task.prior_authors) ? task.prior_authors : []);\n}\n\n/**\n * The state a task was in before the history entry at `i`, passing over\n * pauses, which leave the work where it was.\n */\nfunction stateBefore(history: Task[\"history\"], i: number): TaskState | undefined {\n for (let j = i - 1; j >= 0; j--) {\n if (history[j].state !== \"paused\") return history[j].state;\n }\n return undefined;\n}\n\n/**\n * Whether the history entry at `i` records the work completed: the task\n * entering `completed` from any state but review. A reviewer's decision\n * completes a task out of review, and an entry a task already completed\n * takes, such as a route or a handoff of it, completes nothing.\n */\nfunction workCompletion(history: Task[\"history\"], i: number): boolean {\n if (history[i].state !== \"completed\") return false;\n const before = stateBefore(history, i);\n return before !== \"review_requested\" && before !== \"completed\";\n}\n\n/** The sender of the task's latest completion of the work, if it has one. */\nfunction lastCompleter(task: Task): ParticipantUri | undefined {\n for (let i = task.history.length - 1; i >= 0; i--) {\n if (workCompletion(task.history, i)) return task.history[i].from;\n }\n return undefined;\n}\n\n/** The notes on the history entries of the reviews task.complete opened. */\nconst OPENED_ON_COMPLETE = \"review required; opened on task.complete\";\nconst NEW_ROUND_ON_COMPLETE = \"a new round of the review; opened on task.complete\";\n\n/**\n * The authors of a review recorded before authors were kept, read from the\n * task's history: the assignee, whoever completed the work, whether the\n * completion opened the review or came before a review.request, and the\n * member whose review.request opened the review, which supplied the\n * artefact under review. A reviewer's decision that completed the task is\n * not a completion of the work.\n */\nfunction storedAuthors(task: Task): ParticipantUri[] {\n let requester: ParticipantUri | undefined;\n const withRequester = (authors: ParticipantUri[]) => unionOf(authors, requester !== undefined ? [requester] : []);\n for (let i = task.history.length - 1; i >= 0; i--) {\n const h = task.history[i];\n const opens = h.state === \"review_requested\" && stateBefore(task.history, i) !== \"review_requested\";\n if (opens && (h.note === OPENED_ON_COMPLETE || h.note === NEW_ROUND_ON_COMPLETE)) return withRequester(authorsOf(task, h.from));\n if (opens && requester === undefined) requester = h.from;\n if (workCompletion(task.history, i)) return withRequester(authorsOf(task, h.from));\n }\n return withRequester(authorsOf(task, undefined));\n}\n\n/** The states in which a task is over. */\nconst ENDED: ReadonlyArray<TaskState> = [\"completed\", \"declined\", \"cancelled\", \"superseded\", \"escalated\"];\n\n/**\n * The authors a review the task requires holds, whatever state the task is\n * in: those of its own review, until a reviewer rejects or overrides the\n * round under review, or approves it as its rule asks; or, for a task with\n * no review yet, those of the task it replaces, since an escalation or a\n * supersede carries that review on, however long the chain.\n */\nfunction reviewHolds(ws: Workspace, task: Task): ParticipantUri[] {\n const seen = new Set<string>();\n for (let t: Task | undefined = task; t && !seen.has(t.id); t = typeof t.supersedes === \"string\" ? ws.tasks.get(t.supersedes) : undefined) {\n seen.add(t.id);\n if (!reviewRequired(ws, t)) return [];\n if (t.review) {\n const decided = t.review.decisions.some((d) => d.kind === \"reject\" || d.kind === \"override\") || reviewSatisfied(t.review);\n return decided ? [] : t.review.authors;\n }\n }\n return [];\n}\n\n/**\n * The authors a review the task requires holds to it: from the moment the\n * review opens until the task is over, unless a reviewer has rejected the\n * round under review, and through a successor an escalation or a supersede\n * makes. They may take the work back to revise it, and hand it on with\n * escalate.raise; they do not end the task, or its successor, around a\n * decision. Once a reviewer rejects the work, its authors may give the task\n * up. Empty where the task holds no such review.\n */\nexport function openRequiredReviewAuthors(ws: Workspace, task: Task): ParticipantUri[] {\n return ENDED.includes(task.state) ? [] : reviewHolds(ws, task);\n}\n\n/**\n * The task's assignee, as an author of its work, where it moves the task on\n * itself; otherwise nobody. Whoever completed the work is an author by its\n * completion. A member another member routed or escalated the task to made\n * none of the work it was handed, so nobody can leave a person out of a\n * review's reviewers by passing the task through them.\n */\nexport function heldBy(task: Task, mover: unknown): ParticipantUri[] {\n return mover === task.assignee ? [task.assignee] : [];\n}\n\n/**\n * The authors a successor carries from the task it replaces: that task's\n * review authors where it held a review, its assignee where heldBy counts\n * it, whoever completed the work, and the authors it carried itself.\n */\nexport function successorAuthors(old: Task, mover: unknown): ParticipantUri[] {\n const completer = lastCompleter(old);\n return unionOf(old.review ? old.review.authors : [], heldBy(old, mover),\n completer !== undefined ? [completer] : [],\n Array.isArray(old.prior_authors) ? old.prior_authors : []);\n}\n\n/** Whether a URI is an address scope, which every member it covers answers to. */\nfunction isScope(uri: unknown): boolean {\n return typeof uri === \"string\" && (uri.startsWith(\"workspace:\") || uri.startsWith(\"group:\"));\n}\n\nfunction reply(env: Envelope, body: { result?: unknown; error?: { code: number; message: string; data?: unknown } }): Envelope {\n // JSON-RPC answers with a null id where the request carries none, or is\n // not an object at all, as the Python reference does, so dispatch(null)\n // is answered too.\n const sent = env !== null && typeof env === \"object\" && !Array.isArray(env) ? env.id : undefined;\n const out = { jsonrpc: \"2.0\", id: sent ?? null } as Envelope;\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`: refusals, and the seq each accepted call took. */\ninterface SignedIndex {\n refused: Map<string, { seq: number; code: number }>;\n accepted: Map<string, number>;\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 // A log written before signed copies were refused can hold one call twice;\n // the first is where it took effect.\n else if (!index.accepted.has(digest)) index.accepted.set(digest, entry.seq);\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 /**\n * Workspaces whose store copy may differ from memory after a synchronous\n * write failed or conflicted. Each is reloaded from the store before the\n * next call on it, which is refused while the reload fails.\n */\n private held = new Set<WorkspaceId>();\n /** Entries appended and not yet written, which the audit listeners hear of once they are. */\n private unannounced = new WeakMap<Workspace, AuditEntry[]>();\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 with their\n * seq. Rebuilt 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 if (this.options.storeErrors !== \"log\") this.held.add(ws.id);\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 this.announce(ws, taken.version);\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 // The call that made this change is answered as failed, and the\n // workspace is reloaded from the store before it is used again; under\n // \"log\" the call stands, and the next write carries the change. A\n // write another writer got to first fails its call under either.\n if (err instanceof StoreConflictError || this.options.storeErrors !== \"log\") this.held.add(ws.id);\n failed(err);\n return;\n }\n if (isThenable(result)) return Promise.resolve(result).then(done, failed);\n done();\n }\n\n /** Tell the audit listeners of the entries now written, up to `upTo`. */\n private announce(ws: Workspace, upTo: number): void {\n const queued = this.unannounced.get(ws);\n if (!queued?.length) return;\n const now = queued.filter((e) => e.seq < upTo);\n this.unannounced.set(ws, queued.filter((e) => e.seq >= upTo));\n for (const entry of now) {\n for (const l of this.auditListeners) {\n try { l(ws, entry); } catch { /* listeners never break dispatch */ }\n }\n }\n }\n\n /**\n * The change since the last write, taking the recorded keys with it. Each\n * object is written as a copy in the shape a restore gives back, so a\n * coordinator restarted on the store holds what this one holds, and the\n * workspace's own objects are left as they are.\n */\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, Record<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, Record<string, unknown>]>) {\n all[key] = storedCopy(name, 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) {\n const value = map.peek(key);\n changed[key] = value === undefined ? null : storedCopy(name, value);\n }\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 (err) {\n // Nothing was written. The next save builds the whole workspace again.\n this.reportStoreError(err, { id: ws.id, version: next });\n return;\n }\n\n const upTo = ws.audit.length;\n const pending = this.saveChains.get(ws.id);\n if (pending) {\n this.trackSave(pending.then(() => this.store.save(record)), record, () => this.announce(ws, upTo));\n return;\n }\n let result: PromiseLike<void> | void;\n try {\n result = this.store.save(record);\n } catch (err) {\n if (this.options.storeErrors !== \"log\") this.held.add(ws.id);\n this.reportStoreError(err, record);\n return;\n }\n if (isThenable(result)) {\n this.trackSave(Promise.resolve(result), record, () => this.announce(ws, upTo));\n return;\n }\n this.announce(ws, upTo);\n }\n\n private trackSave(save: Promise<void>, record: WorkspaceRecord, saved: () => void): void {\n const guarded = save.then(saved, 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 reportInternalError(err: unknown, method: string, workspace: string | undefined): void {\n const call = { method, ...(workspace !== undefined ? { workspace } : {}) };\n if (this.options.onInternalError) {\n try {\n this.options.onInternalError(err, call);\n } catch {\n void 0;\n }\n return;\n }\n console.error(`chap coordinator: ${method} failed with an internal error:`, err);\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 const line = `chap coordinator: writing workspace ${record.id} to the store failed: ${message}`;\n // Another writer having written first is handled: the workspace is\n // reloaded, and the call may be sent again.\n if (err instanceof StoreConflictError) console.warn(line);\n else console.error(line);\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` may decide the task's open review. Applied to\n * review-decision methods (decide.* and abstain.declare) and to\n * review.acknowledge: to act on a review you must not be an author of the\n * work under review, must be a human member where the task requires\n * review, and must be one of the reviewers it was addressed to (the `to`\n * set on review.request).\n * Membership is the floor; this is the eligibility ceiling for decisions.\n * Returns an error fragment if not eligible, else null.\n */\n private requireReviewer(ws: Workspace, task: Task, sender: unknown): { error: ReturnType<typeof rpcError> } | null {\n const review = task.review;\n if (!review) return null;\n // A decision by whoever made the work is not a review of it, whatever\n // the reviewer set says, broadcast scopes included.\n if (typeof sender === \"string\" && review.authors.includes(sender)) {\n return { error: rpcError(E.NOT_AUTHORISED, \"The author of the work under review cannot decide it\") };\n }\n if (reviewRequired(ws, task) && rawMember(ws, sender)?.type !== \"human\") {\n return { error: rpcError(E.NOT_AUTHORISED, `This task requires a person's review: ${String(sender)} is not a human member`) };\n }\n if (!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 signature_policy: ws.signature_policy,\n join_policy: ws.join_policy,\n review_rule: ws.review_rule,\n chain_head: ws.chain_head,\n chain_enabled: ws.chain_enabled,\n };\n }\n\n /**\n * One workspace as `snapshot()` holds it: each object of its collections a\n * copy in the shape the store keeps. Reads nothing as a change.\n */\n private snapshotOf(ws: Workspace): Record<string, unknown> {\n const { chain_head, chain_enabled, ...own } = this.metaOf(ws);\n const stored = (name: (typeof COLLECTIONS)[number]) =>\n Array.from(rawValues(ws[name] as unknown as TrackedMap<string, Record<string, unknown>>))\n .map((v) => storedCopy(name, v));\n return {\n ...own,\n members: stored(\"members\"),\n tasks: stored(\"tasks\"),\n overrides: stored(\"overrides\"),\n whispers: stored(\"whispers\"),\n deliberations: stored(\"deliberations\"),\n handoffs: stored(\"handoffs\"),\n snapshots: stored(\"snapshots\"),\n route_decisions: stored(\"route_decisions\"),\n invitations: stored(\"invitations\"),\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(snapshot: Record<string, unknown>): Workspace {\n const w = shapeSnapshot(snapshot);\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 // A workspace written before the policy existed verified every call,\n // and one written before the join policy existed admitted anyone.\n signature_policy: w.signature_policy === \"humans\" ? \"humans\" : \"all\",\n join_policy: w.join_policy === \"invite\" ? \"invite\" : \"open\",\n review_rule: typeof w.review_rule === \"string\" && reviewRuleSupported(w.review_rule) ? w.review_rule : 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 invitations: 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 // A member written before its type was checked against its URI takes\n // the type the scheme names, and holds the admin role only where that\n // type may (SPECIFICATION 5.1, 6.3).\n const scheme = typeof m.uri === \"string\" ? m.uri.split(\":\")[0] : \"\";\n if (PARTICIPANT_TYPES.includes(scheme)) m.type = scheme as Member[\"type\"];\n if (m.role === \"admin\" && !ADMIN_TYPES.includes(m.type)) m.role = \"participant\";\n ws.members.set(m.uri, m);\n }\n for (const t of (w.tasks as Task[]) ?? []) {\n // A review written before authors were recorded takes them from the\n // task's history.\n if (t.review && !Array.isArray(t.review.authors)) t.review.authors = storedAuthors(t);\n // and one written before acknowledgements were kept has none.\n if (t.review && !Array.isArray(t.review.acknowledgements)) t.review.acknowledgements = [];\n ws.tasks.set(t.id, t);\n }\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 for (const x of (w.invitations as Invitation[]) ?? []) ws.invitations.set(x.uri, x);\n return ws;\n }\n\n // -- dispatch ------------------------------------------------------\n\n dispatch(envelope: Envelope): Envelope {\n this.frozenNow = this.advanceClock();\n this.tracker.depth++;\n let response: Envelope;\n let target: WorkspaceId | undefined;\n let ran = false;\n try {\n target = targetOf(envelope);\n const refused = target === undefined ? null : this.keepUp(target);\n if (refused) {\n response = reply(envelope, { error: refused });\n } else {\n ran = true;\n response = this._dispatch(envelope);\n if (response.error) this.recordRefusal(envelope, response.error);\n else if (target === undefined && envelope.method === \"workspace.create\") {\n target = (response.result as { workspace?: WorkspaceId } | undefined)?.workspace;\n }\n }\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 // The call's write failed, so the store does not hold what it did. It is\n // answered as failed, and the workspace goes back to what the store holds.\n if (ran && target !== undefined && this.tracker.depth === 0 && this.held.has(target)) {\n this.reload(target);\n return reply(envelope, { error: storeFailed() });\n }\n return response;\n }\n\n /**\n * Work that changes a workspace outside any call, a whisper lapse check\n * for one, kept to the rules a call keeps (SPECIFICATION 10.3): the\n * workspace is first brought up to date with the store, and left alone\n * as long as it is held; what the work changed is written once, when it ends;\n * and where that write fails, the workspace goes back to what the store\n * holds and the work's results are dropped, since none took effect.\n */\n outsideCall<T>(id: WorkspaceId, work: () => T[]): T[] {\n if (this.tracker.depth > 0) return work();\n if (this.keepUp(id)) return [];\n this.tracker.depth++;\n let out: T[];\n try {\n out = work();\n } finally {\n if (--this.tracker.depth === 0) this.flushUnflushed();\n }\n if (this.held.has(id)) {\n this.reload(id);\n return [];\n }\n return out;\n }\n\n /**\n * Before a call on a workspace: where the store holds a different number of\n * audit entries for it than this instance last wrote, another writer has\n * written it, and it is reloaded. A workspace held after a failed write is\n * reloaded as well, and the call refused while that fails.\n */\n private keepUp(id: WorkspaceId): ReturnType<typeof rpcError> | null {\n if (this.held.has(id)) return this.reload(id) ? null : storeFailed();\n if (typeof this.store.version !== \"function\" || this.saveChains.has(id)) return null;\n let stored: number | undefined;\n try {\n stored = this.store.version(id);\n } catch {\n // Unread, the store may still take the call's write; if it does not,\n // the write fails and is answered as failed.\n return null;\n }\n if (isThenable(stored)) return null;\n const ws = this.workspaces.get(id);\n const p = ws ? this.persisted.get(ws) : undefined;\n // A workspace written whole on its next write replaces the store's copy.\n if (ws && (!p || p.replace)) return null;\n if (stored === p?.seq) return null;\n return this.reload(id) ? null : storeFailed();\n }\n\n /** Replace a workspace with what the store holds of it. False when it cannot be read. */\n private reload(id: WorkspaceId): boolean {\n let record: WorkspaceRecord | undefined;\n try {\n if (typeof this.store.loadOne === \"function\") {\n record = this.store.loadOne(id);\n } else {\n const all = this.store.load();\n if (isThenable(all)) return false;\n record = (all as WorkspaceRecord[]).find((r) => r.id === id);\n }\n if (isThenable(record)) return false;\n } catch (err) {\n this.reportStoreError(err, { id, version: this.workspaces.get(id)?.audit.length ?? 0 });\n return false;\n }\n const old = this.workspaces.get(id);\n if (old) this.unflushed.delete(old);\n if (record) {\n let ws: Workspace;\n try {\n ws = this.rebuild(record.data as Record<string, unknown>);\n } catch (err) {\n this.reportStoreError(err, { id, version: record.version });\n return false;\n }\n this.workspaces.set(id, ws);\n this.markWritten(ws);\n this.wsVersions.set(id, record.version);\n } else {\n this.workspaces.delete(id);\n }\n this.held.delete(id);\n return true;\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 // A workspace is named by a non-empty string. A list or an object names\n // none, and an empty string is no id participant.join could make a\n // workspace under, so both references refuse either before any lookup.\n if (params.workspace !== undefined && (typeof params.workspace !== \"string\" || !params.workspace)) {\n return reply(envelope, { error: rpcError(E.PARAMS, \"workspace must be a non-empty string\") });\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 // and one that matches an accepted call is refused with -32075. The log\n // publishes every call, signature and all, so without this anyone who can\n // read the log could send a refused request again once whatever refused\n // it had changed, or an accepted one again once it applied anew, a\n // reviewer's reject to a resubmitted artefact for instance, and it would\n // 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 index = this.signedIndex(ws);\n const digest = signedDigest(recordedForm(envelope));\n const prior = index.refused.get(digest);\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 const accepted = index.accepted.get(digest);\n if (accepted !== undefined) {\n return reply(envelope, { error: rpcError(E.SIG_ALREADY_ACCEPTED,\n `Accepted at seq ${accepted}; a signed request takes effect once`,\n { accepted_at_seq: accepted }) });\n }\n }\n }\n\n // security-signed/1.0: verify the top-level sig where the workspace\n // requires signatures, because it advertises the profile or this\n // coordinator is configured to require them. participant.join and\n // workspace.create are bootstrap operations that run before any signing\n // key is registered for the actor, so they cannot be signature-verified.\n // Under the \"humans\" policy a call that carries no signature is taken\n // from an agent member, such as one on the server's own transport;\n // people and services sign every call.\n const target = typeof params.workspace === \"string\" ? this.workspaces.get(params.workspace) : undefined;\n if (this.requiresSignatures(target)\n && method !== \"participant.join\" && method !== \"workspace.create\"\n && !(!isSigned(envelope) && target !== undefined\n && !this.mustSign(target, rawMember(target, params.from)?.type))) {\n const sigErr = this.verifySignature(envelope);\n if (sigErr) return reply(envelope, { error: sigErr });\n if (method === \"participant.rotate_key\") {\n // A null old_kid names no key, as a null param gives no value, and\n // the handler refuses it.\n const signingKid = (envelope.sig as string).split(\":\")[1];\n const oldKid = params.old_kid as string | null | undefined;\n if (oldKid != null && 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 // The caller learns only that the call failed. An exception's text can\n // name a path, a query or a value from another workspace, so it goes\n // to the operator through onInternalError and never onto the wire.\n this.reportInternalError(e, method, params.workspace as string | undefined);\n return reply(envelope, { error: rpcError(E.INTERNAL, \"Internal error\") });\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. A workspace.create\n // that names no workspace is recorded in the one it made, which was\n // otherwise left with no entry and never written to the store.\n const wsId = method === \"workspace.create\"\n ? (out.result as { workspace: string }).workspace\n : 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, recordedForm(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 Map() };\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 // The listeners hear of the entry once it is written, so they never hear\n // of one the store did not take.\n const queued = this.unannounced.get(ws);\n if (queued) queued.push(entry);\n else this.unannounced.set(ws, [entry]);\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 // ed25519:<kid>:<base64>, or webauthn:<kid>:<assertion> for a key a\n // browser's authenticator holds (security-signed/1.0 3).\n const parts = sig.split(\":\");\n const scheme = parts[0];\n if (parts.length !== 3 || (scheme !== \"ed25519\" && scheme !== \"webauthn\")) {\n return rpcError(E.SIG_VERIFY_FAILED, \"Malformed signature tag\");\n }\n const assertion = scheme === \"webauthn\" ? parseWebAuthnAssertion(parts[2]) : undefined;\n if (scheme === \"webauthn\" && !assertion) {\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 if (assertion) {\n if (!isWebAuthnKey(key.jwk)) return rpcError(E.SIG_VERIFY_FAILED, `Key ${kid} is not a WebAuthn key`);\n const stripped: Envelope = JSON.parse(JSON.stringify(envelope));\n delete stripped.sig;\n const failure = webAuthnFailure(canonicalize(stripped), assertion, key.jwk as unknown as Record<string, unknown>);\n return failure === null ? null : rpcError(E.SIG_VERIFY_FAILED, failure);\n }\n\n // An ed25519: tag names an Ed25519 key, and a webauthn: tag a WebAuthn\n // key, so neither key is read as the other kind.\n if (!isEd25519Key(key.jwk)) return rpcError(E.SIG_VERIFY_FAILED, `Key ${kid} is not an Ed25519 key`);\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 /**\n * SPECIFICATION 6.5: an identity profile states that a verifier checks\n * people's credentials, so advertising one this coordinator has no\n * verifier for describes a guarantee it does not give.\n */\n private unverifiedIdentity(profiles: string[]): ReturnType<typeof rpcError> | null {\n const named = (name: string) => profiles.some((x) => x === name || x.startsWith(name + \"/\"));\n if (named(\"identity-oidc\") && this.options.verifyOidcToken === undefined) {\n return rpcError(E.PARAMS,\n \"identity-oidc/1.0 is advertised but no token verifier is configured. \" +\n \"A workspace that advertises it and does not enforce it \" +\n \"describes a guarantee it does not give.\");\n }\n if (named(\"identity-vc\") && this.options.verifyVc === undefined) {\n return rpcError(E.PARAMS,\n \"identity-vc/1.0 is advertised but no presentation verifier is configured. \" +\n \"A workspace that advertises it and does not enforce it \" +\n \"describes a guarantee it does not give.\");\n }\n return null;\n }\n\n /** Whether a workspace requires signatures: it advertises security-signed/1.0, or this coordinator is configured to. */\n private requiresSignatures(ws: Workspace | undefined): boolean {\n return !!this.options.requireSignatures || (ws !== undefined && advertises(ws, \"security-signed\"));\n }\n\n /**\n * Whether a participant of this type signs its calls in a workspace that\n * requires signatures: every participant under \"all\", and every one but an\n * agent under \"humans\". A non-member signs.\n */\n private mustSign(ws: Workspace, type: string | undefined): boolean {\n return ws.signature_policy === \"all\" || type !== \"agent\";\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(\"workspace.invite\", p => this.opWorkspaceInvite(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(\"review.acknowledge\", p => this.opReviewAcknowledge(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 built = this.buildWorkspace(p);\n if (built.error) return { error: built.error };\n this.addWorkspace(built.ws);\n return { result: { workspace: built.ws.id, created: built.ws.created } };\n }\n\n /**\n * The workspace a workspace.create with these params makes, or why it\n * cannot be made. Nothing is registered, so participant.join can judge a\n * join by the workspace it would make and make it only once the join\n * passes.\n */\n private buildWorkspace(p: Record<string, unknown>):\n { ws: Workspace; error?: undefined } | { ws?: undefined; error: ReturnType<typeof rpcError> } {\n const bad = paramsError(p, [\n [\"profiles\", \"strings\"], [\"mode\", \"string\"], [\"mode_ceiling\", \"string\"],\n [\"routing_policy_uri\", \"string\"], [\"step_up_window_sec\", \"integer\"], [\"min_acr\", \"string\"],\n ]);\n if (bad) return bad;\n for (const name of [\"mode\", \"mode_ceiling\"]) {\n if (p[name] != null && !MODES.has(p[name] as string)) {\n return { error: rpcError(E.PARAMS, `${name} must be shadow, trial or production`) };\n }\n }\n const policy = p.signature_policy ?? this.options.signaturePolicy ?? \"all\";\n if (policy !== \"all\" && policy !== \"humans\") {\n return { error: rpcError(E.PARAMS, \"signature_policy must be all or humans\") };\n }\n const joinPolicy = p.join_policy ?? this.options.joinPolicy ?? \"open\";\n if (joinPolicy !== \"open\" && joinPolicy !== \"invite\") {\n return { error: rpcError(E.PARAMS, \"join_policy must be open or invite\") };\n }\n const reviewRule = p.review_rule ?? undefined;\n if (reviewRule !== undefined && (typeof reviewRule !== \"string\" || !reviewRuleSupported(reviewRule))) {\n return { error: rpcError(E.PARAMS, \"review_rule must be any_one_approves, all_approve or quorum:<n>\") };\n }\n const id = (p.workspace as string) || this.ids.workspaceId();\n if (this.workspaces.has(id)) return { error: rpcError(E.PARAMS, `workspace already exists: ${id}`) };\n if (Array.isArray(p.profiles)) {\n const unknown = profilesError(p.profiles as string[]);\n if (unknown) return unknown;\n }\n const profiles: string[] = Array.isArray(p.profiles) ? [...(p.profiles as string[])] : [...(this.options.defaultProfiles ?? [\"core/1.0\", \"review/1.0\"])];\n\n // SPECIFICATION 6.5: the descriptor and the enforcement agree. Signatures\n // are enforced wherever security-signed/1.0 is advertised, so enforcing\n // them through the option adds the profile, and advertising it needs\n // nothing configured. A token verifier cannot follow the profile, so\n // identity-oidc/1.0 advertised with none configured describes a\n // guarantee the workspace does not give, and is refused here, where the\n // misconfiguration surfaces at once.\n const signed = profiles.some(x => x === \"security-signed\" || x.startsWith(\"security-signed/\"));\n if (this.options.requireSignatures && !signed) profiles.push(\"security-signed/1.0\");\n const oidc = profiles.some(x => x === \"identity-oidc\" || x.startsWith(\"identity-oidc/\"));\n if (this.options.verifyOidcToken !== undefined && !oidc) profiles.push(\"identity-oidc/1.0\");\n const vc = profiles.some(x => x === \"identity-vc\" || x.startsWith(\"identity-vc/\"));\n if (this.options.verifyVc !== undefined && !vc) profiles.push(\"identity-vc/1.0\");\n const unverified = this.unverifiedIdentity(profiles);\n if (unverified) return { error: unverified };\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 // A param given as null gives no value, as in the Python reference: a\n // null min_acr sets no minimum.\n routing_policy_uri: (p.routing_policy_uri as string | null | undefined) ?? undefined,\n step_up_window_sec: (p.step_up_window_sec as number | null | undefined) ?? 300,\n min_acr: (p.min_acr as string | null | undefined) ?? undefined,\n signature_policy: policy,\n join_policy: joinPolicy,\n ...(reviewRule !== undefined ? { review_rule: reviewRule } : {}),\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 invitations: this.newMap(),\n idempotency_keys: {},\n audit: [],\n chain_enabled: chainEnabled,\n chain_head: chainEnabled ? ZERO_HASH : undefined,\n };\n return { ws };\n }\n\n private addWorkspace(ws: Workspace): void {\n this.workspaces.set(ws.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 }\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 signature_policy: ws.signature_policy,\n join_policy: ws.join_policy,\n review_rule: ws.review_rule ?? \"any_one_approves\",\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 if (!Array.isArray(p.profiles) || !p.profiles.every((x) => typeof x === \"string\")) {\n return { error: rpcError(E.PARAMS, \"profiles must be a list of strings\") };\n }\n const unknown = profilesError(p.profiles as string[]);\n if (unknown) return unknown;\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 // A workspace that requires signatures keeps requiring them, and one that\n // says its people are verified keeps verifying them. Removing either\n // profile would turn its checks off for every call after this one, and\n // the calls the log holds from then on would carry no assurance of who\n // sent them.\n const newProfiles = [...(p.profiles as string[])];\n for (const name of LASTING_PROFILES) {\n const held = ws.profiles.find((x) => x === name || x.startsWith(name + \"/\"));\n if (held !== undefined && !newProfiles.some((x) => x.startsWith(name + \"/\"))) {\n return { error: rpcError(E.NOT_AUTHORISED, `${held} cannot be removed once advertised`) };\n }\n }\n const unverified = this.unverifiedIdentity(newProfiles);\n if (unverified) return { error: unverified };\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 // The member is stored under its URI and read by its type, so neither\n // may be null.\n for (const f of [\"from\", \"type\"]) {\n if (typeof p[f] !== \"string\") return { error: rpcError(E.PARAMS, `${f} must be a string`) };\n }\n // SPECIFICATION 5.1: a participant is one of five types, and the scheme\n // of its URI names the type. Otherwise \"human:mallory\" could join as an\n // agent, which the \"humans\" signature policy lets call unsigned, and\n // still read as a person on the log.\n const type = p.type as string;\n const named = participantError(type, p.from as string, \"from\");\n if (named) return named;\n const bad = paramsError(p, [\n [\"role\", \"string\"], [\"display_name\", \"string\"], [\"scopes\", \"strings\"],\n [\"capabilities\", \"object\"], [\"jwks\", \"object\"], [\"jwks.keys\", \"list\"],\n [\"oidc_token\", \"string\"], [\"vc_presentation\", \"object\"],\n ]);\n if (bad) return bad;\n if (p.role === \"admin\" && !ADMIN_TYPES.includes(type)) {\n return { error: rpcError(E.PARAMS, \"The admin role is held by a human or a service\") };\n }\n // A join may make its workspace. It is judged by the workspace it would\n // make, which is registered only once the join passes, so a refused join\n // leaves nothing behind.\n let ws = this.workspaces.get(p.workspace as string);\n const made = ws === undefined;\n if (!ws) {\n const built = this.buildWorkspace({ workspace: p.workspace });\n if (built.error) return { error: built.error };\n ws = built.ws;\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 let holderVerified = false;\n let credentialBound = false;\n\n // SPECIFICATION 6.3: a newcomer joins in the role an admin's invitation\n // names, else in the role it asks for. The admin role is granted, never\n // claimed: by an invitation, or to the first member, who is the admin of\n // a workspace that admits by invitation. Taken by anyone who asked, it\n // would let an agent drop the workspace's identity profile or revoke a\n // person's key.\n const invitation = existing ? undefined : rawInvitation(ws, uri);\n const asked = typeof p.role === \"string\" && p.role !== \"\" ? p.role : undefined;\n let role = asked ?? \"participant\";\n if (!existing) {\n const first = awaitsFirstMember(ws);\n if (ws.join_policy === \"invite\" && !invitation && !(first && ADMIN_TYPES.includes(type))) {\n return { error: rpcError(E.NOT_AUTHORISED, `${uri} has no invitation to this workspace`) };\n }\n if (invitation?.role !== undefined) {\n if (asked === \"admin\" && invitation.role !== \"admin\") {\n return { error: rpcError(E.NOT_AUTHORISED, \"The admin role is granted by an admin\") };\n }\n role = invitation.role;\n } else if (first && ws.join_policy === \"invite\") {\n if (asked !== undefined && asked !== \"admin\") {\n return { error: rpcError(E.PARAMS,\n \"The first member of a workspace that admits by invitation is its admin\") };\n }\n role = \"admin\";\n } else if (asked === \"admin\" && !first) {\n return { error: rpcError(E.NOT_AUTHORISED, \"The admin role is granted by an admin\") };\n }\n }\n\n // identity-oidc/1.0 and identity-vc/1.0: where a verifier is configured\n // and the workspace advertises its profile, a person joins with the\n // credential it checks. Otherwise a workspace that says its people are\n // verified would admit one on nobody's word. Where both apply either\n // will do, since the two coexist (identity-vc/1.0 2).\n if (type === \"human\") {\n const oidc = this.options.verifyOidcToken !== undefined && advertises(ws, \"identity-oidc\");\n const vc = this.options.verifyVc !== undefined && advertises(ws, \"identity-vc\");\n const presented = (oidc && typeof p.oidc_token === \"string\") || (vc && isObject(p.vc_presentation));\n if ((oidc || vc) && !presented) {\n return { error: oidc\n ? rpcError(E.OIDC_TOKEN_INVALID, vc\n ? \"An oidc_token or a vc_presentation is required to join as a human participant\"\n : \"An oidc_token is required to join as a human participant\")\n : rpcError(E.VC_VP_INVALID, \"A vc_presentation is required to join as a human participant\") };\n }\n }\n\n const member: Member = {\n uri,\n type: type as Member[\"type\"],\n role,\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 // An invitation that names a token subject admits a join carrying a token\n // for that subject, which only a configured verifier can check.\n if (invitation?.oidc_sub !== undefined\n && (this.options.verifyOidcToken === undefined || typeof p.oidc_token !== \"string\")) {\n return { error: rpcError(E.OIDC_TOKEN_INVALID, \"An oidc_token is required: the invitation names a token subject\") };\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 (invitation?.oidc_sub !== undefined && sub !== invitation.oidc_sub) {\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token subject does not match the invitation\") };\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 } else if (type === \"human\" && boundUri !== uri && invitation?.oidc_sub === undefined) {\n // A provider vouches for its user, and only the token, or an admin's\n // invitation naming the token's subject, says which participant that\n // user is. Otherwise any user of the provider takes any free name.\n return { error: rpcError(E.OIDC_CNF_MISMATCH, \"OIDC token does not name this participant\") };\n }\n member.oidc_sub = sub;\n tokenVerified = true;\n // A NumericDate may carry a fraction; both coordinators keep whole\n // seconds, and nothing that is not a finite number.\n const at = claims.auth_time;\n if (typeof at === \"number\" && Number.isFinite(at) && Math.abs(at) <= Number.MAX_SAFE_INTEGER) member.oidc_auth_time = Math.floor(at);\n member.oidc_acr = typeof claims.acr === \"string\" ? claims.acr : undefined;\n // The token binds the key in its cnf.jwk or, with none, the key whose\n // thumbprint is its nonce: a client that cannot have the key put in the\n // token puts its thumbprint in the nonce it asks the identity provider\n // for. A join that brings another key is refused, so a token taken\n // from its holder admits no key of the taker's.\n const cnf = isObject(claims.cnf) ? claims.cnf.jwk : undefined;\n const bound = credentialKeys(cnf, cnf == null ? claims.nonce : undefined, signingKeys(p.jwks));\n if (bound === null) return { error: rpcError(E.OIDC_CNF_MISMATCH, \"The join's keys are not the key the token binds\") };\n if (bound !== undefined) {\n credentialBound = true;\n for (const j of bound) member.keys.push({ jwk: j as unknown as KeyRecord[\"jwk\"], kid: j.kid, valid_from: now });\n }\n }\n // identity-vc/1.0\n if (this.options.verifyVc && isObject(p.vc_presentation)) {\n const subject = this.options.verifyVc(p.vc_presentation);\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 holderVerified = true;\n const bound = credentialKeys(subject.cnf_jwk, undefined, signingKeys(p.jwks));\n if (bound === null) {\n return { error: rpcError(E.VC_HOLDER_BINDING_INVALID, \"The join's keys are not the key the presentation binds\") };\n }\n if (bound !== undefined) {\n credentialBound = true;\n for (const j of bound) member.keys.push({ jwk: j as unknown as KeyRecord[\"jwk\"], kid: j.kid, valid_from: now });\n }\n }\n\n // A person a credential verifies signs with a key the credential binds,\n // or one an invitation pins: keys the join asserts on its own are not\n // the person's on anyone's word.\n if (!existing && type === \"human\" && (tokenVerified || holderVerified) && !credentialBound\n && !invitation?.jwks && signingKeys(p.jwks).length > 0) {\n return { error: tokenVerified\n ? rpcError(E.OIDC_CNF_MISMATCH, \"The token binds no key: a person it verifies signs with a key it binds\")\n : rpcError(E.VC_HOLDER_BINDING_INVALID,\n \"The presentation binds no key: a person it verifies signs with a key it binds\") };\n }\n\n // An invitation that pins keys names the keys the member signs with: the\n // join's own keys, and a key an identity profile binds, are among them,\n // and the member holds the pinned keys.\n const pinned = invitation?.jwks?.keys;\n if (pinned) {\n const strays = [...signingKeys(p.jwks), ...member.keys.map((k) => k.jwk as unknown as Record<string, unknown>)]\n .filter((j) => !pinned.some((k) => sameKey(k as unknown as Record<string, unknown>, j)));\n if (strays.length) {\n return { error: rpcError(E.NOT_AUTHORISED, `${uri} joins with keys its invitation does not name`,\n { kids: [...new Set(strays.map((j) => j.kid))] }) };\n }\n member.keys = pinned.map((j) => ({ jwk: j, kid: j.kid, valid_from: now }));\n }\n\n const attested = [...member.keys];\n\n // Self-asserted JWKs are ignored for an identity-bound participant: the\n // verifier-pinned key is the signing key (proof of possession).\n if (attested.length === 0) {\n for (const j of signingKeys(p.jwks)) {\n if (!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 // A member's keys change through participant.rotate_key, which the old\n // key signs. A join under the member's name that brings only keys the\n // member does not hold, and no identity binding one, is refused: the\n // name is held by other keys, and answering it as joined would leave\n // its sender holding a key nothing here accepts.\n if (attested.length === 0) {\n const keys = signingKeys(p.jwks);\n const held = keys.some((j) => existing.keys.some((k) => sameKey(k.jwk as unknown as Record<string, unknown>, j)));\n if (keys.length > 0 && !held) {\n return { error: rpcError(E.NOT_AUTHORISED,\n `${uri} is already a member, with other keys; a new key arrives through participant.rotate_key`,\n { kids: [...new Set(keys.map((j) => j.kid))] }) };\n }\n }\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 // A participant that signs its calls joins with a key: without one it\n // would hold a name it could never sign for. The key may be its own, or\n // one an identity profile or an invitation binds.\n if (this.requiresSignatures(ws) && this.mustSign(ws, type) && member.keys.length === 0) {\n return { error: rpcError(E.PARAMS, `${uri} must sign in this workspace, and joins with no key`) };\n }\n if (made) this.addWorkspace(ws);\n ws.members.set(uri, member);\n if (invitation) ws.invitations.delete(uri);\n return { result: { joined: true, as: uri } };\n }\n\n /**\n * SPECIFICATION 6.3.3: an admin invites a participant. For a URI that is\n * not a member it records an invitation, which the invitee's join takes\n * up. For a member that holds no key in force it registers the\n * invitation's keys: the way back for a member whose keys were all revoked,\n * or who joined a workspace that requires signatures with none.\n */\n private opWorkspaceInvite(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"uri\", \"type\"]);\n if (miss) return { error: rpcError(E.PARAMS, `Missing field: ${miss}`) };\n for (const f of [\"uri\", \"type\"]) {\n if (typeof p[f] !== \"string\") return { error: rpcError(E.PARAMS, `${f} must be a string`) };\n }\n const bad = paramsError(p, [\n [\"role\", \"string\"], [\"jwks\", \"object\"], [\"jwks.keys\", \"list\"], [\"oidc_sub\", \"string\"],\n ]);\n if (bad) return bad;\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 (rawMember(ws, p.from)!.role !== \"admin\") {\n return { error: rpcError(E.NOT_AUTHORISED, \"workspace.invite requires the admin role\") };\n }\n const uri = p.uri as ParticipantUri;\n const type = p.type as string;\n const named = participantError(type, uri, \"uri\");\n if (named) return named;\n const role = typeof p.role === \"string\" && p.role !== \"\" ? p.role : undefined;\n if (role === \"admin\" && !ADMIN_TYPES.includes(type)) {\n return { error: rpcError(E.PARAMS, \"The admin role is held by a human or a service\") };\n }\n const sub = typeof p.oidc_sub === \"string\" ? p.oidc_sub : undefined;\n if (sub !== undefined && this.options.verifyOidcToken === undefined) {\n return { error: rpcError(E.PARAMS, \"oidc_sub names a token subject, and this Coordinator has no token verifier\") };\n }\n let pinned: Array<Jwk & Record<string, unknown>> | undefined;\n if (p.jwks != null) {\n pinned = signingKeys(p.jwks) as unknown as Array<Jwk & Record<string, unknown>>;\n if (pinned.length === 0) return { error: rpcError(E.PARAMS, \"jwks names no key: each key needs a kid\") };\n }\n const now = this.now();\n const member = ws.members.get(uri);\n if (member) {\n // A member's keys otherwise change through participant.rotate_key,\n // which a key it holds signs.\n if (member.keys.some((k) => inForce(k, now))) {\n return { error: rpcError(E.PARAMS,\n `${uri} is a member and holds a key in force; its keys change through participant.rotate_key`) };\n }\n if (!pinned) {\n return { error: rpcError(E.PARAMS, `${uri} is a member; an invitation for a member registers the keys its jwks names`) };\n }\n // Where a token verifier is configured, a person's key is the one their\n // token binds, and they register a new one by joining again with it.\n // Registered here, it would be a key the admin chose, and the admin\n // could revoke a person's keys and sign as them.\n if ((this.options.verifyOidcToken !== undefined && (member.type === \"human\" || member.oidc_sub !== undefined))\n || (this.options.verifyVc !== undefined && (member.type === \"human\" || member.vc_holder !== undefined))) {\n return { error: rpcError(E.PARAMS,\n `${uri} registers a new key by joining again with a token that binds it; an invitation does not register a person's keys here`) };\n }\n if ((role !== undefined && role !== member.role) || (sub !== undefined && sub !== member.oidc_sub)) {\n return { error: rpcError(E.PARAMS, `${uri} is a member; an invitation for a member registers keys and changes nothing else`) };\n }\n // A kid names one key for good: a signature naming a revoked kid is\n // refused whatever key holds it now.\n const reused = pinned.find((j) => member.keys.some((k) => k.kid === j.kid));\n if (reused) return { error: rpcError(E.PARAMS, `Key ${reused.kid} was ${uri}'s; a new key takes a new kid`) };\n for (const j of pinned) member.keys.push({ jwk: j, kid: j.kid, valid_from: now });\n return { result: { invited: true, uri, registered: pinned.map((j) => j.kid) } };\n }\n // Where a token verifier is configured, a person's keys arrive with the\n // token or presentation they join with. Pinned here, they would be keys\n // the admin chose, which a join whose token binds no key would take up,\n // and the admin could sign as the person.\n if (pinned && (type === \"human\" || sub !== undefined)\n && (this.options.verifyOidcToken !== undefined || this.options.verifyVc !== undefined)) {\n return { error: rpcError(E.PARAMS,\n `${uri} joins with a token that binds its key; an invitation does not register a person's keys here`) };\n }\n const invitation: Invitation = {\n uri, type: type as Invitation[\"type\"], invited_by: p.from as ParticipantUri, invited_at: now,\n };\n if (role !== undefined) invitation.role = role;\n if (pinned) invitation.jwks = { keys: pinned };\n if (sub !== undefined) invitation.oidc_sub = sub;\n ws.invitations.set(uri, invitation);\n return { result: { invited: true, 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 // A member that left and joined again would come back unpaused, so a\n // paused member stays until another member lifts its pause.\n if (rawMember(ws, p.from)?.paused) {\n return { error: rpcError(E.NOT_AUTHORISED, \"A paused participant does not leave until another member lifts its pause\") };\n }\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 // A param of the wrong type is refused, so both references read the same\n // task from the same call.\n const bad = paramsError(p, [\n [\"assignee\", \"string\"], [\"to\", \"string\"], [\"mode\", \"string\"], [\"review_required\", \"boolean\"],\n [\"routing_hints\", \"object\"], [\"idempotency_key\", \"string\"],\n ]);\n if (bad) return bad;\n // The keys live in a plain object, where these names belong to the\n // object itself: \"__proto__\" was never stored, so a retry made a second\n // task here and found the first in Python.\n if (RESERVED_KEYS.includes(p.idempotency_key as string)) {\n return { error: rpcError(E.PARAMS, \"idempotency_key must not be __proto__, constructor or prototype\") };\n }\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.\n const requestedMode = ((p.mode as Mode) || ws.mode);\n if (!modeLE(requestedMode, ws.mode_ceiling)) {\n return { error: rpcError(E.MODE_CEILING_EXCEEDED,\n `Requested mode ${requestedMode} exceeds ceiling ${ws.mode_ceiling}`) };\n }\n\n const taskId = this.ids.taskId();\n const now = this.now();\n const task: Task = {\n id: taskId,\n kind: p.kind as string,\n state: \"created\",\n assignee,\n delegator: p.from as ParticipantUri,\n input: p.input as Record<string, unknown>,\n created_at: now,\n updated_at: now,\n deadline: p.deadline as string | undefined,\n mode: requestedMode,\n routing_hints: p.routing_hints as Task[\"routing_hints\"],\n history: [{ ts: now, from: p.from as ParticipantUri, state: \"created\" }],\n paused: false,\n };\n\n // modes/1.0: trial mode forces review\n // modes/1.0: trial forces review, but only when the workspace opted into\n // modes/1.0. mode is inert without the profile.\n if (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && task.mode === \"trial\") task.review_required = true;\n else if (\"review_required\" in p) task.review_required = !!p.review_required;\n\n ws.tasks.set(taskId, task);\n if (typeof p.idempotency_key === \"string\") {\n ws.idempotency_keys[p.idempotency_key] = taskId;\n 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 // The state is required, and is written into the refusal below.\n if (typeof p.state !== \"string\") return { error: rpcError(E.PARAMS, \"state must be a string\") };\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, and does not complete, when one is\n // required or when the task holds a review already. task.update reaches\n // the same state by another route and carries no output, so completing\n // here would record a finished task with nothing reviewed and no decision\n // on the chain.\n if (newState === \"completed\" && reviewRequired(ws, task)) {\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 if (newState === \"completed\" && task.review) {\n return { error: rpcError(E.PARAMS,\n \"This task holds a review. Submit the output with task.complete, which opens a new round; a reviewer decision completes it.\") };\n }\n // A review once opened is decided. Its authors may take their work back\n // to revise it, and nobody else; and a task whose review no decision has\n // closed is not declined around it.\n if (task.state === \"review_requested\" && !task.review!.authors.includes(p.from as ParticipantUri)) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"Only the authors of the work under review take it back from review\") };\n }\n if (newState === \"cancelled\" && openRequiredReviewAuthors(ws, task).includes(p.from as ParticipantUri)) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"The authors of the work under review cannot end its review without a decision\") };\n }\n if (newState === \"declined\" && task.review && !task.review.decisions.some((d) => d.kind === \"reject\")) {\n return { error: rpcError(E.PARAMS,\n \"This task holds a review no decision has closed; a reviewer's decision ends it\") };\n }\n if (newState === \"declined\" && !task.review && openRequiredReviewAuthors(ws, task).length > 0) {\n return { error: rpcError(E.PARAMS,\n \"This task carries on a review no decision has closed; completing it opens the review a reviewer decides\") };\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 if (p.confidence != null && typeof p.confidence !== \"number\" && typeof p.confidence !== \"string\") {\n return { error: rpcError(E.PARAMS, \"confidence must be a number or a string\") };\n }\n // The assignee does the work a person reviews. A completion from anyone\n // else would make them an author, and an author cannot decide: routing a\n // task to a reviewer and completing it would take that reviewer off the\n // review.\n const required = reviewRequired(ws, task);\n if (required && p.from !== task.assignee) {\n return { error: rpcError(E.NOT_AUTHORISED, \"Only the assignee completes a task that requires review\") };\n }\n // review/1.0 S3.1: task.complete on a task whose review is required opens a\n // review implicitly and does not complete, and so does task.complete on a\n // task that holds a review from an earlier round. The submitted output\n // becomes the artefact under review; only a reviewer decision (decide.*)\n // then takes the task to completed. Without this a review_required task\n // would reach completed with unreviewed output and no decision, and a task\n // taken back from review with task.update would complete with none.\n if (required || task.review) {\n const now = this.now();\n // The assignee and the completer made this artefact, and neither may\n // decide it.\n const authors = authorsOf(task, p.from);\n let note = OPENED_ON_COMPLETE;\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 authors, and where there are\n // none the completion is refused: a review no person can decide would\n // never close.\n const eligible = [...rawEntries(ws.members)]\n .filter(([uri, member]) => !authors.includes(uri) && 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: ws.review_rule ?? \"any_one_approves\",\n decisions: [], authors, acknowledgements: [] };\n } else {\n // The task held a review already: it went back to in_progress through\n // task.update or a reject with request_revision, and this completion\n // submits a new artefact. A decision counts only for the artefact it\n // was made on, so the new round starts with no decisions; kept, an\n // approval of the earlier artefact would count towards the rule on\n // this one. The reviewers and the rule stay, so a revision cannot\n // weaken the review. The authors of the new artefact are left out of\n // the reviewers, and so is any member who is not a person where the\n // review is required; where nobody remains, the completion is refused.\n // The authors of the earlier rounds stay authors of this one: the work\n // is theirs as well, whoever resubmits it.\n const roundAuthors = unionOf(task.review.authors, authors);\n const reviewers = task.review.requested_to.filter((r) => !roundAuthors.includes(r)\n && !(required && rawMember(ws, r) !== undefined && rawMember(ws, r)!.type !== \"human\"));\n if (reviewers.length === 0) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"No reviewer of this task remains once the authors of the work are left out\") };\n }\n task.review = { ...task.review, requested_at: now, requested_to: reviewers, decisions: [],\n authors: roundAuthors, acknowledgements: [] };\n note = NEW_ROUND_ON_COMPLETE;\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\", note });\n return { result: { state: \"review_requested\", review_id: task.id } };\n }\n task.output = p.output;\n if (p.confidence != null) task.confidence = p.confidence as number | string;\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 // A range or filter that is not an object reads as none. Within one, a\n // field the read compares or slices by must be of its type.\n const bad = paramsError(p, [\n [\"range.from_seq\", \"integer\"], [\"range.to_seq\", \"integer\"],\n [\"filter.method\", \"string\"], [\"filter.from\", \"string\"], [\"filter.task_id\", \"string\"],\n ]);\n if (bad) return bad;\n const range = (isObject(p.range) ? p.range : {}) as { from_seq?: number; to_seq?: number };\n const filter = (isObject(p.filter) ? p.filter : {}) as {\n method?: string; from?: string; task_id?: string; outcome?: unknown;\n };\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 if (to != null && typeof to !== \"string\"\n && !(Array.isArray(to) && to.every((r) => typeof r === \"string\"))) {\n return { error: rpcError(E.PARAMS, \"to must be a string or a list of strings\") };\n }\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 bad = paramsError(p, [[\"rule\", \"string\"]]);\n if (bad) return bad;\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 const open = task.state === \"review_requested\" ? task.review : undefined;\n if (open) {\n // An artefact left out reads as null, as it does in Python and in a\n // store's copy.\n if (contentHash(task.pending_artefact ?? null) !== contentHash(p.artefact ?? null)) {\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 != null && declaredRule !== open.rule) {\n return { error: rpcError(\n E.REVIEW_ALREADY_OPEN,\n `Cannot change the decision rule of an open review (currently ${open.rule})`,\n ) };\n }\n }\n\n // Where a person's review is required, the work's authors do not choose\n // who reviews it, and the reviewers a request names, opening the review\n // or widening it, are people other than the authors, each named. Without\n // this the agent whose work a required review holds could add itself, or\n // a person it joined, or any member at all through a broadcast scope,\n // and approve its own work. An explicit review of a task that does not\n // require one keeps its own `to`, so a deliberate agent-reviews-agent\n // flow is still available.\n const authors = open ? open.authors\n : unionOf(task.review ? task.review.authors : [], authorsOf(task, lastCompleter(task)));\n if (reviewRequired(ws, task)) {\n // The review a task requires opens on task.complete, from the assignee,\n // under the workspace's rule. Opened here, by anyone, it would take an\n // artefact, a rule and reviewers its requester chose, and a requester\n // who is not an author could approve work it supplied itself, or reopen\n // a task a review already completed.\n if (!open) {\n return { error: rpcError(E.NOT_AUTHORISED,\n \"This task requires a person's review, which opens on task.complete; review.request only adds reviewers to it once it is open\") };\n }\n if (authors.includes(p.from as ParticipantUri)) {\n return { error: rpcError(E.NOT_AUTHORISED, \"The author of the work under review cannot request its review\") };\n }\n const scope = reviewers.find(isScope);\n if (scope !== undefined) {\n return { error: rpcError(E.PARAMS,\n `A review that requires a person names its reviewers, and ${scope} is an address scope`) };\n }\n for (const r of reviewers) {\n if (authors.includes(r)) {\n return { error: rpcError(E.NOT_AUTHORISED, `The author of the work under review cannot review it: ${r}`) };\n }\n const member = rawMember(ws, r);\n if (member && member.type !== \"human\") {\n return { error: rpcError(E.NOT_AUTHORISED, `This task requires a person's review: ${r} is not a human member`) };\n }\n }\n }\n\n if (open) {\n // Union, preserving order and the decisions already recorded.\n for (const r of reviewers) {\n if (!open.requested_to.includes(r)) open.requested_to.push(r);\n }\n if (p.deadline != null) open.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: [...open.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 authors,\n acknowledgements: [],\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 * review/1.0 S3.6: a reviewer says they have begun the open review. Only\n * someone who may decide it can, so the log's record of who took a review\n * up, and when, names reviewers alone. It changes nothing else: the review\n * stays open and the acknowledgement counts towards no rule.\n */\n private opReviewAcknowledge(p: Record<string, unknown>): ReturnType<Handler> {\n const miss = missing(p, [\"workspace\", \"from\", \"task_id\"]);\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(ws, task, p.from);\n if (notReviewer) return notReviewer;\n const review = task.review!;\n if (review.acknowledgements.some((a) => a.reviewer === p.from)) {\n return { error: rpcError(E.PARAMS, \"Already acknowledged in this round\") };\n }\n review.acknowledgements.push({ reviewer: p.from as ParticipantUri, ts: this.now() });\n return { result: { acknowledged: true, requested_at: review.requested_at } };\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 // A null output is no artefact, as it is in the Python reference.\n if (task.pending_artefact === undefined || task.pending_artefact === null) {\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 bad = paramsError(p, [[\"tags\", \"strings\"], [\"request_revision\", \"boolean\"]]);\n if (bad) return bad;\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(ws, 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 bad = paramsError(p, [[\"tags\", \"strings\"], [\"policy_refs\", \"strings\"]]);\n if (bad) return bad;\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(ws, 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 || base === null) 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 maxStringBytes: this.options.maxEnvelopeBytes ?? DEFAULT_MAX_ENVELOPE_BYTES,\n });\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 bad = paramsError(p, [[\"category\", \"string\"]]);\n if (bad) return bad;\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(ws, 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 bad = paramsError(p, [[\"new_task.kind\", \"string\"]]);\n if (bad) return bad;\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. The successor\n // requires review when the original did or held a review, since a review\n // once opened is decided, and a trial task forces review under modes/1.0\n // as it does at task.create.\n if (orig.review_required || orig.review !== undefined\n || (ws.profiles.some(pr => pr.startsWith(\"modes/\")) && newTask.mode === \"trial\")) {\n newTask.review_required = true;\n }\n // Whoever made the work it carries on is an author of its review too, so\n // handing the work on does not make its author a reviewer of it.\n newTask.prior_authors = successorAuthors(orig, p.from);\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 // Empty capabilities and scopes are left out, as the Python reference\n // leaves them out.\n if (m.display_name) out.display_name = m.display_name;\n if (m.capabilities && Object.keys(m.capabilities).length) out.capabilities = m.capabilities;\n if (m.scopes?.length) 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\";\nimport { confidenceOf, criticalityOf } from \"./profiles/routing.js\";\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 conf = confidenceOf(hints);\n const r = criticalityOf(hints);\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 conf = confidenceOf(hints);\n const r = criticalityOf(hints);\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 /**\n * Create the task with ``review_required``, so ``task.complete`` holds the\n * result as the artefact under review, opens a review addressed to the\n * workspace's human members other than ``caller``, and leaves the task in\n * ``review_requested`` until one of them decides. Where the workspace has\n * no such member, this throws before anything is recorded. Default false:\n * the task completes at once.\n */\n reviewRequired?: boolean;\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 *\n * Throws when the coordinator refuses a call. A refused ``task.complete``\n * leaves the task it names in progress, on the log.\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 if (options.reviewRequired) {\n const described = coord.dispatch({\n jsonrpc: \"2.0\",\n id: `wrap-${options.tool}-describe`,\n method: \"workspace.describe\",\n params: { workspace, from: options.caller },\n });\n if (described.error) throw new Error(`workspace.describe failed: ${JSON.stringify(described.error)}`);\n const members = (described.result as { members: { uri: string; type: string }[] }).members;\n if (!members.some((m) => m.type === \"human\" && m.uri !== options.caller)) {\n throw new Error(\"review_required needs a human member other than the caller to review the result; nothing was recorded\");\n }\n }\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 if (options.reviewRequired) createParams.review_required = true;\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 for ${taskId}: ${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":";AAkBA,SAAS,kBAAkB;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,IAAI;AACtD,UAAI,OAAO,SAAU,OAAO,MAAQ,OAAM,IAAI,MAAM,oBAAoB;AACxE;AAAA,IACF,WAAW,KAAK,SAAU,KAAK,OAAQ;AACrC,YAAM,IAAI,MAAM,oBAAoB;AAAA,IACtC;AAAA,EACF;AACF;AAEA,SAAS,gBAAgB,GAAmB;AAC1C,wBAAsB,CAAC;AACvB,SAAO,KAAK,UA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