{"version":3,"sources":["../src/cli.ts","../src/http-transport.ts","../src/peer-authority.ts","../src/server.ts","../src/agents-export.ts","../src/skill-tools.ts","../src/drift-context.ts","../package.json","../src/version.ts","../src/recognition-context.ts","../src/stdio.ts"],"sourcesContent":["#!/usr/bin/env node\n// SPDX-License-Identifier: BUSL-1.1\n/**\n * `bourdon-l6-server` — CLI entry point. Port of `core/l6_server.py`'s\n * `main()` / `_parse_args()` / `run_l6_server()`.\n *\n * Defaults match the Python server byte-for-byte: `--transport stdio`,\n * `--port 7500`, `--host 127.0.0.1`. A non-loopback HTTP bind without auth\n * refuses to start (non-zero exit). stdio resolves to OPERATOR.\n */\n\nimport { DEFAULT_LIBRARY_PATH, FederationRegistry, L6Store } from \"@getbourdon/federation\";\n\nimport { BindRefusedError, runHttpServer } from \"./http-transport.js\";\nimport { resolvePeerClients } from \"./peer-authority.js\";\nimport { createL6Server } from \"./server.js\";\nimport { runStdio } from \"./stdio.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\n\nconst HELP_TEXT = `Usage: bourdon-l6-server [options]\n\nOptions:\n  --library <path>          L5 agent-library path\n  --transport <stdio|http>  MCP transport (default: stdio)\n  --host <host>             HTTP bind host (default: 127.0.0.1)\n  --port <port>             HTTP bind port (default: 7500)\n  --federate                Load the default peer configuration (network enabled)\n  --peer <url>              Add a peer MCP endpoint (repeatable; network enabled)\n  --peers-config <path>     Use a peer configuration file (network enabled)\n  --no-peers                Disable peers; rejects other peer options\n  --allow-unauthenticated   Allow unauthenticated loopback HTTP\n  -h, --help                Show this help\n  --version                 Show the installed version\n`;\n\ninterface Args {\n  library: string;\n  transport: \"stdio\" | \"http\";\n  port: number;\n  host: string;\n  federate: boolean;\n  noPeers: boolean;\n  peer: string[];\n  peersConfig?: string;\n  allowUnauthenticated: boolean;\n}\n\nfunction parseArgs(argv: string[]): Args {\n  const args: Args = {\n    library: DEFAULT_LIBRARY_PATH,\n    transport: \"stdio\",\n    port: 7500,\n    host: \"127.0.0.1\",\n    federate: false,\n    noPeers: false,\n    peer: [],\n    allowUnauthenticated: false,\n  };\n  for (let i = 0; i < argv.length; i++) {\n    const a = argv[i];\n    const next = (): string => {\n      const v = argv[++i];\n      if (v === undefined) throw new Error(`missing value for ${a}`);\n      return v;\n    };\n    switch (a) {\n      case \"--library\":\n        args.library = next();\n        break;\n      case \"--transport\": {\n        const t = next();\n        if (t !== \"stdio\" && t !== \"http\") throw new Error(`invalid --transport: ${t}`);\n        args.transport = t;\n        break;\n      }\n      case \"--port\":\n        args.port = Number.parseInt(next(), 10);\n        if (!Number.isInteger(args.port) || args.port < 1 || args.port > 65_535) {\n          throw new Error(\"--port must be an integer from 1 to 65535\");\n        }\n        break;\n      case \"--host\":\n        args.host = next();\n        break;\n      case \"--federate\":\n        args.federate = true;\n        break;\n      case \"--peer\":\n        args.peer.push(next());\n        break;\n      case \"--peers-config\":\n        args.peersConfig = next();\n        break;\n      case \"--no-peers\":\n        args.noPeers = true;\n        break;\n      case \"--allow-unauthenticated\":\n        args.allowUnauthenticated = true;\n        break;\n      default:\n        throw new Error(`unknown argument: ${a}`);\n    }\n  }\n  return args;\n}\n\nasync function main(): Promise<void> {\n  const argv = process.argv.slice(2);\n  if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n    process.stdout.write(HELP_TEXT);\n    return;\n  }\n  if (argv.includes(\"--version\")) {\n    process.stdout.write(`bourdon-l6-server ${PACKAGE_VERSION}\\n`);\n    return;\n  }\n\n  const args = parseArgs(argv);\n  const peers = resolvePeerClients({\n    federate: args.federate,\n    noPeers: args.noPeers,\n    peersConfig: args.peersConfig,\n    peerUrls: args.peer,\n    clientName: \"@getbourdon/mcp-server peer\",\n    clientVersion: PACKAGE_VERSION,\n  });\n  const store = new L6Store(args.library, peers);\n  const registry = new FederationRegistry();\n\n  process.stderr.write(\n    `Bourdon L6 server starting — library=${args.library}, transport=${args.transport}, peers=${peers.length}\\n`,\n  );\n\n  if (args.transport === \"stdio\") {\n    await runStdio(createL6Server(store, { registry }));\n    return;\n  }\n  runHttpServer(() => createL6Server(store, { registry }), {\n    port: args.port,\n    host: args.host,\n    allowUnauthenticated: args.allowUnauthenticated,\n    registry,\n  });\n}\n\nmain().catch((exc) => {\n  if (exc instanceof BindRefusedError) {\n    process.stderr.write(`${exc.message}\\n`);\n    process.exit(1);\n  }\n  const message = exc instanceof Error ? exc.message : String(exc);\n  process.stderr.write(`fatal: ${message}\\n`);\n  process.exit(1);\n});\n","// SPDX-License-Identifier: BUSL-1.1\n/**\n * HTTP (streamable-HTTP) transport + Bearer auth — port of the HTTP half of\n * `core/l6_server.py` (`_build_auth_middleware`, `_build_operator_identity_middleware`,\n * the `run_l6_server` http branch, `_is_loopback_host`, `_normalized_legacy_token`).\n *\n * Security invariants preserved IN CODE (a miss here leaks PRIVATE memory or\n * escalates a quarantined caller to OPERATOR across machines):\n *  - Fail CLOSED: with no auth configured and not `--allow-unauthenticated`,\n *    every request gets 503.\n *  - Empty Bearer can NEVER authenticate as OPERATOR — the legacy compare\n *    requires BOTH a configured legacy token AND a non-empty presented token\n *    before the constant-time compare, and `normalizedLegacyToken()` maps a\n *    set-but-empty/whitespace `BOURDON_PEER_TOKEN_SERVER` to null (3-Star P1-1).\n *  - Per-agent `bdn_` tokens resolve via the registry (sha256-at-rest,\n *    constant-time; re-reads on mtime so `bourdon revoke` takes effect live).\n *  - A 401 does NOT distinguish invalid vs revoked and never echoes the token.\n *  - Default bind 127.0.0.1; a NON-LOOPBACK bind REFUSES TO START (throws, the\n *    CLI exits non-zero) with `--allow-unauthenticated` (anonymous = loopback\n *    only) OR with no auth configured.\n *  - On success the identity is bound for the request subtree via\n *    AsyncLocalStorage (`runWithCaller`), so the tool handlers observe the\n *    authenticated caller deterministically; an HTTP request that bypassed this\n *    middleware would resolve to OPERATOR only under stdio, never here.\n */\n\nimport { timingSafeEqual } from \"node:crypto\";\nimport {\n  createServer as createHttpServer,\n  type IncomingMessage,\n  type ServerResponse,\n} from \"node:http\";\n\nimport {\n  AgentIdentity,\n  FederationRegistry,\n  HandoffGovernance,\n  OPERATOR,\n  TIER_TRUSTED,\n  runWithCaller,\n} from \"@getbourdon/federation\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\n\nexport const DEFAULT_PORT = 7500;\nexport const DEFAULT_HOST = \"127.0.0.1\";\nconst MAX_REQUEST_BODY_BYTES = 8 * 1024 * 1024;\nconst LEGACY_PEER = new AgentIdentity(\"legacy-peer\", TIER_TRUSTED);\n\n/**\n * The legacy shared peer token, with empty/whitespace normalized to null. A\n * set-but-empty `BOURDON_PEER_TOKEN_SERVER` (a routine .env slip) is treated as\n * \"no token\" everywhere — both the startup gate and per-request auth (P1-1).\n */\nexport function normalizedLegacyToken(): string | null {\n  const value = process.env.BOURDON_PEER_TOKEN_SERVER;\n  if (value !== undefined && value.trim() === \"\") return null;\n  return value ?? null;\n}\n\n/** Constant-time string compare (mirrors Python `hmac.compare_digest`): false,\n * not throw, on a length mismatch; no early exit on equal length. */\nfunction constantTimeStringEqual(a: string, b: string): boolean {\n  const ba = Buffer.from(a, \"utf8\");\n  const bb = Buffer.from(b, \"utf8\");\n  if (ba.length !== bb.length) return false;\n  return timingSafeEqual(ba, bb);\n}\n\n/** Whether a bind host is loopback-only. */\nexport function isLoopbackHost(host: string): boolean {\n  if (host === \"localhost\") return true;\n  // IPv4 loopback 127.0.0.0/8.\n  if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) return true;\n  // IPv6 loopback ::1 (with optional brackets).\n  const stripped = host.replace(/^\\[/, \"\").replace(/\\]$/, \"\");\n  if (stripped === \"::1\" || stripped === \"0:0:0:0:0:0:0:1\") return true;\n  return false;\n}\n\nexport type AuthResult =\n  | { kind: \"unconfigured\" } // 503\n  | { kind: \"unauthorized\"; message: string } // 401\n  | { kind: \"ok\"; identity: AgentIdentity };\n\n/**\n * Resolve an `Authorization` header to an identity, reproducing the\n * `_BearerAuth.dispatch` decision exactly.\n */\nexport function authenticateBearer(\n  registry: FederationRegistry,\n  legacy: string | null,\n  authHeader: string | null | undefined,\n): AuthResult {\n  if (legacy === null && !registry.isConfigured()) {\n    return { kind: \"unconfigured\" };\n  }\n  const header = authHeader ?? \"\";\n  if (!header.toLowerCase().startsWith(\"bearer \")) {\n    return { kind: \"unauthorized\", message: \"missing Bearer token\" };\n  }\n  // header.split(\" \", 1)[1].strip() — everything after the first space, trimmed.\n  const token = header.slice(header.indexOf(\" \") + 1).trim();\n  let identity: AgentIdentity | null = null;\n  // Require BOTH a configured legacy token and a non-empty presented token\n  // before the constant-time compare, so an empty Bearer can never match.\n  if (legacy && token && constantTimeStringEqual(token, legacy)) {\n    identity = LEGACY_PEER;\n  }\n  if (identity === null) {\n    identity = registry.authenticate(token);\n  }\n  if (identity === null) {\n    // Deliberately does not distinguish invalid vs revoked; never echoes the token.\n    return { kind: \"unauthorized\", message: \"invalid or revoked Bearer token\" };\n  }\n  return { kind: \"ok\", identity };\n}\n\n/** Error thrown when a non-loopback bind is refused. The CLI catches it and\n * exits non-zero (mirrors Python's `raise SystemExit`). */\nexport class BindRefusedError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"BindRefusedError\";\n  }\n}\n\nexport interface RunHttpServerOptions {\n  port?: number;\n  host?: string;\n  allowUnauthenticated?: boolean;\n  registry?: FederationRegistry;\n  governance?: HandoffGovernance;\n}\n\nclass RequestBodyTooLargeError extends Error {\n  constructor() {\n    super(`request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes`);\n  }\n}\n\n/** Internal transport boundary; not exported by the package facade. */\nexport function readBody(req: IncomingMessage): Promise<unknown> {\n  return new Promise((resolve, reject) => {\n    const chunks: Buffer[] = [];\n    let receivedBytes = 0;\n    let settled = false;\n\n    function finish(error?: Error, value?: unknown): void {\n      if (settled) return;\n      settled = true;\n      chunks.length = 0;\n      req.off(\"data\", onData);\n      req.off(\"end\", onEnd);\n      req.off(\"aborted\", onAborted);\n      // An aborted IncomingMessage emits error before close. Keep its error\n      // handler until close even after the body promise has already rejected.\n      if (error) reject(error);\n      else resolve(value);\n    }\n\n    function onData(chunk: Buffer): void {\n      if (chunk.length > MAX_REQUEST_BODY_BYTES - receivedBytes) {\n        req.pause();\n        finish(new RequestBodyTooLargeError());\n        return;\n      }\n      receivedBytes += chunk.length;\n      chunks.push(chunk);\n    }\n\n    function onEnd(): void {\n      const raw = Buffer.concat(chunks).toString(\"utf8\");\n      try {\n        finish(undefined, raw ? JSON.parse(raw) : undefined);\n      } catch {\n        finish();\n      }\n    }\n\n    function onAborted(): void {\n      finish(new Error(\"request body interrupted\"));\n    }\n\n    function onError(): void {\n      onAborted();\n    }\n\n    function onClose(): void {\n      onAborted();\n      req.off(\"error\", onError);\n      req.off(\"close\", onClose);\n    }\n\n    req.on(\"data\", onData);\n    req.on(\"end\", onEnd);\n    req.on(\"aborted\", onAborted);\n    req.on(\"error\", onError);\n    req.on(\"close\", onClose);\n\n    const declaredBytes = req.headers[\"content-length\"];\n    if (\n      declaredBytes &&\n      /^\\d+$/.test(declaredBytes) &&\n      Number(declaredBytes) > MAX_REQUEST_BODY_BYTES\n    ) {\n      req.pause();\n      finish(new RequestBodyTooLargeError());\n    }\n  });\n}\n\nfunction sendJson(res: ServerResponse, status: number, payload: unknown): void {\n  const body = JSON.stringify(payload);\n  res.writeHead(status, { \"content-type\": \"application/json\" });\n  res.end(body);\n}\n\n/** Normalize only own HTTP headers; duplicate provenance can never choose a winner. */\nfunction governanceHeaders(req: IncomingMessage): Record<string, string | undefined> {\n  const headers: Record<string, string | undefined> = Object.create(null);\n  for (const [name, value] of Object.entries(req.headers)) {\n    const normalized = name.toLowerCase();\n    headers[normalized] = Object.hasOwn(headers, normalized) || Array.isArray(value) ? \"\" : value;\n  }\n  // Node joins ordinary duplicate headers. Count their original field names:\n  // permissive token decoding must not turn a joined value into a valid handoff.\n  const seen = new Set<string>();\n  for (let index = 0; index < req.rawHeaders.length; index += 2) {\n    const name = req.rawHeaders[index]!.toLowerCase();\n    if (seen.has(name)) headers[name] = \"\";\n    seen.add(name);\n  }\n  return headers;\n}\n\n/**\n * Serve the L6 MCP server over STATELESS streamable-HTTP, always via our own\n * `node:http` server so the bind host is ours. Each request runs in its own\n * task with a fresh transport, so the bound caller identity deterministically\n * reaches the tool handlers.\n *\n * `createServer` is a factory so each request gets a fresh `McpServer`/transport\n * pair (stateless = no cross-request session state). The returned handler is\n * also used by `runHttpServer`; this module-only seam does not bypass startup gates.\n *\n * v0.9.0 bind/auth contract: default bind 127.0.0.1; a non-loopback bind with\n * `--allow-unauthenticated` (anonymous is loopback-only) OR with no auth\n * configured throws `BindRefusedError` BEFORE listening (never serves-then-503).\n */\nexport function createHttpRequestHandler(\n  createServer: () => McpServer,\n  options: RunHttpServerOptions = {},\n): (req: IncomingMessage, res: ServerResponse) => Promise<void> {\n  const host = options.host ?? DEFAULT_HOST;\n  const allowUnauthenticated = options.allowUnauthenticated ?? false;\n  const registry = options.registry ?? new FederationRegistry();\n  const legacy = normalizedLegacyToken();\n  const governance = options.governance ?? new HandoffGovernance();\n  const authConfigured = legacy !== null || registry.hasActiveAgents();\n\n  if (!isLoopbackHost(host)) {\n    if (allowUnauthenticated) {\n      throw new BindRefusedError(\n        `refusing to start: --allow-unauthenticated with non-loopback bind '${host}'. ` +\n          \"Anonymous access is loopback-only; register an agent token \" +\n          \"(`bourdon agent add <id>`) or set BOURDON_PEER_TOKEN_SERVER to serve on this interface.\",\n      );\n    }\n    if (!authConfigured) {\n      throw new BindRefusedError(\n        `refusing to start: bind '${host}' is network-reachable but no auth is configured. ` +\n          \"Register an agent token (`bourdon agent add <id>`) or set \" +\n          \"BOURDON_PEER_TOKEN_SERVER, or bind 127.0.0.1.\",\n      );\n    }\n  }\n\n  const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n    // Resolve the caller identity for this request.\n    let identity: AgentIdentity;\n    if (allowUnauthenticated) {\n      // Loopback-only operator-identity binding (matches stdio behavior).\n      identity = OPERATOR;\n    } else {\n      const auth = authenticateBearer(registry, legacy, req.headers.authorization ?? null);\n      if (auth.kind === \"unconfigured\") {\n        sendJson(res, 503, {\n          error:\n            \"Server has no auth configured (no registered agents via `bourdon agent add` \" +\n            \"and no BOURDON_PEER_TOKEN_SERVER) and was launched without --allow-unauthenticated.\",\n        });\n        return;\n      }\n      if (auth.kind === \"unauthorized\") {\n        sendJson(res, 401, { error: auth.message });\n        return;\n      }\n      identity = auth.identity;\n    }\n\n    const binding = governance.apply(identity, governanceHeaders(req));\n    if (binding.error !== null) {\n      console.warn(`handoff rejected (${binding.error}); caller quarantined for this request`);\n    }\n    identity = binding.identity;\n\n    let body: unknown;\n    try {\n      body = await readBody(req);\n    } catch (error) {\n      if (error instanceof RequestBodyTooLargeError) {\n        // Finish the response before closing, so the caller receives 413 even\n        // when it has not finished uploading a declared or chunked body.\n        res.shouldKeepAlive = false;\n        sendJson(res, 413, { error: error.message });\n        return;\n      }\n      throw error;\n    }\n    const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });\n    const server = createServer();\n    res.on(\"close\", () => {\n      void transport.close();\n      void server.close();\n    });\n    await server.connect(transport);\n    // Bind identity for the whole request subtree so the tool handlers see the\n    // authenticated caller (AsyncLocalStorage = the contextvar analogue).\n    await runWithCaller(identity, () => transport.handleRequest(req, res, body));\n  };\n\n  return handle;\n}\n\n/** Start the same authenticated request handler exposed for in-process integration. */\nexport function runHttpServer(\n  createServer: () => McpServer,\n  options: RunHttpServerOptions = {},\n): import(\"node:http\").Server {\n  const handle = createHttpRequestHandler(createServer, options);\n  const port = options.port ?? DEFAULT_PORT;\n  const host = options.host ?? DEFAULT_HOST;\n  const httpServer = createHttpServer((req, res) => {\n    handle(req, res).catch(() => {\n      if (!res.headersSent && !res.destroyed) sendJson(res, 500, { error: \"request failed\" });\n    });\n  });\n  httpServer.listen(port, host);\n  return httpServer;\n}\n","// SPDX-License-Identifier: BUSL-1.1\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { RemoteL6Client, type PeerTransport } from \"@getbourdon/federation\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { parse as yamlParse } from \"yaml\";\n\nimport { isLoopbackHost } from \"./http-transport.js\";\n\ntype Dict = Record<string, unknown>;\n\nconst PEER_TOKEN_ENV_PATTERN = /^BOURDON_PEER_[A-Z0-9_]+$/;\n\nexport const DEFAULT_PEERS_CONFIG = join(homedir(), \".bourdon\", \"peers.yaml\");\n\nexport class PeerAuthorityError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"PeerAuthorityError\";\n  }\n}\n\nexport interface PeerAuthorityOptions {\n  federate: boolean;\n  noPeers: boolean;\n  peersConfig?: string;\n  peerUrls: readonly string[];\n  clientName: string;\n  clientVersion: string;\n  defaultPeersConfig?: string;\n}\n\nfunction sdkPeerTransport(clientName: string, clientVersion: string): PeerTransport {\n  return {\n    async callTool(toolName, toolArgs, opts) {\n      const timeoutMs = opts.timeout * 1000;\n      if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n        throw new RangeError(\n          \"peer timeout must be positive whole milliseconds within the timer limit\",\n        );\n      }\n      const controller = new AbortController();\n      const fetches = new Map<AbortController, () => void>();\n      const deadline = performance.now() + timeoutMs;\n      const transport = new StreamableHTTPClientTransport(new URL(opts.url), {\n        requestInit: { headers: opts.headers as Record<string, string> },\n        fetch: async (input, init) => {\n          // Each request owns its SDK bridge so operation cleanup can abort it\n          // directly even if SDK close never settles.\n          controller.signal.throwIfAborted();\n          const requestController = new AbortController();\n          const sdkSignal =\n            init?.signal !== undefined\n              ? init.signal\n              : input instanceof Request\n                ? input.signal\n                : undefined;\n          const dispose = (): void => {\n            sdkSignal?.removeEventListener(\"abort\", abortFromSdk);\n            fetches.delete(requestController);\n          };\n          const abortFromSdk = (): void => {\n            requestController.abort(sdkSignal?.reason);\n            dispose();\n          };\n          fetches.set(requestController, dispose);\n          sdkSignal?.addEventListener(\"abort\", abortFromSdk, { once: true });\n          if (sdkSignal?.aborted) abortFromSdk();\n          try {\n            requestController.signal.throwIfAborted();\n            const pending = fetch(input, { ...init, signal: requestController.signal }).then(\n              (response) => {\n                if (requestController.signal.aborted) {\n                  try {\n                    void response.body?.cancel().catch(() => {});\n                  } catch {\n                    /* late body cleanup */\n                  }\n                  throw requestController.signal.reason;\n                }\n                // Keep bridges through the body lifetime; the enclosing operation\n                // owns final disposal because headers do not mean the body is done.\n                if (!response.body) dispose();\n                return response;\n              },\n            );\n            return await awaitPeerOperation(pending, requestController.signal);\n          } catch (error) {\n            dispose();\n            throw error;\n          }\n        },\n      });\n      const client = new Client({ name: clientName, version: clientVersion }, { capabilities: {} });\n      const cleanup = (): void => {\n        clearTimeout(timer);\n        controller.signal.removeEventListener(\"abort\", cleanup);\n        for (const [requestController, dispose] of fetches) {\n          requestController.abort(controller.signal.reason);\n          dispose();\n        }\n        closePeerResources(client, transport);\n      };\n      const expire = (): void => {\n        controller.abort(new DOMException(\"peer operation deadline exceeded\", \"TimeoutError\"));\n      };\n      const timer = setTimeout(expire, timeoutMs);\n      controller.signal.addEventListener(\"abort\", cleanup);\n      const remainingBudget = (): number => {\n        const remaining = Math.ceil(deadline - performance.now());\n        if (remaining <= 0) expire();\n        controller.signal.throwIfAborted();\n        return remaining;\n      };\n      const requestOptions = () => {\n        const remaining = remainingBudget();\n        return {\n          signal: controller.signal,\n          timeout: remaining,\n          maxTotalTimeout: remaining,\n          resetTimeoutOnProgress: false,\n        };\n      };\n      try {\n        const connecting = client.connect(transport, requestOptions());\n        // connect() may allocate SDK resources after the first cleanup attempt.\n        void connecting.then(\n          () => {\n            if (controller.signal.aborted) closePeerResources(client, transport);\n          },\n          () => {\n            if (controller.signal.aborted) closePeerResources(client, transport);\n          },\n        );\n        await awaitPeerOperation(connecting, controller.signal);\n        const result = await awaitPeerOperation(\n          client.callTool({ name: toolName, arguments: toolArgs }, undefined, requestOptions()),\n          controller.signal,\n        );\n        remainingBudget();\n        const content = (result as { content?: unknown }).content;\n        if (!Array.isArray(content)) return null;\n        for (const item of content) {\n          if (\n            item !== null &&\n            typeof item === \"object\" &&\n            (item as { type?: unknown }).type === \"text\" &&\n            typeof (item as { text?: unknown }).text === \"string\"\n          ) {\n            const parsed: unknown = JSON.parse((item as { text: string }).text);\n            remainingBudget();\n            return parsed;\n          }\n        }\n        return null;\n      } finally {\n        if (!controller.signal.aborted) controller.abort();\n      }\n    },\n  };\n}\n\nfunction closePeerResources(client: Client, transport: StreamableHTTPClientTransport): void {\n  for (const resource of [client, transport]) {\n    try {\n      void resource.close().catch(() => {});\n    } catch {\n      /* cleanup must not delay or mask the result */\n    }\n  }\n}\n\nfunction awaitPeerOperation<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n  return new Promise<T>((resolve, reject) => {\n    const onAbort = (): void => {\n      signal.removeEventListener(\"abort\", onAbort);\n      reject(signal.reason);\n    };\n    signal.addEventListener(\"abort\", onAbort, { once: true });\n    pending.then(\n      (value) => {\n        signal.removeEventListener(\"abort\", onAbort);\n        resolve(value);\n      },\n      (error: unknown) => {\n        signal.removeEventListener(\"abort\", onAbort);\n        reject(error);\n      },\n    );\n    if (signal.aborted) onAbort();\n  });\n}\n\nfunction normalizedPeerUrl(value: unknown, source: string): string {\n  if (typeof value !== \"string\" || value.trim() === \"\") {\n    throw new PeerAuthorityError(`${source} must be a non-empty URL`);\n  }\n\n  let parsed: URL;\n  try {\n    parsed = new URL(value.trim());\n  } catch {\n    throw new PeerAuthorityError(`${source} is not a valid URL`);\n  }\n  if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n    throw new PeerAuthorityError(`${source} must use http or https`);\n  }\n  if (parsed.username || parsed.password) {\n    throw new PeerAuthorityError(`${source} must not contain user information`);\n  }\n  if (parsed.search || parsed.hash) {\n    throw new PeerAuthorityError(`${source} must not contain a query or fragment`);\n  }\n  if (parsed.protocol === \"http:\" && !isLoopbackHost(parsed.hostname)) {\n    throw new PeerAuthorityError(`${source} must use https for a non-loopback host`);\n  }\n  return parsed.toString();\n}\n\nfunction tokenEnvironment(value: unknown, source: string): string {\n  if (value === undefined || value === null || value === \"\") return \"BOURDON_PEER_TOKEN\";\n  if (typeof value !== \"string\" || !PEER_TOKEN_ENV_PATTERN.test(value)) {\n    throw new PeerAuthorityError(`${source} must match BOURDON_PEER_*`);\n  }\n  return value;\n}\n\nfunction configEntries(path: string): Dict[] {\n  if (!existsSync(path)) {\n    throw new PeerAuthorityError(`peer configuration file not found: ${path}`);\n  }\n\n  let contents: string;\n  try {\n    contents = readFileSync(path, \"utf8\");\n  } catch {\n    throw new PeerAuthorityError(`peer configuration file could not be read: ${path}`);\n  }\n\n  let parsed: unknown;\n  try {\n    parsed = yamlParse(contents) as unknown;\n  } catch {\n    throw new PeerAuthorityError(`peer configuration file is not valid YAML: ${path}`);\n  }\n  if (parsed === null || parsed === undefined) return [];\n  if (typeof parsed !== \"object\" || Array.isArray(parsed)) {\n    throw new PeerAuthorityError(`peer configuration must be a mapping: ${path}`);\n  }\n\n  const peers = (parsed as Dict).peers;\n  if (peers === undefined || peers === null) return [];\n  if (!Array.isArray(peers)) {\n    throw new PeerAuthorityError(`peer configuration 'peers' must be a list: ${path}`);\n  }\n\n  const entries: Dict[] = [];\n  for (let index = 0; index < peers.length; index++) {\n    const entry = peers[index];\n    if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) {\n      throw new PeerAuthorityError(`peer configuration entry ${index + 1} must be a mapping`);\n    }\n    entries.push(entry as Dict);\n  }\n  return entries;\n}\n\nexport function resolvePeerClients(\n  options: PeerAuthorityOptions,\n  transport?: PeerTransport,\n): RemoteL6Client[] {\n  const explicitConfig = options.peersConfig !== undefined;\n  const explicitPeers = options.peerUrls.length > 0;\n  const networkRequested = options.federate || explicitConfig || explicitPeers;\n\n  if (options.noPeers && networkRequested) {\n    throw new PeerAuthorityError(\n      \"--no-peers cannot be combined with --federate, --peer, or --peers-config\",\n    );\n  }\n  if (options.noPeers || !networkRequested) return [];\n\n  const resolvedTransport =\n    transport ?? sdkPeerTransport(options.clientName, options.clientVersion);\n  const clients: RemoteL6Client[] = [];\n  const seenUrls = new Set<string>();\n  const addPeer = (\n    urlValue: unknown,\n    nameValue: unknown,\n    tokenEnvValue: unknown,\n    source: string,\n  ): void => {\n    const url = normalizedPeerUrl(urlValue, source);\n    if (seenUrls.has(url)) return;\n    if (nameValue !== undefined && (typeof nameValue !== \"string\" || nameValue.trim() === \"\")) {\n      throw new PeerAuthorityError(`${source} name must be a non-empty string`);\n    }\n    const name = typeof nameValue === \"string\" ? nameValue.trim() : url;\n    const tokenEnv = tokenEnvironment(tokenEnvValue, `${source} token_env`);\n    seenUrls.add(url);\n    clients.push(new RemoteL6Client({ url, name, tokenEnv, transport: resolvedTransport }));\n  };\n\n  const configPath = explicitConfig\n    ? options.peersConfig\n    : options.federate\n      ? (options.defaultPeersConfig ?? DEFAULT_PEERS_CONFIG)\n      : undefined;\n  if (configPath !== undefined) {\n    if (configPath.trim() === \"\") {\n      throw new PeerAuthorityError(\"--peers-config requires a non-empty path\");\n    }\n    const entries = configEntries(configPath);\n    for (let index = 0; index < entries.length; index++) {\n      const entry = entries[index] as Dict;\n      addPeer(entry.url, entry.name, entry.token_env, `peer configuration entry ${index + 1}`);\n    }\n  }\n\n  for (let index = 0; index < options.peerUrls.length; index++) {\n    addPeer(options.peerUrls[index], undefined, undefined, `--peer value ${index + 1}`);\n  }\n  return clients;\n}\n","// SPDX-License-Identifier: BUSL-1.1\n/**\n * Bourdon L6 — MCP server (faithful port of `core/l6_server.py`).\n *\n * Wraps `@getbourdon/federation`'s `L6Store` in an `@modelcontextprotocol/sdk`\n * `McpServer` so any MCP-aware agent (Claude Code, Codex, Cursor) can query the\n * federation natively. Registers the SAME tools + 3 resources as the Python\n * server, with byte-identical names, arg names, and defaults (the public/team\n * `access_level` split is reproduced exactly).\n *\n * WIRE ENCODING — the single highest-risk port detail: every tool handler\n * returns `{ content: [{ type: \"text\", text: JSON.stringify(payload) }] }`, NOT\n * the SDK's default structured content. The Python `RemoteL6Client` (and\n * `@getbourdon/client`) recover the payload with `json.loads(item.text)` /\n * `JSON.parse(text)`. Returning structured content instead makes a Python peer's\n * `json.loads(item.text)` get `None` and silently breaks mixed-language\n * federation. Each tool closure builds a plain object; `jsonContent` stringifies\n * it onto the wire.\n *\n * Caller identity arrives via the AsyncLocalStorage binding (`getCaller()` from\n * `@getbourdon/federation`): the HTTP auth middleware binds the resolved\n * identity for the request subtree; stdio has no binding and resolves to\n * OPERATOR (trusted) — exactly v0.8.0 behavior. Quarantined callers get an\n * allowlisted read surface (granted namespaces) and STAGED writes; every call is\n * audited, allow and deny alike.\n */\n\nimport {\n  type AgentIdentity,\n  type CommitConflict,\n  type CommitL5Options,\n  type EntityMatch,\n  type RollbackL5Options,\n  type WorkstreamMatch,\n  FederationAudit,\n  FederationRegistry,\n  CommitConflictError,\n  L6Store,\n  MAX_REPORTED_CONFLICTS,\n  ON_CONFLICT_MODES,\n  OPERATOR,\n  ReadOnlyMemoryError,\n  StaleWriteError,\n  authorizedAccess,\n  describeMember,\n  enforceToolAccess,\n  quarantineMayCall,\n  explainDigest,\n  exportEgressAccess,\n  getCaller,\n  mergeIntoStaged,\n  requireBoundedCommitRows,\n  namespaceAcceptsWrites,\n  requireBoundedCommitPayload,\n  entityTraceToDict,\n  ingestMeeting,\n  traceEntity,\n  CONSENSUS_STRATEGIES,\n  ConsensusEngine,\n  ProposalNotFoundError,\n  ZeroDepVectorEngine,\n  defaultClipsDir,\n  getClipper,\n  proposalToDict,\n  searchResultToDict,\n} from \"@getbourdon/federation\";\nimport {\n  briefPath,\n  compileTurn,\n  universalTurnBriefToDict,\n} from \"@getbourdon/inference\";\nimport { supersessionDiagnostics, validateManifest } from \"@getbourdon/l5\";\nimport {\n  LIST_ALL,\n  LIST_OFF,\n  PROPOSER_QUARANTINED,\n  PROPOSER_TRUSTED,\n  SKILLS_ADVERTISE_ENV,\n  STATUS_PENDING,\n  SkillContentError,\n  SkillIndexError,\n  type SkillSource,\n  computeContentSha256,\n  createProposal,\n  listProposals,\n  openAdvisoryBallot,\n  proposalSummary,\n  readSkillFolder,\n  resolveAdvertisedFolder,\n  skillSourcesForAgent,\n  skillsListingMode,\n  validateSkillName,\n} from \"@getbourdon/participants\";\nimport { McpServer, ResourceTemplate } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { CallToolResult, ReadResourceResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { realpathSync } from \"node:fs\";\nimport { isAbsolute, join as pathJoin, relative, resolve as pathResolve, sep } from \"node:path\";\nimport { z } from \"zod\";\n\nimport { exportLocalAgents, resolveLocalName } from \"./agents-export.js\";\nimport { getSkillPayload, listSkillsPayload } from \"./skill-tools.js\";\nimport { driftingSurfaces } from \"./drift-context.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\nimport {\n  compileCodexTurnFromStore,\n  getDeeperContextForPrompt,\n  prepareRecognitionContextFromStore,\n} from \"./recognition-context.js\";\n\nconst DECISION_ALLOW = \"allow\";\nconst DECISION_DENY = \"deny\";\n\ntype Dict = Record<string, unknown>;\n\n/** Build the JSON-in-TextContent envelope (the wire contract). */\nfunction jsonContent(payload: unknown): CallToolResult {\n  return { content: [{ type: \"text\" as const, text: JSON.stringify(payload) }] };\n}\n\n/** Python `os.strerror` text for the errno codes a disk write commonly raises. */\nconst OS_ERROR_TEXT: Readonly<Record<string, string>> = {\n  EACCES: \"Permission denied\",\n  EBUSY: \"Device or resource busy\",\n  EDQUOT: \"Disk quota exceeded\",\n  EEXIST: \"File exists\",\n  EIO: \"Input/output error\",\n  EISDIR: \"Is a directory\",\n  EMFILE: \"Too many open files\",\n  ENAMETOOLONG: \"File name too long\",\n  ENOENT: \"No such file or directory\",\n  ENOSPC: \"No space left on device\",\n  ENOTDIR: \"Not a directory\",\n  ENOTEMPTY: \"Directory not empty\",\n  EPERM: \"Operation not permitted\",\n  EROFS: \"Read-only file system\",\n};\n\n/** A filesystem error from Node (the oracle's `OSError`): an `E...` errno code. */\nfunction isOsError(exc: unknown): exc is NodeJS.ErrnoException & { code: string } {\n  if (!(exc instanceof Error)) return false;\n  const code = (exc as NodeJS.ErrnoException).code;\n  return typeof code === \"string\" && /^E[A-Z0-9]+$/.test(code);\n}\n\n/**\n * A filesystem error's reason without the file it names: Node's message reads\n * `ENOSPC: no space left on device, open '<path>'`, and the path names the\n * host's home directory and account to a remote caller. The oracle's\n * `_os_error_detail` (`exc.strerror`).\n */\nfunction osErrorDetail(exc: NodeJS.ErrnoException & { code: string }): string {\n  const known = OS_ERROR_TEXT[exc.code];\n  if (known !== undefined) return known;\n  const prefix = `${exc.code}: `;\n  if (exc.message.startsWith(prefix)) {\n    const reason = exc.message.slice(prefix.length).split(\",\")[0]!.trim();\n    if (reason) return reason.charAt(0).toUpperCase() + reason.slice(1);\n  }\n  return exc.code;\n}\n\n/** Response fields that carry a filesystem path; see `libraryRelative`. */\nconst PATH_FIELDS: ReadonlySet<string> = new Set([\"path\", \"generated_from\"]);\n\n/** Build the JSON-in-text resource envelope. */\nfunction jsonResource(uri: string, payload: unknown): ReadResourceResult {\n  return {\n    contents: [{ uri, mimeType: \"application/json\", text: JSON.stringify(payload) }],\n  };\n}\n\n/** Python `repr()` of a simple string: single-quoted. Agent ids / namespaces\n * are `^[a-z0-9][a-z0-9_-]*$`, so no escaping is needed. */\nfunction pyRepr(s: string): string {\n  return `'${s}'`;\n}\n\nexport interface CreateL6ServerOptions {\n  name?: string;\n  registry?: FederationRegistry;\n  audit?: FederationAudit;\n  /**\n   * Explicit canonical HTTPS MCP resource for caller descriptions (Python's\n   * `caller_audience`). Must match the enrolled library identity. Left unset,\n   * `describe_caller` reports `not_configured` rather than guessing.\n   */\n  callerAudience?: string | null;\n  /**\n   * `agentId -> SkillSource[] | null`: where an agent's skill reader looks,\n   * used by `propose_skill` to find the folder an advertised skill was read\n   * from. Defaults to the built-in readers' directories\n   * (`skillSourcesForAgent` in `@getbourdon/participants`).\n   */\n  skillSources?: (agentId: string) => readonly SkillSource[] | null;\n}\n\n/**\n * Build an `McpServer` exposing the L6 resources + tools over `store`. Mirrors\n * `create_l6_server(store, name=\"bourdon-l6\", registry=None, audit=None,\n * auth_provider=None, caller_audience=None)`.\n */\n// Tool annotations (MCP ToolAnnotations), the same three sets as the oracle's\n// core/l6_server.py. Every tool declares which it is, so a client can tell a\n// read from a write before it calls and a directory reviewer sees it in the\n// listing. openWorldHint is false throughout: every tool acts on this library.\nconst READS = {\n  readOnlyHint: true,\n  destructiveHint: false,\n  idempotentHint: true,\n  openWorldHint: false,\n} as const;\n/** Writes that only ever add (a meeting, a clip, a proposal, a vote). */\nconst ADDS = {\n  readOnlyHint: false,\n  destructiveHint: false,\n  idempotentHint: false,\n  openWorldHint: false,\n} as const;\n/** Writes that can replace what is there (a manifest commit or rollback). */\nconst REPLACES = {\n  readOnlyHint: false,\n  destructiveHint: true,\n  idempotentHint: false,\n  openWorldHint: false,\n} as const;\n\n/**\n * Sent in the MCP `initialize` response, byte-identical to the oracle's\n * `SERVER_INSTRUCTIONS` (pinned in conformance `mcp_server_meta.json`). Hosts\n * that surface server instructions to the model get a standing reason to call\n * `compile_turn`, and to reach for the shared skills on a how-to task.\n */\nexport const SERVER_INSTRUCTIONS =\n  \"Bourdon provides recognition of the user's projects, people, and prior \" +\n  \"work across their AI agents. At the start of any turn that references the \" +\n  \"user's projects, people, decisions, or prior work, call `compile_turn` \" +\n  \"with the user's message before answering or asking the user for context \" +\n  \"they may already have given another agent. For a how-to task, call \" +\n  \"`list_skills`, then `get_skill`.\";\n\n/**\n * The default MCP `compile_turn` response: the brief once, plus its anchors.\n * The full TurnBrief carries the brief four times over (every delivery\n * variant) plus the scoring trace; `verbose: true` keeps that shape.\n */\nfunction slimTurnBrief(full: Dict): Dict {\n  const routing = (full.routing ?? {}) as Dict;\n  const delivery = (full.delivery ?? {}) as Dict;\n  const items = (full.items ?? []) as Dict[];\n  return {\n    schema_version: full.schema_version,\n    agent_id: full.agent_id,\n    routing: { mode: routing.mode ?? null, confidence: routing.confidence ?? null },\n    brief: delivery.rendered_text ?? \"\",\n    items: items.map((item) => ({\n      rank: item.rank,\n      kind: item.kind,\n      name: item.name,\n      summary: item.summary,\n      source_agents: [...((item.source_agents ?? []) as unknown[])],\n    })),\n  };\n}\n\nconst CONFLICT_ACCESS_RANK: Record<string, number> = { public: 0, team: 1, private: 2 };\n\n/**\n * Throw when incoming rows violate the L5 schema (the oracle's\n * `_reject_schema_invalid_contribution`). Builds a probe manifest shaped the\n * way `commitL5` would write these rows (identity filled, workstream status\n * defaulted) and validates it, plus the supersedes self-link / cycle check.\n * Callers must have shallow-checked that rows are objects.\n */\nfunction rejectSchemaInvalidContribution(\n  agentId: string,\n  contribution: {\n    agentType: string | null;\n    instance: string | null;\n    roleNarrative: string | null;\n    entities: Dict[] | null;\n    sessions: Dict[] | null;\n    workstreams: Dict[] | null;\n    notes: Dict[] | null;\n  },\n): void {\n  const probeAgent: Dict = { id: agentId, type: contribution.agentType || \"other\" };\n  if (contribution.instance !== null) probeAgent.instance = contribution.instance;\n  if (contribution.roleNarrative !== null) probeAgent.role_narrative = contribution.roleNarrative;\n  const probe: Dict = {\n    spec_version: \"0.1\",\n    agent: probeAgent,\n    last_updated: new Date().toISOString(),\n    known_entities: [...(contribution.entities ?? [])],\n    recent_sessions: [...(contribution.sessions ?? [])],\n    known_workstreams: (contribution.workstreams ?? []).map((row) => ({\n      ...row,\n      status: row.status ?? \"active\",\n    })),\n    notes: [...(contribution.notes ?? [])],\n  };\n  const validation = validateManifest(probe);\n  const messages = [\n    ...(validation.valid\n      ? []\n      : validation.errors.map((e) =>\n          `${e.instancePath || \"/\"} [${e.keyword}] ${e.message ?? \"\"}`.trimEnd(),\n        )),\n    ...supersessionDiagnostics(probe),\n  ];\n  if (messages.length > 0) {\n    throw new Error(\n      \"contribution failed L5 validation: \" +\n        messages\n          .slice(0, 5)\n          .map((message) => `[schema] ${message}`)\n          .join(\"; \"),\n    );\n  }\n}\n\nexport function createL6Server(store: L6Store, options: CreateL6ServerOptions = {}): McpServer {\n  const name = options.name ?? \"bourdon-l6\";\n  // Python defaults BOTH collaborators eagerly (`registry = FederationRegistry()`),\n  // so the descriptor reads the operator's own registry when none is injected.\n  const registry = options.registry ?? new FederationRegistry();\n  const audit = options.audit ?? new FederationAudit();\n  const callerAudience = options.callerAudience ?? null;\n\n  const mcp = new McpServer(\n    { name, version: PACKAGE_VERSION },\n    { instructions: SERVER_INSTRUCTIONS },\n  );\n\n  // -- Trust-tier enforcement helpers (ported from the l6_server closures) -----\n\n  /** The current caller. OPERATOR (trusted) under stdio / unbound; the bound\n   * identity under HTTP (set by the auth middleware via AsyncLocalStorage). An\n   * HTTP request that bypassed the middleware never reaches here (middleware\n   * 401s first), so the stdio default is the only unbound path. */\n  function resolveCaller(): AgentIdentity {\n    return getCaller();\n  }\n\n  function recordAudit(\n    caller: AgentIdentity,\n    op: string,\n    namespace = \"*\",\n    decision: string = DECISION_ALLOW,\n    detail: string | null = null,\n  ): void {\n    audit.record(caller.agentId, op, namespace, decision, detail, {\n      traceId: caller.traceId ?? undefined,\n      taintFloor: caller.taintFloor,\n    });\n  }\n\n  /**\n   * Record a mutation in the audit log BEFORE it happens; fail closed.\n   * Mutations must not proceed unrecorded: when the audit append cannot be\n   * persisted (disk full, permissions), the mutation is refused with a\n   * structured error instead of silently happening off the record. Reads\n   * stay best-effort via `recordAudit`.\n   */\n  function mutationAuditGate(\n    caller: AgentIdentity,\n    op: string,\n    namespace = \"*\",\n    detail: string | null = null,\n  ): Dict | null {\n    try {\n      audit.record(caller.agentId, op, namespace, DECISION_ALLOW, detail, {\n        required: true,\n        traceId: caller.traceId ?? undefined,\n        taintFloor: caller.taintFloor,\n      });\n    } catch (exc) {\n      const message = exc instanceof Error ? exc.message : String(exc);\n      return {\n        error: \"audit unavailable\",\n        op,\n        agent: caller.agentId,\n        detail:\n          `mutation refused: the audit log could not be appended (${message}); ` +\n          \"free disk space or fix permissions on the audit path and retry\",\n      };\n    }\n    return null;\n  }\n\n  function denied(\n    op: string,\n    caller: AgentIdentity,\n    namespace = \"*\",\n    detail = \"tier 'quarantined' may not call this tool\",\n  ): Dict {\n    recordAudit(caller, op, namespace, DECISION_DENY, detail);\n    return {\n      error: \"access denied\",\n      op,\n      agent: caller.agentId,\n      tier: caller.tier,\n      detail,\n    };\n  }\n\n  function authorizeTool(\n    caller: AgentIdentity,\n    op: string,\n    args: Record<string, unknown> = {},\n  ): Dict | null {\n    const decision = enforceToolAccess(op, caller, args, {\n      acceptsWrites: (agentId) => namespaceAcceptsWrites(store.libraryPath, agentId),\n    });\n    if (decision.decision === \"allow\" || decision.denial === null) return null;\n    const namespace = String(args.agent ?? args.agent_id ?? (args.source_agent || \"*\"));\n    return denied(op, caller, namespace, decision.denial.detail);\n  }\n\n  /**\n   * Rewrite the filesystem paths in a tool response for an MCP caller. A\n   * caller may be remote, and an absolute path names the host's home\n   * directory, account and library layout. Every `path` and `generated_from`\n   * field (at any depth) under the library becomes its library-relative POSIX\n   * form (`agents/alice.l5.yaml`); one outside the library is dropped. The\n   * oracle's `_library_relative`.\n   */\n  function libraryRelative(value: unknown): unknown {\n    if (Array.isArray(value)) return value.map(libraryRelative);\n    if (value === null || typeof value !== \"object\") return value;\n    const out: Dict = {};\n    for (const [key, item] of Object.entries(value as Dict)) {\n      if (PATH_FIELDS.has(key) && typeof item === \"string\" && isAbsolute(item)) {\n        const rel = relativeToLibrary(item);\n        if (rel !== null) out[key] = rel;\n        continue;\n      }\n      out[key] = libraryRelative(item);\n    }\n    return out;\n  }\n\n  function relativeToLibrary(target: string): string | null {\n    const realOrResolved = (p: string): string => {\n      try {\n        return realpathSync.native(p);\n      } catch {\n        return pathResolve(p);\n      }\n    };\n    const library = store.libraryPath;\n    const pairs: [string, string][] = [\n      [pathResolve(library), pathResolve(target)],\n      [realOrResolved(library), realOrResolved(target)],\n    ];\n    for (const [root, file] of pairs) {\n      const rel = relative(root, file);\n      if (rel === \"\") return \".\";\n      if (rel === \"..\" || rel.startsWith(`..${sep}`) || isAbsolute(rel)) continue;\n      return rel.split(sep).join(\"/\");\n    }\n    return null;\n  }\n\n  /** A namespace this caller may read: granted, or org-readable (readable by\n   * every member because writable by none). The oracle's `_may_read`. */\n  function mayRead(caller: AgentIdentity, agentId: string): boolean {\n    return caller.mayRead(agentId) || store.isOrgReadable(agentId);\n  }\n\n  /** Conflicts a commit raises, filtered to what `caller` may read: the\n   * namespaces it may read, at its own ceiling (plan 006, phase b). */\n  function visibleCommitConflicts(\n    caller: AgentIdentity,\n    agentId: string,\n    entities: Dict[] | null,\n  ): CommitConflict[] {\n    const [access] = authorizedAccess(caller, \"team\", false);\n    return store.commitConflicts(\n      agentId,\n      (entities ?? []).filter(\n        (row) => row !== null && typeof row === \"object\" && !Array.isArray(row),\n      ),\n      { accessLevel: access, mayRead: (other) => mayRead(caller, other) },\n    );\n  }\n\n  /** `on_conflict=\"reject\"` refused the write; nothing was written or staged. */\n  function conflictRefusal(\n    caller: AgentIdentity,\n    agentId: string,\n    mode: string,\n    exc: CommitConflictError,\n  ): Dict {\n    recordAudit(\n      caller,\n      \"commit_to_federation\",\n      agentId,\n      DECISION_DENY,\n      `conflicts=${exc.conflicts.length}`,\n    );\n    return {\n      error: \"conflicting facts\",\n      agent_id: agentId,\n      mode,\n      conflicts: exc.conflicts,\n      detail: exc.message,\n    };\n  }\n\n  /**\n   * Drop provenance conflict records `caller` may not read (plan 006, phase b).\n   * A record stays only when its other agent is a namespace the caller may\n   * read and its `visibility` (the stricter of the two rows) is within the\n   * caller's ceiling. When anything was dropped the truncation marker goes\n   * too, so not even a count of hidden records leaks.\n   */\n  function readableConflicts(caller: AgentIdentity, write: Dict): Dict {\n    const recorded = write.conflicts;\n    if (!Array.isArray(recorded)) return write;\n    const [ceiling] = authorizedAccess(caller, \"private\", false);\n    const kept = recorded.filter((c: unknown) => {\n      if (c === null || typeof c !== \"object\" || Array.isArray(c)) return false;\n      const record = c as Dict;\n      const visibility = record.visibility;\n      return (\n        typeof record.agent === \"string\" &&\n        typeof visibility === \"string\" &&\n        Object.hasOwn(CONFLICT_ACCESS_RANK, visibility) &&\n        CONFLICT_ACCESS_RANK[visibility]! <= CONFLICT_ACCESS_RANK[ceiling]! &&\n        mayRead(caller, record.agent)\n      );\n    });\n    const out: Dict = { ...write };\n    if (kept.length !== recorded.length) delete out.conflicts_truncated;\n    if (kept.length > 0) out.conflicts = kept;\n    else delete out.conflicts;\n    return out;\n  }\n\n  /** Drop non-granted agents from EntityMatch rows; drop emptied rows. */\n  function filterEntityMatches(matches: EntityMatch[], caller: AgentIdentity): EntityMatch[] {\n    if (caller.isTrusted) return matches;\n    const kept: EntityMatch[] = [];\n    for (const m of matches) {\n      const agents = m.agents.filter((a) => mayRead(caller, a));\n      if (agents.length === 0) continue;\n      m.agents = agents;\n      const summaries: Record<string, string> = {};\n      for (const [a, s] of Object.entries(m.summaries)) {\n        if (mayRead(caller, a)) summaries[a] = s;\n      }\n      m.summaries = summaries;\n      // A supersession link names another entity; keep it only when a\n      // namespace this caller may read states it.\n      if (m.supersededBy && !m.supersededByAgents.some((a) => mayRead(caller, a))) {\n        m.supersededBy = null;\n      }\n      kept.push(m);\n    }\n    return kept;\n  }\n\n  /** Drop non-granted agents from WorkstreamMatch rows; drop emptied rows. */\n  function filterWorkstreamMatches(\n    matches: WorkstreamMatch[],\n    caller: AgentIdentity,\n  ): WorkstreamMatch[] {\n    if (caller.isTrusted) return matches;\n    const kept: WorkstreamMatch[] = [];\n    for (const match of matches) {\n      const agents = match.agents.filter((agent) => caller.mayRead(agent));\n      if (agents.length === 0) continue;\n      match.agents = agents;\n      kept.push(match);\n    }\n    return kept;\n  }\n\n  // -- Caller description -----------------------------------------------------\n  //\n  // Registered where `core/l6_server.py` registers it (immediately ahead of the\n  // resources) so the two surfaces stay line-comparable. READ-ONLY: it observes\n  // policy, it never grants anything, and it goes through NO tier gate —\n  // `describe_caller` is absent from `tier_matrix.json` and from\n  // `core/enforcement.py` on the oracle side too.\n\n  mcp.registerTool(\n    \"describe_caller\",\n    {\n      title: \"Describe caller\",\n      annotations: READS,\n      description:\n        \"Describe this authenticated member and current meetings authority.\\n\\n\" +\n        \"Requires explicit library enrollment and member-bound credentials.\\n\" +\n        \"A descriptor is a policy observation, not a reusable write permit.\",\n      inputSchema: {},\n    },\n    (): CallToolResult => {\n      const result = describeMember(resolveCaller(), registry, store.libraryPath, callerAudience);\n      const decision = \"error\" in result ? DECISION_DENY : DECISION_ALLOW;\n      // Invalid identities must not become an unbounded audit/log payload: the\n      // row is keyed on the literal \"caller\", never on the claimed agent id.\n      audit.record(\"caller\", \"describe_caller\", \"meetings\", decision);\n      return jsonContent(result);\n    },\n  );\n\n  // -- Resources ---------------------------------------------------------------\n\n  mcp.registerResource(\n    \"agents\",\n    \"agent-library://agents\",\n    { description: \"List of all agent IDs known to the federation.\" },\n    (uri): ReadResourceResult => {\n      const caller = resolveCaller();\n      if (!caller.isTrusted) {\n        return jsonResource(uri.href, denied(\"resource:agents\", caller));\n      }\n      let agents = store.listAgents();\n      if (!caller.isTrusted) agents = agents.filter((a) => caller.mayRead(a));\n      recordAudit(caller, \"resource:agents\");\n      return jsonResource(uri.href, agents);\n    },\n  );\n\n  mcp.registerResource(\n    \"agent-memory\",\n    new ResourceTemplate(\"agent-library://agents/{agent_id}/memory\", { list: undefined }),\n    { description: \"Full visibility-filtered L5 manifest for one agent.\" },\n    (uri, variables): ReadResourceResult => {\n      const caller = resolveCaller();\n      const agentId = String(variables.agent_id);\n      if (!caller.isTrusted) {\n        return jsonResource(uri.href, denied(\"resource:agent-memory\", caller, agentId));\n      }\n      if (!caller.mayRead(agentId)) {\n        return jsonResource(\n          uri.href,\n          denied(\n            \"resource:agent-memory\",\n            caller,\n            agentId,\n            `namespace ${pyRepr(agentId)} not granted`,\n          ),\n        );\n      }\n      recordAudit(caller, \"resource:agent-memory\", agentId);\n      // The local operator keeps the configured default level; a remote caller\n      // gets its own clamped ceiling, never the BOURDON_DEFAULT_ACCESS_LEVEL\n      // fallback (which may be private).\n      const manifest =\n        caller === OPERATOR\n          ? store.getAgentManifest(agentId, false)\n          : store.getAgentManifest(agentId, false, authorizedAccess(caller, \"team\", false)[0]);\n      if (manifest === null) {\n        return jsonResource(uri.href, { error: `agent not found: ${agentId}` });\n      }\n      return jsonResource(uri.href, manifest);\n    },\n  );\n\n  mcp.registerResource(\n    \"entity\",\n    new ResourceTemplate(\"agent-library://entities/{name}\", { list: undefined }),\n    { description: \"Cross-agent view of one entity by name.\" },\n    (uri, variables): ReadResourceResult => {\n      const caller = resolveCaller();\n      if (!caller.isTrusted) {\n        return jsonResource(uri.href, denied(\"resource:entity\", caller));\n      }\n      let matches = store.findEntity(String(variables.name), false, \"public\");\n      matches = filterEntityMatches(matches, caller);\n      recordAudit(caller, \"resource:entity\");\n      return jsonResource(\n        uri.href,\n        matches.map((m) => m.toDict()),\n      );\n    },\n  );\n\n  // -- Tools -------------------------------------------------------------------\n\n  mcp.registerTool(\n    \"query_agent_memory\",\n    {\n      title: \"Query agent memory\",\n      annotations: READS,\n      description: \"Find entries in one agent's L5 that match a topic.\",\n      inputSchema: {\n        agent: z.string(),\n        topic: z.string(),\n        access_level: z.string().default(\"public\"),\n        include_private: z.boolean().default(false),\n      },\n    },\n    (args): CallToolResult => {\n      const { agent, topic } = args;\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"query_agent_memory\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      recordAudit(caller, \"query_agent_memory\", agent);\n      const matches = store\n        .findEntity(topic, includePrivate, accessLevel, caller.isTrusted ? null : agent)\n        .filter((m) => m.agents.includes(agent));\n      return jsonContent({\n        agent,\n        topic,\n        access_level: accessLevel,\n        include_private: includePrivate,\n        matches: matches.map((m) => m.toDict()),\n      });\n    },\n  );\n\n  mcp.registerTool(\n    \"list_recent_work\",\n    {\n      title: \"List recent work\",\n      annotations: READS,\n      description: \"Return a page of sessions across agents (or a single agent).\",\n      inputSchema: {\n        since: z.string().nullish(),\n        agent: z.string().nullish(),\n        access_level: z.string().default(\"public\"),\n        include_private: z.boolean().default(false),\n        limit: z.number().int().nullish(),\n        cursor: z.string().nullish(),\n        summary: z.boolean().default(false),\n        federation_hop: z.number().int().default(0),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const since = args.since ?? null;\n      const agent = args.agent ?? null;\n      const [accessLevel, includePrivate] = authorizedAccess(\n        resolveCaller(),\n        args.access_level,\n        args.include_private,\n      );\n      const limit = args.limit ?? null;\n      const cursor = args.cursor ?? null;\n      const summary = args.summary;\n      const federationHop = args.federation_hop;\n\n      const caller = resolveCaller();\n      const deniedCall = authorizeTool(caller, \"list_recent_work\", args);\n      if (deniedCall !== null) {\n        const denial = deniedCall;\n        denial.sessions = [];\n        denial.next_cursor = null;\n        denial.has_more = false;\n        return jsonContent(denial);\n      }\n      recordAudit(caller, \"list_recent_work\", agent ?? \"*\");\n\n      let cutoff: Date | null = null;\n      if (since) {\n        const parsed = parseSince(since);\n        if (parsed === null) {\n          console.warn(`Invalid 'since' value: ${since}`);\n        } else {\n          cutoff = parsed;\n        }\n      }\n      try {\n        let page;\n        if (store.peers.length > 0 && federationHop <= 0) {\n          page = await store.listRecentWorkFederated({\n            since: cutoff,\n            agent,\n            includePrivate,\n            accessLevel,\n            limit,\n            cursor,\n          });\n        } else {\n          page = store.listRecentWork({\n            since: cutoff,\n            agent,\n            includePrivate,\n            accessLevel,\n            limit,\n            cursor,\n          });\n        }\n        let rows = page.sessions;\n        if (!caller.isTrusted) rows = rows.filter((s) => caller.mayRead(s.agent));\n        return jsonContent({\n          since,\n          agent,\n          access_level: accessLevel,\n          include_private: includePrivate,\n          limit,\n          cursor,\n          summary,\n          sessions: rows.map((s) => s.toDict(summary)),\n          next_cursor: page.nextCursor,\n          has_more: page.hasMore,\n        });\n      } catch (exc) {\n        // Bad cursor token — surface to the caller rather than silently treating\n        // it as a fresh first page.\n        return jsonContent({\n          error: String(exc instanceof Error ? exc.message : exc),\n          since,\n          agent,\n          access_level: accessLevel,\n          include_private: includePrivate,\n          limit,\n          cursor,\n          summary,\n          sessions: [],\n          next_cursor: null,\n          has_more: false,\n        });\n      }\n    },\n  );\n\n  mcp.registerTool(\n    \"list_workstreams\",\n    {\n      title: \"List workstreams\",\n      annotations: READS,\n      description: \"List ongoing multi-session workstreams across agents.\",\n      inputSchema: {\n        status: z.string().nullish(),\n        agent: z.string().nullish(),\n        access_level: z.string().default(\"public\"),\n        include_private: z.boolean().default(false),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"list_workstreams\", args);\n      if (denial !== null) {\n        denial.workstreams = [];\n        return jsonContent(denial);\n      }\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      const agent = args.agent ?? null;\n      recordAudit(caller, \"list_workstreams\", agent ?? \"*\");\n      let matches = store.listWorkstreams({\n        status: args.status ?? null,\n        agent,\n        includePrivate,\n        accessLevel,\n      });\n      matches = filterWorkstreamMatches(matches, caller);\n      return jsonContent({\n        status: args.status ?? null,\n        agent,\n        access_level: accessLevel,\n        include_private: includePrivate,\n        workstreams: matches.map((match) => match.toDict()),\n      });\n    },\n  );\n\n  mcp.registerTool(\n    \"list_notes\",\n    {\n      title: \"List notes\",\n      annotations: READS,\n      description: \"Return a page of freestanding notes across agents.\",\n      inputSchema: {\n        since: z.string().nullish(),\n        agent: z.string().nullish(),\n        access_level: z.string().default(\"public\"),\n        include_private: z.boolean().default(false),\n        limit: z.number().int().nullish(),\n        cursor: z.string().nullish(),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"list_notes\", args);\n      if (denial !== null) {\n        denial.notes = [];\n        denial.next_cursor = null;\n        denial.has_more = false;\n        return jsonContent(denial);\n      }\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      const since = args.since ?? null;\n      const agent = args.agent ?? null;\n      recordAudit(caller, \"list_notes\", agent ?? \"*\");\n\n      let cutoff: Date | null = null;\n      if (since) {\n        cutoff = parseSince(since);\n        if (cutoff === null) console.warn(`Invalid 'since' value: ${since}`);\n      }\n      try {\n        const page = store.listNotes({\n          since: cutoff,\n          agent,\n          includePrivate,\n          accessLevel,\n          limit: args.limit ?? null,\n          cursor: args.cursor ?? null,\n        });\n        let rows = page.notes;\n        if (!caller.isTrusted) rows = rows.filter((note) => caller.mayRead(note.agent));\n        return jsonContent({\n          since,\n          agent,\n          access_level: accessLevel,\n          include_private: includePrivate,\n          limit: args.limit ?? null,\n          cursor: args.cursor ?? null,\n          notes: rows.map((note) => note.toDict()),\n          next_cursor: page.nextCursor,\n          has_more: page.hasMore,\n        });\n      } catch (exc) {\n        return jsonContent({\n          error: String(exc instanceof Error ? exc.message : exc),\n          since,\n          agent,\n          access_level: accessLevel,\n          include_private: includePrivate,\n          limit: args.limit ?? null,\n          cursor: args.cursor ?? null,\n          notes: [],\n          next_cursor: null,\n          has_more: false,\n        });\n      }\n    },\n  );\n\n  mcp.registerTool(\n    \"find_entity\",\n    {\n      title: \"Find entity\",\n      annotations: READS,\n      description: \"Find an entity by name across all agents.\",\n      inputSchema: {\n        name: z.string(),\n        access_level: z.string().default(\"public\"),\n        include_private: z.boolean().default(false),\n        federation_hop: z.number().int().default(0),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const { name } = args;\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"find_entity\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      const federationHop = args.federation_hop;\n      recordAudit(caller, \"find_entity\");\n      // Retirement (plan 006, phase c) is derived only from workstreams in\n      // namespaces this caller may read, so a hidden archived workstream can\n      // neither retire nor reveal anything.\n      const readable = caller.isTrusted ? undefined : (agent: string) => mayRead(caller, agent);\n      let matches: EntityMatch[];\n      if (federationHop > 0) {\n        matches = store.findEntity(name, includePrivate, accessLevel, null, readable);\n      } else {\n        matches = await store.findEntityFederated(name, includePrivate, accessLevel, readable);\n      }\n      matches = filterEntityMatches(matches, caller);\n      return jsonContent({\n        name,\n        access_level: accessLevel,\n        include_private: includePrivate,\n        matches: matches.map((m) => m.toDict()),\n      });\n    },\n  );\n\n  mcp.registerTool(\n    \"trace_entity\",\n    {\n      title: \"Trace entity provenance\",\n      annotations: READS,\n      description:\n        \"Trace the memory provenance and evolution of an entity across all agents. \" +\n        \"Inspects which agent session originated it, which git commit / transcript \" +\n        \"was referenced, which version archive snapshots recorded it, and which \" +\n        \"peers also carry it.\",\n      inputSchema: {\n        entity: z.string(),\n        access_level: z.string().default(\"team\"),\n        include_private: z.boolean().default(false),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"trace_entity\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      recordAudit(caller, \"trace_entity\");\n      const trace = traceEntity(args.entity, {\n        libraryPath: store.libraryPath,\n        includePrivate,\n        accessLevel,\n        briefPath,\n      });\n      return jsonContent(entityTraceToDict(trace));\n    },\n  );\n\n  mcp.registerTool(\n    \"list_agents\",\n    {\n      title: \"List agents\",\n      annotations: READS,\n      description: \"List agent IDs known to this L6 server, plus any peers' agents.\",\n      inputSchema: {\n        federation_hop: z.number().int().default(0),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"list_agents\", args);\n      if (denial !== null) return jsonContent(denial);\n      let agents: string[];\n      if (args.federation_hop > 0) {\n        agents = [...store.listAgents()].sort();\n      } else {\n        agents = await store.listAgentsFederated();\n      }\n      if (!caller.isTrusted) agents = agents.filter((a) => caller.mayRead(a));\n      recordAudit(caller, \"list_agents\");\n      return jsonContent({ agents });\n    },\n  );\n\n  mcp.registerTool(\n    \"export_agents\",\n    {\n      title: \"Export local agents\",\n      annotations: READS,\n      description: \"Export THIS server's LOCAL agents only, source-attributed for the tray.\",\n      inputSchema: {},\n    },\n    (): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"export_agents\");\n      if (denial !== null) return jsonContent(denial);\n      // Egress visibility clamp (3-Star audit P0-1): PRIVATE session content must\n      // never cross the federation wire. Trusted -> team; quarantined -> public;\n      // the member's max_access ceiling then applies on top.\n      const egressAccess = exportEgressAccess(caller);\n      const envelope = exportLocalAgents(\n        pathJoin(store.libraryPath, \"agents\"),\n        resolveLocalName(),\n        egressAccess,\n      );\n      if (!caller.isTrusted) {\n        envelope.agents = (envelope.agents as Dict[]).filter((a) =>\n          caller.mayRead(String(a.id ?? \"\")),\n        );\n      }\n      recordAudit(caller, \"export_agents\");\n      return jsonContent(libraryRelative(envelope));\n    },\n  );\n\n  mcp.registerTool(\n    \"commit_to_federation\",\n    {\n      title: \"Commit to federation\",\n      annotations: REPLACES,\n      description:\n        \"Call when the conversation settles something the user's other agents should know: \" +\n        \"a decision, a plan, a status change (shipped, blocked, paused) or a finding. \" +\n        'Commit under your own agent_id. Mark anything personal, financial or credential-like visibility: \"private\". ' +\n        \"Never commit small talk or a transcript. \" +\n        \"Write a contribution to the federation under agent_id: durable facts in entities (name + summary), \" +\n        \"what happened in sessions (date, project_focus, key_actions), short dated facts in notes.\",\n      inputSchema: {\n        agent_id: z.string(),\n        agent_type: z.string().nullish(),\n        instance: z.string().nullish(),\n        role_narrative: z.string().nullish(),\n        entities: z.array(z.record(z.string(), z.unknown())).nullish(),\n        sessions: z.array(z.record(z.string(), z.unknown())).nullish(),\n        workstreams: z.array(z.record(z.string(), z.unknown())).nullish(),\n        notes: z.array(z.record(z.string(), z.unknown())).nullish(),\n        mode: z.string().default(\"merge\"),\n        expected_digest: z.string().nullish(),\n        session_id: z.string().nullish(),\n        transcript_ref: z.string().nullish(),\n        on_clamp: z.string().default(\"spill\"),\n        on_conflict: z.string().default(\"flag\"),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const agentId = args.agent_id;\n      const agentType = args.agent_type ?? null;\n      const instance = args.instance ?? null;\n      const roleNarrative = args.role_narrative ?? null;\n      const entities = (args.entities ?? null) as Dict[] | null;\n      const sessions = (args.sessions ?? null) as Dict[] | null;\n      const workstreams = (args.workstreams ?? null) as Dict[] | null;\n      const notes = (args.notes ?? null) as Dict[] | null;\n      const mode = args.mode;\n      const expectedDigest = args.expected_digest ?? null;\n      const sessionId = args.session_id ?? null;\n      const transcriptRef = args.transcript_ref ?? null;\n\n      const caller = resolveCaller();\n      const deniedCall = authorizeTool(caller, \"commit_to_federation\", args);\n      if (deniedCall !== null) return jsonContent(deniedCall);\n      if (!caller.isTrusted) {\n        let stagedConflicts: CommitConflict[] = [];\n        try {\n          const families = { entities, sessions, workstreams, notes };\n          for (const [family, rows] of Object.entries(families)) requireBoundedCommitRows(family, rows);\n          requireBoundedCommitPayload(families);\n          for (const row of entities ?? []) {\n            if (row === null || typeof row !== \"object\" || !String(row.name ?? \"\").trim()) {\n              throw new Error(\"each entity needs a non-empty 'name'\");\n            }\n          }\n          for (const row of sessions ?? []) {\n            // \"\" is allowed, matching the schema's Session.date provision for\n            // \"no recognisable timestamp\". Missing/non-string/whitespace stays\n            // rejected; real dates are checked by the schema validation below.\n            const dateValue = row !== null && typeof row === \"object\" ? row.date : undefined;\n            if (typeof dateValue !== \"string\" || (dateValue !== \"\" && !dateValue.trim())) {\n              throw new Error(`each session needs a string ISO-8601 'date' (or \"\")`);\n            }\n          }\n          for (const row of workstreams ?? []) {\n            if (row === null || typeof row !== \"object\" || !String(row.name ?? \"\").trim()) {\n              throw new Error(\"each workstream needs a non-empty 'name'\");\n            }\n          }\n          for (const row of notes ?? []) {\n            if (\n              row === null ||\n              typeof row !== \"object\" ||\n              !String(row.date ?? \"\").trim() ||\n              !String(row.text ?? \"\").trim()\n            ) {\n              throw new Error(\"each note needs a non-empty 'date' and 'text'\");\n            }\n          }\n          // Schema-validate the incoming rows before they are copied into\n          // staging (including the supersedes self-link / cycle check); commitL5\n          // validates the merge again at promotion. Rejecting here keeps\n          // staging clean too.\n          rejectSchemaInvalidContribution(agentId, {\n            agentType,\n            instance,\n            roleNarrative,\n            entities,\n            sessions,\n            workstreams,\n            notes,\n          });\n          if (!(ON_CONFLICT_MODES as readonly string[]).includes(args.on_conflict)) {\n            throw new Error(\n              `invalid on_conflict '${args.on_conflict}': must be one of ['flag', 'reject']`,\n            );\n          }\n          // Conflicts against the namespaces this caller may read, at its own\n          // ceiling: a report or a refusal never reveals a row it could not\n          // read anyway (plan 006, phase b).\n          stagedConflicts = visibleCommitConflicts(caller, agentId, entities);\n          if (stagedConflicts.length > 0 && args.on_conflict === \"reject\") {\n            throw new CommitConflictError(stagedConflicts);\n          }\n          // Fail closed on the audit: the staged write must not happen\n          // unrecorded, so the entry lands BEFORE the write.\n          const gate = mutationAuditGate(\n            caller,\n            \"commit_to_federation\",\n            agentId,\n            agentId !== caller.agentId ? \"staged via=write_grant\" : \"staged\",\n          );\n          if (gate !== null) {\n            return jsonContent({ ...gate, agent_id: agentId, mode });\n          }\n          const path = mergeIntoStaged(\n            store.libraryPath,\n            caller.agentId,\n            agentId,\n            entities,\n            sessions,\n            {\n              agentType,\n              instance,\n              roleNarrative,\n              workstreams,\n              notes,\n            },\n          );\n          const stagedResult: Dict = {\n            staged: true,\n            agent_id: agentId,\n            path: String(path),\n            note:\n              \"quarantined write staged for review; an operator must run \" +\n              \"`bourdon staging promote \" +\n              agentId +\n              \"` before it propagates to the federation\",\n          };\n          if (stagedConflicts.length > 0) {\n            stagedResult.conflicts = stagedConflicts.slice(0, MAX_REPORTED_CONFLICTS);\n          }\n          if (stagedConflicts.length > MAX_REPORTED_CONFLICTS) {\n            stagedResult.conflicts_truncated = true;\n          }\n          return jsonContent(libraryRelative(stagedResult));\n        } catch (exc) {\n          if (exc instanceof CommitConflictError) {\n            return jsonContent(conflictRefusal(caller, agentId, mode, exc));\n          }\n          if (isOsError(exc)) {\n            // Disk-full and friends surface as a structured refusal whose\n            // detail names no file.\n            recordAudit(caller, \"commit_to_federation\", agentId, DECISION_DENY, \"staging write failed\");\n            return jsonContent({\n              error: \"staging write failed\",\n              agent_id: agentId,\n              mode,\n              detail: osErrorDetail(exc),\n            });\n          }\n          return jsonContent({\n            error: String(exc instanceof Error ? exc.message : exc),\n            agent_id: agentId,\n            mode,\n          });\n        }\n      }\n      // Fail closed on the audit: a mutation must never happen unrecorded.\n      const gate = mutationAuditGate(caller, \"commit_to_federation\", agentId);\n      if (gate !== null) {\n        return jsonContent({ ...gate, agent_id: agentId, mode });\n      }\n      try {\n        const commitOptions: CommitL5Options = {\n          agentType,\n          instance,\n          roleNarrative,\n          entities,\n          sessions,\n          workstreams,\n          notes,\n          mode: mode as \"merge\" | \"replace\",\n          // The caller identity comes from the authenticated session, never\n          // from a parameter — otherwise provenance is self-reported.\n          // session_id/transcript_ref ARE caller-asserted, documented as such.\n          caller: caller.agentId,\n          sessionId,\n          transcriptRef,\n          onClamp: args.on_clamp,\n          onConflict: args.on_conflict,\n          conflictAccessLevel: authorizedAccess(caller, \"team\", false)[0],\n          conflictMayRead: (other: string) => mayRead(caller, other),\n        };\n        // Only forward a CAS base when one was supplied: passing null would\n        // assert \"this manifest does not exist yet\" and fail every merge.\n        if (expectedDigest !== null) commitOptions.expectedDigest = expectedDigest;\n        const summary = await store.commitL5(agentId, commitOptions);\n        return jsonContent(summary);\n      } catch (exc) {\n        if (exc instanceof CommitConflictError) {\n          return jsonContent(conflictRefusal(caller, agentId, mode, exc));\n        }\n        if (exc instanceof StaleWriteError) {\n          recordAudit(caller, \"commit_to_federation\", agentId, DECISION_DENY, \"stale write\");\n          return jsonContent({\n            error: \"stale write\",\n            agent_id: agentId,\n            mode,\n            expected_digest: exc.expected,\n            current_digest: exc.found,\n            detail:\n              \"the manifest changed since the digest you passed; re-read \" +\n              \"it, re-apply your edit to the new state, and commit again\",\n          });\n        }\n        if (exc instanceof ReadOnlyMemoryError) {\n          recordAudit(caller, \"commit_to_federation\", agentId, DECISION_DENY, \"read-only memory\");\n          return jsonContent({\n            error: \"read-only memory\",\n            agent_id: agentId,\n            detail: exc.message,\n          });\n        }\n        if (isOsError(exc)) {\n          // Disk-full and friends surface as a structured refusal whose detail\n          // names no file. Checked AFTER the store's own error types.\n          recordAudit(caller, \"commit_to_federation\", agentId, DECISION_DENY, \"store write failed\");\n          return jsonContent({\n            error: \"store write failed\",\n            agent_id: agentId,\n            mode,\n            detail: osErrorDetail(exc),\n          });\n        }\n        return jsonContent({\n          error: String(exc instanceof Error ? exc.message : exc),\n          agent_id: agentId,\n          mode,\n        });\n      }\n    },\n  );\n\n  mcp.registerTool(\n    \"get_cross_agent_summary\",\n    {\n      title: \"Cross-agent summary\",\n      annotations: READS,\n      description: \"Aggregate everything the federation knows about a project.\",\n      inputSchema: {\n        project: z.string(),\n        access_level: z.string().default(\"public\"),\n        include_private: z.boolean().default(false),\n        federation_hop: z.number().int().default(0),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const { project } = args;\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"get_cross_agent_summary\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      const federationHop = args.federation_hop;\n      recordAudit(caller, \"get_cross_agent_summary\");\n      let summary;\n      if (federationHop > 0) {\n        summary = store.getCrossAgentSummary(project, includePrivate, accessLevel);\n      } else {\n        summary = await store.getCrossAgentSummaryFederated(project, includePrivate, accessLevel);\n      }\n      return jsonContent(summary.toDict());\n    },\n  );\n\n  mcp.registerTool(\n    \"prepare_recognition_context\",\n    {\n      title: \"Prepare recognition context\",\n      annotations: READS,\n      description: \"Return immediate recognition and a bounded prompt-context fragment.\",\n      inputSchema: {\n        prompt: z.string(),\n        access_level: z.string().default(\"team\"),\n        include_private: z.boolean().default(false),\n        federation_hop: z.number().int().default(0),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const { prompt } = args;\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"prepare_recognition_context\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      const federationHop = args.federation_hop;\n      recordAudit(caller, \"prepare_recognition_context\");\n      const response =\n        store.peers.length > 0 && federationHop <= 0\n          ? await prepareRecognitionContextFederated(store, prompt, accessLevel, includePrivate)\n          : await prepareRecognitionContextFromStore(store, prompt, accessLevel, includePrivate);\n      // Deliberately OUTSIDE the measured recognition window: this reads\n      // state a previous export already wrote and must not be charged to\n      // the recognition_latency_us figure callers tune against. The key is\n      // present only when non-empty — a healthy machine says nothing.\n      const drifting = driftingSurfaces();\n      if (drifting.length > 0) {\n        (response as Record<string, unknown>).drifting_surfaces = drifting;\n      }\n      return jsonContent(response);\n    },\n  );\n\n  mcp.registerTool(\n    \"compile_codex_turn\",\n    {\n      title: \"Compile Codex turn brief\",\n      annotations: READS,\n      description: \"Compile a turn-scoped Codex recognition brief.\",\n      inputSchema: {\n        prompt: z.string(),\n        cwd: z.string().nullish(),\n        access_level: z.string().default(\"team\"),\n        max_items: z.number().int().default(6),\n        max_chars: z.number().int().default(1800),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"compile_codex_turn\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel] = authorizedAccess(caller, args.access_level, false);\n      recordAudit(caller, \"compile_codex_turn\");\n      return jsonContent(\n        compileCodexTurnFromStore(store, args.prompt, {\n          cwd: args.cwd ?? null,\n          accessLevel,\n          maxItems: args.max_items,\n          maxChars: args.max_chars,\n        }),\n      );\n    },\n  );\n\n  mcp.registerTool(\n    \"compile_turn\",\n    {\n      title: \"Compile turn brief\",\n      annotations: READS,\n      description:\n        \"Call FIRST, before answering, whenever the user's message references \" +\n        \"their projects, people, decisions or prior work. Returns a short \" +\n        \"recognition brief of what the user's other agents already know. \" +\n        \"`format` picks markdown, xml, compact, brief, json or yaml. \" +\n        \"`verbose: true` returns the full brief with every delivery variant, \" +\n        \"trace and diagnostics.\",\n      inputSchema: {\n        prompt: z.string(),\n        agent: z.string().default(\"generic\"),\n        cwd: z.string().nullish(),\n        access_level: z.string().default(\"team\"),\n        max_items: z.number().int().default(6),\n        max_chars: z.number().int().default(1800),\n        format: z.string().default(\"markdown\"),\n        verbose: z.boolean().default(false),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"compile_turn\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel] = authorizedAccess(caller, args.access_level, false);\n      recordAudit(caller, \"compile_turn\");\n      const full = universalTurnBriefToDict(\n        compileTurn(args.prompt, {\n          agentId: args.agent,\n          // An omitted cwd means \"no repo\", never the server process's own\n          // working directory (a service's cwd is System32 on Windows).\n          cwd: args.cwd || \"\",\n          libraryPath: store.libraryPath,\n          accessLevel,\n          maxItems: args.max_items,\n          maxChars: args.max_chars,\n          format: args.format,\n          // Grants gate namespaces here as in every other cross-agent read.\n          readable: caller.isTrusted\n            ? undefined\n            : (agent: string) => caller.mayRead(agent) || store.isOrgReadable(agent),\n        }),\n      ) as Dict;\n      return jsonContent(args.verbose ? full : slimTurnBrief(full));\n    },\n  );\n\n  mcp.registerTool(\n    \"ingest_meeting\",\n    {\n      title: \"Ingest meeting\",\n      annotations: ADDS,\n      description:\n        \"Ingest a meeting transcript, sync notes, or decision log into meetings memory.\",\n      inputSchema: {\n        content: z.string(),\n        access_level: z.string().default(\"team\"),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"ingest_meeting\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel] = authorizedAccess(caller, args.access_level, false);\n      recordAudit(caller, \"ingest_meeting\");\n      return jsonContent(\n        libraryRelative(\n          await ingestMeeting(args.content, store, {\n            accessLevel,\n            caller: caller.agentId,\n          }),\n        ),\n      );\n    },\n  );\n\n  mcp.registerTool(\n    \"get_deeper_context\",\n    {\n      title: \"Get deeper context\",\n      annotations: READS,\n      description: \"Return post-recognition L2 context for the prompt.\",\n      inputSchema: {\n        prompt: z.string(),\n        access_level: z.string().default(\"team\"),\n        include_private: z.boolean().default(false),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"get_deeper_context\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      recordAudit(caller, \"get_deeper_context\");\n      return jsonContent(\n        await getDeeperContextForPrompt(store, args.prompt, accessLevel, includePrivate),\n      );\n    },\n  );\n\n  mcp.registerTool(\n    \"list_memory_versions\",\n    {\n      title: \"List memory versions\",\n      annotations: READS,\n      description:\n        \"Prior states of one agent's memory, newest first. Each row carries an \" +\n        \"opaque version_id to pass to rollback_agent_memory and a digest8 that \" +\n        \"joins to the provenance entry explaining which session produced it.\",\n      inputSchema: {\n        agent_id: z.string(),\n        limit: z.number().int().nullish(),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"list_memory_versions\", args);\n      if (denial !== null) return jsonContent(denial);\n      if (!caller.mayRead(args.agent_id)) {\n        return jsonContent(denied(\"list_memory_versions\", caller, args.agent_id, \"not granted\"));\n      }\n      recordAudit(caller, \"list_memory_versions\", args.agent_id);\n      let rows: Dict[];\n      try {\n        rows = store.listMemoryVersions(args.agent_id);\n      } catch (error) {\n        if (\n          error instanceof Error &&\n          error.name === \"InvalidHistoryPathError\" &&\n          \"code\" in error &&\n          error.code === \"BOURDON_INVALID_HISTORY_PATH\"\n        ) {\n          return jsonContent({\n            error: \"invalid input\",\n            detail: \"invalid history namespace or path\",\n          });\n        }\n        throw error;\n      }\n      if (args.limit !== null && args.limit !== undefined) {\n        rows = rows.slice(0, Math.max(0, Math.trunc(args.limit)));\n      }\n      return jsonContent({ agent_id: args.agent_id, versions: rows, count: rows.length });\n    },\n  );\n\n  mcp.registerTool(\n    \"explain_memory_change\",\n    {\n      title: \"Explain memory change\",\n      annotations: READS,\n      description:\n        \"Which write produced a given state of an agent's memory: hand it a \" +\n        \"manifest digest (or a version's digest8) and it returns the caller, \" +\n        \"session, transcript, and what changed. session_id and transcript_ref \" +\n        \"are caller-asserted and unverified; the recorded caller identity is not.\",\n      inputSchema: {\n        agent_id: z.string(),\n        digest: z.string(),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"explain_memory_change\", args);\n      if (denial !== null) return jsonContent(denial);\n      if (!caller.mayRead(args.agent_id)) {\n        return jsonContent(denied(\"explain_memory_change\", caller, args.agent_id, \"not granted\"));\n      }\n      recordAudit(caller, \"explain_memory_change\", args.agent_id);\n      let found: Dict | null;\n      try {\n        found = explainDigest(store.libraryPath, args.agent_id, args.digest);\n      } catch (error) {\n        if (\n          error instanceof Error &&\n          error.name === \"InvalidHistoryPathError\" &&\n          \"code\" in error &&\n          error.code === \"BOURDON_INVALID_HISTORY_PATH\"\n        ) {\n          return jsonContent({\n            error: \"invalid input\",\n            detail: \"invalid history namespace or path\",\n          });\n        }\n        throw error;\n      }\n      if (found === null) {\n        return jsonContent({\n          agent_id: args.agent_id,\n          digest: args.digest,\n          found: false,\n          detail: \"no recorded write produced that state\",\n        });\n      }\n      return jsonContent({\n        agent_id: args.agent_id,\n        found: true,\n        write: readableConflicts(caller, found),\n      });\n    },\n  );\n\n  mcp.registerTool(\n    \"rollback_agent_memory\",\n    {\n      title: \"Roll back agent memory\",\n      annotations: REPLACES,\n      description:\n        \"Restore an archived version of an agent's memory. TRUSTED ONLY — the \" +\n        \"most destructive operation the server exposes: it discards every \" +\n        \"contribution made after the chosen version, including other agents'. \" +\n        \"Pass expected_digest when the decision took a while, so a commit that \" +\n        \"landed meanwhile fails the restore instead of being silently erased. \" +\n        \"The restore is itself snapshotted first, so a rollback is undoable.\",\n      inputSchema: {\n        agent_id: z.string(),\n        version_id: z.string(),\n        expected_digest: z.string().nullish(),\n        session_id: z.string().nullish(),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      if (!caller.isTrusted) {\n        // A rollback is a deletion wearing a restore's clothes: quarantined\n        // callers cannot reach it directly, and staging is no path to it\n        // either — staging is for ADDING content.\n        return jsonContent(\n          denied(\n            \"rollback_agent_memory\",\n            caller,\n            args.agent_id,\n            \"rollback discards other agents' contributions and is restricted to trusted callers\",\n          ),\n        );\n      }\n      // Fail closed on the audit: the most destructive mutation the server\n      // exposes must never happen unrecorded.\n      const gate = mutationAuditGate(\n        caller,\n        \"rollback_agent_memory\",\n        args.agent_id,\n        `restore=${args.version_id} requested`,\n      );\n      if (gate !== null) {\n        gate.agent_id = args.agent_id;\n        return jsonContent(gate);\n      }\n      const options: RollbackL5Options = {\n        caller: caller.agentId,\n        sessionId: args.session_id ?? null,\n      };\n      if (args.expected_digest !== null && args.expected_digest !== undefined) {\n        options.expectedDigest = args.expected_digest;\n      }\n      let result: Dict;\n      try {\n        result = await store.rollbackL5(args.agent_id, args.version_id, options);\n      } catch (exc) {\n        if (\n          exc instanceof Error &&\n          exc.name === \"InvalidHistoryPathError\" &&\n          \"code\" in exc &&\n          exc.code === \"BOURDON_INVALID_HISTORY_PATH\"\n        ) {\n          return jsonContent({\n            error: \"invalid input\",\n            detail: \"invalid history namespace or path\",\n          });\n        }\n        if (exc instanceof ReadOnlyMemoryError) {\n          recordAudit(caller, \"rollback_agent_memory\", args.agent_id, DECISION_DENY, \"read-only memory\");\n          return jsonContent({\n            error: \"read-only memory\",\n            agent_id: args.agent_id,\n            detail: exc.message,\n          });\n        }\n        if (exc instanceof StaleWriteError) {\n          recordAudit(caller, \"rollback_agent_memory\", args.agent_id, DECISION_DENY, \"stale write\");\n          return jsonContent({\n            error: \"stale write\",\n            agent_id: args.agent_id,\n            expected_digest: exc.expected,\n            current_digest: exc.found,\n            detail:\n              \"memory changed while the rollback was being decided; \" +\n              \"re-read the history and choose again\",\n          });\n        }\n        if (isOsError(exc)) {\n          // Disk-full and friends surface as a structured refusal, not a\n          // stack trace. Checked AFTER the store's own error types, which\n          // carry more specific stories.\n          recordAudit(caller, \"rollback_agent_memory\", args.agent_id, DECISION_DENY, \"store write failed\");\n          return jsonContent({\n            error: \"store write failed\",\n            agent_id: args.agent_id,\n            detail: osErrorDetail(exc),\n          });\n        }\n        return jsonContent({\n          error: exc instanceof Error ? exc.message : String(exc),\n          agent_id: args.agent_id,\n        });\n      }\n      recordAudit(\n        caller,\n        \"rollback_agent_memory\",\n        args.agent_id,\n        DECISION_ALLOW,\n        `restored=${args.version_id}`,\n      );\n      return jsonContent(libraryRelative(result));\n    },\n  );\n\n  mcp.registerTool(\n    \"search_federation\",\n    {\n      title: \"Search federation\",\n      annotations: READS,\n      description:\n        \"Search across federated agent memory, entities, consensus proposals, and clips. \" +\n        \"Uses sublinear-scaled TF-IDF cosine similarity vector search.\",\n      inputSchema: {\n        query: z.string(),\n        top_k: z.number().int().default(5),\n        min_score: z.number().default(0.01),\n        source: z.string().nullish(),\n        access_level: z.string().default(\"team\"),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"search_federation\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel] = authorizedAccess(caller, args.access_level, false);\n      recordAudit(caller, \"search_federation\");\n\n      const engine = new ZeroDepVectorEngine();\n      const readable = caller.isTrusted ? undefined : (agent: string) => mayRead(caller, agent);\n      // The agents' L5 memory, through the same visibility filter and\n      // namespace grants as every other read tool.\n      engine.indexStore(store, { accessLevel, readable });\n      // Every auxiliary record (legacy manifests and L6 entities, clips)\n      // passes the same ceiling and namespace check before it is indexed, so a\n      // hidden row neither surfaces nor shifts the scores of visible ones.\n      // Consensus proposals reach only callers the consensus tools serve.\n      // The operator's own ~/.bourdon/clips are indexed only for a trusted\n      // caller: reaching for them by default made the document count depend\n      // on whose machine ran the query. Paths come back library-relative.\n      engine.indexLibrary(store.libraryPath, {\n        includeOperatorClips: caller.isTrusted,\n        operatorClipsDir: defaultClipsDir,\n        accessLevel,\n        readable,\n        includeProposals: caller.isTrusted || quarantineMayCall(\"vote_consensus\"),\n        relativePaths: true,\n      });\n      const matches = engine.search(args.query, {\n        topK: args.top_k,\n        minScore: args.min_score,\n        sourceFilter: args.source ?? null,\n      });\n      return jsonContent({\n        query: args.query,\n        total_matches: matches.length,\n        results: matches.map(searchResultToDict),\n      });\n    },\n  );\n\n  mcp.registerTool(\n    \"capture_clip\",\n    {\n      title: \"Capture clip\",\n      annotations: ADDS,\n      description:\n        \"Capture a research note, code snippet, or link into Bourdon memory. \" +\n        \"Saves to the federated clipper store for discovery by all agents.\",\n      inputSchema: {\n        content: z.string(),\n        title: z.string().nullish(),\n        tags: z.array(z.string()).nullish(),\n        source_url: z.string().nullish(),\n        access_level: z.string().default(\"team\"),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"capture_clip\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel] = authorizedAccess(caller, args.access_level, false);\n      // capture_clip WRITES into the federated clipper store, so it takes the\n      // fail-closed gate: a mutation must not proceed unrecorded.\n      const gate = mutationAuditGate(caller, \"capture_clip\");\n      if (gate !== null) return jsonContent(gate);\n\n      const clipper = getClipper(pathJoin(store.libraryPath, \".clips\"));\n      let clip;\n      try {\n        clip = clipper.capture({\n          content: args.content,\n          title: args.title ?? null,\n          tags: args.tags ?? null,\n          sourceUrl: args.source_url ?? null,\n          agentId: caller.agentId,\n          metadata: { access_level: accessLevel },\n        });\n      } catch (exc) {\n        return jsonContent({ error: exc instanceof Error ? exc.message : String(exc) });\n      }\n      return jsonContent({\n        ok: true,\n        clip_id: clip.clipId,\n        title: clip.title,\n        agent_id: clip.agentId,\n        access_level: accessLevel,\n      });\n    },\n  );\n\n  mcp.registerTool(\n    \"propose_consensus\",\n    {\n      title: \"Propose consensus\",\n      annotations: ADDS,\n      description:\n        \"Propose a decision topic for multi-agent federation consensus. \" +\n        \"Strategies: majority, supermajority, unanimity, weighted.\",\n      inputSchema: {\n        topic: z.string(),\n        options: z.array(z.string()),\n        strategy: z.string().default(\"majority\"),\n        quorum: z.number().int().default(2),\n        description: z.string().default(\"\"),\n        proposal_id: z.string().nullish(),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"propose_consensus\", args);\n      if (denial !== null) return jsonContent(denial);\n      const gate = mutationAuditGate(caller, \"propose_consensus\");\n      if (gate !== null) return jsonContent(gate);\n\n      // An unrecognized strategy falls back to \"majority\" rather than\n      // erroring — the oracle's behaviour, and the metadata records what was\n      // actually used, not what was asked for.\n      const strategy = (CONSENSUS_STRATEGIES as readonly string[]).includes(args.strategy)\n        ? args.strategy\n        : \"majority\";\n      const engine = new ConsensusEngine(pathJoin(store.libraryPath, \".consensus\"));\n      try {\n        const proposal = engine.propose({\n          topic: args.topic,\n          options: args.options,\n          proposedBy: caller.agentId,\n          quorum: args.quorum,\n          proposalId: args.proposal_id ?? null,\n          metadata: { strategy, description: args.description },\n        });\n        return jsonContent(proposalToDict(proposal));\n      } catch (exc) {\n        return jsonContent({ error: exc instanceof Error ? exc.message : String(exc) });\n      }\n    },\n  );\n\n  mcp.registerTool(\n    \"vote_consensus\",\n    {\n      title: \"Vote on consensus\",\n      annotations: ADDS,\n      description: \"Cast a vote on an active multi-agent consensus proposal.\",\n      inputSchema: {\n        proposal_id: z.string(),\n        choice: z.string(),\n        reason: z.string().default(\"\"),\n      },\n    },\n    async (args): Promise<CallToolResult> => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"vote_consensus\", args);\n      if (denial !== null) return jsonContent(denial);\n      const gate = mutationAuditGate(caller, \"vote_consensus\");\n      if (gate !== null) return jsonContent(gate);\n\n      const engine = new ConsensusEngine(pathJoin(store.libraryPath, \".consensus\"));\n      try {\n        const proposal = engine.vote({\n          proposalId: args.proposal_id,\n          agentId: caller.agentId,\n          option: args.choice,\n          rationale: args.reason,\n        });\n        const tally = engine.tally(args.proposal_id);\n        return jsonContent({ ok: true, proposal: proposalToDict(proposal), tally });\n      } catch (exc) {\n        if (exc instanceof ProposalNotFoundError) {\n          return jsonContent({ error: `proposal not found: ${args.proposal_id}` });\n        }\n        return jsonContent({ error: exc instanceof Error ? exc.message : String(exc) });\n      }\n    },\n  );\n\n  // -- Skills (plan 005, phase 3) ---------------------------------------------\n\n  mcp.registerTool(\n    \"list_skills\",\n    {\n      title: \"List skills\",\n      annotations: READS,\n      description:\n        \"List the skills (step-by-step procedures) this caller may load.\\n\\n\" +\n        \"Three kinds of row, told apart by `tier`:\\n\\n\" +\n        \"* `shared` -- promoted into the shared skill library. Carries `name`, \" +\n        \"`description`, `version`, `content_sha256` and its provenance \" +\n        \"(`source_agent`, `promoted_by`, `promoted_at`). `get_skill` returns its body.\\n\" +\n        \"* `advertised` -- a skill an agent keeps locally and lists in its manifest \" +\n        \"(only with `include_local`, the default). One row per `content_sha256`, \" +\n        \"naming every agent that has it in `advertised_by`, with `origin` when known \" +\n        \"and `shared` (`matches` / `diverged`) when a shared skill has the same bytes \" +\n        \"or name. Not loadable until promoted.\\n\" +\n        \"* `proposed` -- a skill proposed for the shared library (`propose_skill`) \" +\n        \"and awaiting a person's approval (only with `include_local`; a trusted \" +\n        \"caller sees every pending proposal, any other caller its own).\\n\\n\" +\n        \"`query` filters by a case-insensitive substring of the name or description. \" +\n        \"Rows follow the caller's access ceiling; advertised rows come only from \" +\n        \"namespaces the caller may read.\",\n      inputSchema: {\n        query: z.string().nullish(),\n        include_local: z.boolean().default(true),\n        access_level: z.string().default(\"team\"),\n        include_private: z.boolean().default(false),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"list_skills\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel, includePrivate] = authorizedAccess(\n        caller,\n        args.access_level,\n        args.include_private,\n      );\n      recordAudit(caller, \"list_skills\");\n      const payload = listSkillsPayload(store, {\n        accessLevel,\n        mayRead: (agentId) => caller.isTrusted || mayRead(caller, agentId),\n        query: args.query ?? null,\n        includeLocal: args.include_local,\n        proposals: args.include_local ? visibleProposals(caller, accessLevel) : [],\n      });\n      payload.include_private = includePrivate;\n      return jsonContent(payload);\n    },\n  );\n\n  mcp.registerTool(\n    \"get_skill\",\n    {\n      title: \"Get skill\",\n      annotations: READS,\n      description:\n        \"Load one shared skill: its `SKILL.md` text as `body`, with provenance.\\n\\n\" +\n        \"Only skills promoted into the shared library have a body here. The response \" +\n        \"carries `source_agent`, `promoted_by`, `version` and `content_sha256` beside \" +\n        \"the text so you can see what you are about to follow. `version` selects an \" +\n        \"archived version (default: the live one; a retired skill is served only by \" +\n        \"explicit version). `include_files` adds the reference files (`file`, `bytes` \" +\n        \"and `text`).\\n\\n\" +\n        \"For a skill an agent only advertises, the response is its index rows and a \" +\n        \"message that it must be promoted first; Bourdon never reads an agent's skill \" +\n        \"folder over MCP.\",\n      inputSchema: {\n        name: z.string(),\n        version: z.number().int().nullish(),\n        include_files: z.boolean().default(false),\n        access_level: z.string().default(\"team\"),\n        include_private: z.boolean().default(false),\n      },\n    },\n    (args): CallToolResult => {\n      const caller = resolveCaller();\n      const denial = authorizeTool(caller, \"get_skill\", args);\n      if (denial !== null) return jsonContent(denial);\n      const [accessLevel] = authorizedAccess(caller, args.access_level, args.include_private);\n      recordAudit(caller, \"get_skill\");\n      return jsonContent(\n        getSkillPayload(store, args.name, {\n          accessLevel,\n          mayRead: (agentId) => caller.isTrusted || mayRead(caller, agentId),\n          version: args.version ?? null,\n          includeFiles: args.include_files,\n          // A quarantined caller gets the SKILL.md body, never reference file text.\n          serveFileContents: caller.isTrusted,\n        }),\n      );\n    },\n  );\n\n  // -- Skill proposals (plan 005, phase 4) ------------------------------------\n\n  /**\n   * Pending skill proposals `caller` may see. A trusted caller reading at TEAM\n   * or above sees every pending proposal (a row carries an advertised skill's\n   * description, which is TEAM). Any caller sees the proposals it made itself.\n   */\n  function visibleProposals(caller: AgentIdentity, accessLevel: string): Dict[] {\n    let pending;\n    try {\n      pending = listProposals(store.libraryPath, STATUS_PENDING);\n    } catch {\n      return [];\n    }\n    const seesAll =\n      caller.isTrusted && (CONFLICT_ACCESS_RANK[accessLevel] ?? -1) >= CONFLICT_ACCESS_RANK.team!;\n    return pending.filter((p) => seesAll || p.proposed_by === caller.agentId).map(proposalSummary);\n  }\n\n  function proposeSkill(args: {\n    name: string;\n    content_sha256?: string | null;\n    source_agent?: string | null;\n  }): Dict {\n    const caller = resolveCaller();\n    const denial = authorizeTool(caller, \"propose_skill\", args);\n    if (denial !== null) return denial;\n    const name = args.name;\n    const wanted = args.content_sha256 ?? null;\n    const sourceAgent = args.source_agent ?? null;\n\n    let agent = caller.agentId;\n    if (caller === OPERATOR && sourceAgent) {\n      agent = sourceAgent;\n    } else if (sourceAgent && sourceAgent !== caller.agentId) {\n      return denied(\n        \"propose_skill\",\n        caller,\n        sourceAgent,\n        \"an agent may propose only its own advertised skills\",\n      );\n    }\n    try {\n      validateSkillName(name);\n    } catch (exc) {\n      if (!(exc instanceof SkillIndexError)) throw exc;\n      return { error: \"invalid skill name\", name, detail: exc.message };\n    }\n\n    // The agent's OWN advertisement, read back for that agent (or for the local\n    // operator). SkillRefs are always emitted at TEAM, so this read is pinned\n    // there rather than at the caller's egress ceiling: nothing from the\n    // manifest leaves except the proposal the caller asked for.\n    const manifest = store.getAgentManifest(agent, false, \"team\") ?? {};\n    const advertised = Array.isArray(manifest.skills) ? (manifest.skills as unknown[]) : [];\n    const refs = advertised.filter(\n      (ref): ref is Dict =>\n        ref !== null &&\n        typeof ref === \"object\" &&\n        !Array.isArray(ref) &&\n        (ref as Dict).name === name &&\n        (wanted === null || (ref as Dict).content_sha256 === wanted),\n    );\n    const mode = skillsListingMode(agent);\n    if (refs.length === 0 && mode !== LIST_ALL) {\n      // Skills are listed one at a time once a person shares them, so an\n      // unshared skill has no ref to propose from. Say how to share it rather\n      // than \"not found\".\n      const off =\n        mode === LIST_OFF\n          ? ` (listing is turned off for this agent: ${SKILLS_ADVERTISE_ENV} is set ` +\n            \"to an off or unrecognised value, or the agent is named in \" +\n            \"BOURDON_SKILLS_NO_ADVERTISE)\"\n          : \"\";\n      return {\n        error: \"skill advertising is off\",\n        name,\n        source_agent: agent,\n        detail:\n          \"skills are listed one at a time: a person runs \" +\n          `\\`bourdon skills share ${name}\\` at this machine's terminal, then the ` +\n          \"agent is re-exported and the skill proposed again; to list every \" +\n          `skill instead, set ${SKILLS_ADVERTISE_ENV}=1 where the export runs${off}`,\n      };\n    }\n    if (refs.length === 0) {\n      return {\n        error: \"skill not advertised\",\n        name,\n        source_agent: agent,\n        detail:\n          \"propose a skill that list_skills shows this agent advertising; \" +\n          \"re-export the agent if the skill is new\",\n      };\n    }\n    if (refs.length > 1) {\n      return {\n        error: \"ambiguous skill\",\n        name,\n        source_agent: agent,\n        content_sha256: refs.map((ref) => String(ref.content_sha256)).sort(),\n        detail: \"pass content_sha256 to pick one advertised copy\",\n      };\n    }\n    const ref = refs[0]!;\n    const resolve = options.skillSources ?? skillSourcesForAgent;\n    const sources = resolve(agent);\n    if (!sources || sources.length === 0) {\n      return {\n        error: \"no skill reader\",\n        name,\n        source_agent: agent,\n        detail:\n          \"this machine has no skill reader for that agent, so its \" +\n          \"folder cannot be read for a proposal\",\n      };\n    }\n    const folder = resolveAdvertisedFolder(sources, ref);\n    if (folder === null) {\n      return {\n        error: \"skill folder not found\",\n        name,\n        source_agent: agent,\n        path_hint: ref.path_hint ?? null,\n      };\n    }\n    let content;\n    try {\n      content = readSkillFolder(folder);\n    } catch (exc) {\n      if (exc instanceof SkillContentError) {\n        return {\n          error: \"skill cannot be shared\",\n          name,\n          source_agent: agent,\n          problems: exc.problems,\n          detail:\n            \"shared skills are text-only in v1: SKILL.md plus markdown, \" +\n            \"text and template files\",\n        };\n      }\n      return { error: \"skill folder unreadable\", name, source_agent: agent };\n    }\n    const digest = computeContentSha256(content.files);\n    if (content.frontMatter.name !== name || digest !== ref.content_sha256) {\n      return {\n        error: \"skill changed since it was advertised\",\n        name,\n        source_agent: agent,\n        detail: \"re-export the agent, then propose again\",\n      };\n    }\n\n    const gate = mutationAuditGate(\n      caller,\n      \"propose_skill\",\n      agent,\n      `name=${name} content_sha256=${digest}`,\n    );\n    if (gate !== null) return gate;\n    let outcome;\n    try {\n      outcome = createProposal(store.libraryPath, content, {\n        ref,\n        sourceAgent: agent,\n        proposedBy: caller.agentId,\n        proposerTier: caller.isTrusted ? PROPOSER_TRUSTED : PROPOSER_QUARANTINED,\n      });\n    } catch (exc) {\n      return {\n        error: \"proposal failed\",\n        name,\n        detail: isOsError(exc) ? osErrorDetail(exc) : exc instanceof Error ? exc.message : String(exc),\n      };\n    }\n    const { proposal, created } = outcome;\n    if (created && caller.isTrusted) openAdvisoryBallot(store.libraryPath, proposal);\n    return {\n      ok: true,\n      created,\n      proposal: proposalSummary(proposal),\n      ballot: proposal.ballot,\n      next:\n        \"Pending until a person approves it with `bourdon skills approve \" +\n        `${proposal.proposal_id}\\`. Votes on its ballot are advisory.`,\n    };\n  }\n\n  mcp.registerTool(\n    \"propose_skill\",\n    {\n      title: \"Propose skill\",\n      annotations: ADDS,\n      description:\n        \"Propose one of your advertised skills for the shared skill library.\\n\\n\" +\n        \"Bourdon reads the skill from the folder your own skill reader advertised \" +\n        \"(never a path you pass), checks that it is text-only, and snapshots it into \" +\n        \"a pending proposal, so editing the folder later does not change what gets \" +\n        \"approved. A person approves or rejects it at a terminal \" +\n        \"(`bourdon skills approve`); no tool approves a proposal.\\n\\n\" +\n        \"`content_sha256` picks one advertised copy when you advertise more than one \" +\n        \"skill with this name. `source_agent` is honoured for the local operator \" +\n        \"only; every other caller proposes its own skills. Pending proposals appear \" +\n        \"in `list_skills` as `tier: proposed`.\",\n      inputSchema: {\n        name: z.string(),\n        content_sha256: z.string().nullish(),\n        source_agent: z.string().nullish(),\n      },\n    },\n    (args): CallToolResult => jsonContent(proposeSkill(args)),\n  );\n\n  return mcp;\n}\n\n// -- module-local helpers ------------------------------------------------------\n\n/**\n * Parse the supported extended ISO calendar forms, retaining the supplied day.\n * The store consumes a Date as a UTC calendar cutoff, not as an instant.\n * Invalid input returns null so the tools keep their warning/default fallback.\n */\nfunction parseSince(since: string): Date | null {\n  const match =\n    /^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:Z|([+-])(\\d{2}):?(\\d{2}))?)?$/.exec(\n      since,\n    );\n  if (match === null) return null;\n  const year = Number(match[1]);\n  const month = Number(match[2]);\n  const day = Number(match[3]);\n  if (year < 1 || month < 1 || month > 12 || day < 1 || day > 31) return null;\n  const hour = Number(match[4] ?? 0);\n  const minute = Number(match[5] ?? 0);\n  const second = Number(match[6] ?? 0);\n  const offsetHour = Number(match[9] ?? 0);\n  const offsetMinute = Number(match[10] ?? 0);\n  if (hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) return null;\n\n  // setUTCFullYear avoids Date.UTC's special treatment of years 00 through 99.\n  const cutoff = new Date(0);\n  cutoff.setUTCFullYear(year, month - 1, day);\n  if (\n    cutoff.getUTCFullYear() !== year ||\n    cutoff.getUTCMonth() !== month - 1 ||\n    cutoff.getUTCDate() !== day\n  )\n    return null;\n  return cutoff;\n}\n\n/**\n * Federated recognition with bounded per-peer latency — port of\n * `prepare_recognition_context_federated`. Local recognition fires first\n * (always a valid answer); peers augment under their per-call recognition\n * budget. Slow/failed peers are dropped and reported in `peer_latencies_us`.\n */\nasync function prepareRecognitionContextFederated(\n  store: L6Store,\n  prompt: string,\n  accessLevel = \"team\",\n  includePrivate = false,\n): Promise<Dict> {\n  const local = await prepareRecognitionContextFromStore(store, prompt, accessLevel, includePrivate);\n  if (store.peers.length === 0) {\n    local.peer_latencies_us = {};\n    local.peers_queried = 0;\n    local.peers_responded = 0;\n    local.peers_timed_out = 0;\n    return local;\n  }\n\n  const matchedByKey = new Map<string, Dict>();\n  for (const e of local.matched_entities as Dict[]) {\n    const n = String(e.name ?? \"\");\n    if (n) matchedByKey.set(n.toLowerCase(), e);\n  }\n  const peerLatencies: Record<string, number | null> = {};\n  const extraContextLines: string[] = [];\n  let peersResponded = 0;\n  let peersTimedOut = 0;\n\n  const results = await Promise.all(\n    store.peers.map(async (peer) => {\n      const start = Number(process.hrtime.bigint());\n      let payload: Dict | null = null;\n      let timedOut = false;\n      try {\n        const budgetMs = Math.max(0, peer.recognitionTimeout) * 1000;\n        const work = peer.prepareRecognitionContext(prompt, accessLevel, includePrivate);\n        const timer = new Promise<symbol>((resolve) =>\n          setTimeout(() => resolve(TIMEOUT), budgetMs),\n        );\n        const raced = await Promise.race([work, timer]);\n        if (raced === TIMEOUT) {\n          timedOut = true;\n        } else {\n          payload = raced as Dict;\n        }\n      } catch (exc) {\n        console.warn(`peer ${peer.name} prepare_recognition_context raised: ${String(exc)}`);\n        payload = null;\n      }\n      const latencyUs = Math.round(((Number(process.hrtime.bigint()) - start) / 1000) * 10) / 10;\n      return { name: peer.name, payload, latencyUs: payload ? latencyUs : null, timedOut };\n    }),\n  );\n\n  for (const { name, payload, latencyUs, timedOut } of results) {\n    peerLatencies[name] = latencyUs;\n    if (timedOut) {\n      peersTimedOut += 1;\n      continue;\n    }\n    if (payload === null) continue;\n    peersResponded += 1;\n    for (const ent of (payload.matched_entities as Dict[] | undefined) ?? []) {\n      if (ent === null || typeof ent !== \"object\") continue;\n      const entName = String(ent.name ?? \"\").trim();\n      if (!entName) continue;\n      const taggedAgents = (Array.isArray(ent.source_agents) ? ent.source_agents : [])\n        .filter((a): a is string => typeof a === \"string\")\n        .map((a) => `peer:${name}:${a}`);\n      const key = entName.toLowerCase();\n      const existing = matchedByKey.get(key);\n      if (existing === undefined) {\n        matchedByKey.set(key, {\n          name: entName,\n          type: String(ent.type ?? \"topic\"),\n          source_agents: taggedAgents,\n        });\n      } else {\n        const src = existing.source_agents as string[];\n        for (const a of taggedAgents) if (!src.includes(a)) src.push(a);\n      }\n    }\n    const peerRecognition = String(payload.recognition ?? \"\").trim();\n    if (peerRecognition) extraContextLines.push(`[peer:${name}] ${peerRecognition}`);\n  }\n\n  local.matched_entities = [...matchedByKey.values()];\n  if (extraContextLines.length > 0) {\n    const existingCtx = String(local.prompt_context ?? \"\");\n    local.prompt_context = existingCtx.replace(/\\s+$/, \"\") + \"\\n\" + extraContextLines.join(\"\\n\");\n  }\n  local.peer_latencies_us = peerLatencies;\n  local.peers_queried = store.peers.length;\n  local.peers_responded = peersResponded;\n  local.peers_timed_out = peersTimedOut;\n  return local;\n}\n\nconst TIMEOUT = Symbol(\"timeout\");\n","// SPDX-License-Identifier: BUSL-1.1\n/**\n * Source-attributed agent export — faithful port of `core/agents_export.py`.\n *\n * The single place that turns a directory of `*.l5.yaml` manifests into the\n * stable, redacted `bourdon.agents/v1` JSON shape the desktop tray consumes.\n * The `export_agents` MCP tool calls `exportLocalAgents` here (NOT\n * `L6Store.exportAgents`, which serves the different federated-merge shape).\n *\n * Redaction reuses the `@getbourdon/redaction` SSOT — `_safe_native_memory_text`\n * in Python is a thin wrapper over `redact_text(value, limit=180)`, so the tray\n * never sees a raw credential regardless of session visibility. `source` /\n * `source_kind` are stamped by the caller (this machine), never read from the\n * agent's self-reported manifest.\n *\n * EGRESS visibility gate (3-Star audit P0-1): the peer-facing export path passes\n * `access_level=\"team\"`/`\"public\"` so PRIVATE session content never crosses the\n * federation wire. The default `\"private\"` admits every well-formed session for\n * the operator's own local tray view. Session visibility is resolved by the\n * shared `@getbourdon/l5` visibility policy -- the same one every other egress\n * surface applies -- and an unknown access level throws rather than widening.\n */\n\nimport { readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { liveSessionsByAgent, type LiveSession, type TitleLookup } from \"@getbourdon/federation\";\nimport {\n  effectiveVisibility,\n  filterManifestVisibility,\n  normalizeAccessLevel,\n} from \"@getbourdon/l5\";\nimport { recentSessionThreads, sessionThreadTitles } from \"@getbourdon/participants\";\nimport type { RecentThread } from \"@getbourdon/participants\";\nimport { redactText } from \"@getbourdon/redaction\";\nimport { parse as yamlParse } from \"yaml\";\n\nexport const AGENTS_SCHEMA = \"bourdon.agents/v1\";\nexport const MAX_RECENT_SESSIONS = 10;\n\ntype Dict = Record<string, unknown>;\n\n/**\n * Resolve this machine's label for source attribution. Honors\n * `BOURDON_LOCAL_NAME` (a deployment can pin a stable, friendly label), else\n * `os.hostname()`. Computed at call time so tests can override either source.\n */\nexport function resolveLocalName(): string {\n  const env = process.env.BOURDON_LOCAL_NAME;\n  if (env && env.trim()) return env.trim();\n  return hostname();\n}\n\n/** Run a single emitted string field through the canonical redaction (limit\n * 180). Non-strings pass through untouched. */\nfunction redactField(value: unknown): unknown {\n  if (typeof value === \"string\") return redactText(value, 180);\n  return value;\n}\n\nfunction redactStrList(values: unknown): string[] {\n  if (!Array.isArray(values)) return [];\n  return values.map((item) => redactText(String(item), 180));\n}\n\nfunction sessionDate(session: unknown): string {\n  if (session !== null && typeof session === \"object\" && !Array.isArray(session)) {\n    return String((session as Dict).date ?? \"\");\n  }\n  return \"\";\n}\n\n/**\n * Build one redacted, source-attributed summary from a parsed L5 manifest. The\n * canonical per-agent tray shape plus the two source-attribution fields.\n */\nexport function summarizeAgentManifest(\n  manifest: Dict,\n  opts: { source: string; sourceKind?: string; accessLevel?: string },\n): Dict {\n  const sourceKind = opts.sourceKind ?? \"local\";\n  const level = normalizeAccessLevel(opts.accessLevel ?? \"private\");\n  const agent = (manifest.agent as Dict) || {};\n\n  // Egress visibility gate: drop sessions above the caller's access level so\n  // PRIVATE/TEAM content cannot leak to a peer (3-Star audit P0-1). This is the\n  // shared policy every other egress surface uses -- private tag families, the\n  // manifest's `visibility_policy` and fail-closed handling of malformed\n  // records all apply. `private` (the local default) admits every well-formed\n  // session.\n  const policyValue = manifest.visibility_policy;\n  const policy =\n    policyValue !== null && typeof policyValue === \"object\" && !Array.isArray(policyValue)\n      ? policyValue\n      : null;\n  // Stable sort by date descending (mirrors Python `sorted(..., reverse=True)`).\n  const visibleSessions = [\n    ...(filterManifestVisibility(manifest, level).recent_sessions as Dict[]),\n  ].sort((a, b) => {\n    const da = sessionDate(a);\n    const db = sessionDate(b);\n    return da < db ? 1 : da > db ? -1 : 0;\n  });\n  const recentActivity = visibleSessions.slice(0, MAX_RECENT_SESSIONS).map((session) => ({\n    date: sessionDate(session),\n    project_focus: redactStrList(session.project_focus),\n    key_actions: redactStrList(session.key_actions),\n    visibility: effectiveVisibility(session, policy),\n  }));\n  const freshest = visibleSessions.length > 0 ? sessionDate(visibleSessions[0]) : null;\n\n  const capabilities = manifest.capabilities;\n  const roleNarrative = agent.role_narrative;\n\n  return {\n    id: redactField(String(agent.id ?? \"\")),\n    type: redactField(String(agent.type ?? \"\")) || null,\n    instance: redactField(String(agent.instance ?? \"\")) || null,\n    role_narrative: roleNarrative ? redactField(String(roleNarrative)) : null,\n    last_updated: manifest.last_updated ?? null,\n    capability_count: Array.isArray(capabilities) ? capabilities.length : 0,\n    session_count: visibleSessions.length,\n    freshest_session_date: freshest || null,\n    recent_activity: recentActivity,\n    parse_error: null,\n    source: opts.source,\n    source_kind: sourceKind,\n  };\n}\n\n/** Partial-failure entry so the tray can represent a broken manifest. */\nexport function errorAgentEntry(\n  agentId: string,\n  message: string,\n  opts: { source: string; sourceKind?: string },\n): Dict {\n  return {\n    id: agentId,\n    type: null,\n    instance: null,\n    role_narrative: null,\n    last_updated: null,\n    capability_count: null,\n    session_count: null,\n    freshest_session_date: null,\n    recent_activity: [],\n    parse_error: message,\n    source: opts.source,\n    source_kind: opts.sourceKind ?? \"local\",\n  };\n}\n\n/**\n * Enrich each agent row in place with live-session presence — port of\n * `_join_live_presence()` in `core/agents_export.py`.\n *\n * Adds `live_sessions` (a possibly-empty list of {instance, title, host,\n * project, started_at, age_s}) and `live_count` to every agent, read from\n * `~/.bourdon/presence` via `@getbourdon/federation`. Presence is ephemeral and\n * orthogonal to the durable L5 manifests. Best-effort: a read failure never\n * sinks the export — every agent just gets `live_count=0`.\n *\n * EGRESS GATE (parity with the per-session access gate): presence reveals what\n * you are actively working on *right now* (project, host). It is emitted for\n * the local tray (`private`) and for TRUSTED team peers (`team`) — the latter\n * is what makes the federated cross-machine live-session view work — but NEVER\n * for a `public`/untrusted caller, who gets `live_count=0` and for whom the\n * presence directory is not read at all.\n *\n * An agent with live sessions but NO L5 manifest yet (registered before its\n * first export) gets a minimal synthesized row — a running session must never\n * be invisible in the tray. Synthesized rows carry only the id + live fields\n * (`session_count` 0, no durable data to show).\n *\n * Live sessions carry a human `title` when one can be resolved — see\n * {@link codexTitleLookup}. The title is redacted on the way out like every\n * other emitted string.\n */\n/**\n * Build a `(agentId, sessionId) -> title` resolver for presence — port of\n * `_codex_title_lookup()` in `core/agents_export.py`.\n *\n * Titles come from the Codex/ChatGPT-app `session_index.jsonl` (`thread_name`)\n * — the app's Work and Codex modes share `~/.codex`, so one lookup covers both.\n * Only agents whose base id is `codex` are resolved; other agents' session ids\n * live in other namespaces. The index is read ONCE per export (the closure\n * captures the map), not once per session.\n *\n * Returns `null` (no lookup at all) when the map can't be built or is empty —\n * presence then behaves exactly as it did before titles existed.\n *\n * SECURITY: the resolver receives the FULL session id, which is the whole point\n * — it is invoked inside `summarize()`, the one place the full id is still in\n * hand, so a title can be carried out while only the 8-char `instance` prefix\n * ever egresses. The returned title is RAW USER TEXT and is redacted by the\n * caller (`attach()` below) before it reaches a peer.\n */\nexport function codexTitleLookup(): TitleLookup | null {\n  let titles: Record<string, string>;\n  try {\n    titles = sessionThreadTitles();\n  } catch {\n    return null; // titles are decoration, never fatal\n  }\n  if (Object.keys(titles).length === 0) return null;\n\n  return (agentId: string, sessionId: string): string | null => {\n    const base = agentId.endsWith(\"-automations\")\n      ? agentId.slice(0, agentId.length - \"-automations\".length)\n      : agentId;\n    if (base !== \"codex\") return null;\n    return titles[sessionId] ?? null;\n  };\n}\n\n/**\n * Attach `recent_threads` to the local `codex` agent row.\n *\n * `[{instance, title, updated_at}]` from `session_index.jsonl` — the titled\n * thread list a ChatGPT-app user recognizes, INDEPENDENT of presence (app\n * threads fire no presence hooks, so a thread can appear here with no live\n * session at all).\n *\n * Same EGRESS GATE as live presence: thread titles reveal what the user is\n * working on, so they are emitted for `private`/`team` and NEVER for `public`.\n * Titles route through the audited redaction pipeline. Best-effort: any failure\n * leaves rows untouched (the field is optional in the contract).\n */\nfunction joinCodexThreads(agents: Dict[], accessLevel: string): void {\n  // EGRESS GATE — returns BEFORE any Codex read. Nothing below may be hoisted.\n  if (accessLevel === \"public\") return;\n\n  let threads: RecentThread[];\n  try {\n    threads = recentSessionThreads();\n  } catch {\n    return; // decoration, never fatal\n  }\n  if (threads.length === 0) return;\n\n  for (const thread of threads) {\n    if (thread.title) thread.title = (redactField(String(thread.title)) as string) || null;\n  }\n  for (const agent of agents) {\n    if (String(agent.id ?? \"\") === \"codex\") {\n      agent.recent_threads = threads;\n      return;\n    }\n  }\n}\n\nfunction joinLivePresence(agents: Dict[], accessLevel: string, source: string): void {\n  // EGRESS GATE — returns BEFORE any presence read AND before any Codex read.\n  // Nothing below this block may be hoisted above it.\n  if (accessLevel === \"public\") {\n    for (const agent of agents) {\n      agent.live_sessions = [];\n      agent.live_count = 0;\n    }\n    return;\n  }\n\n  let byAgent: Record<string, LiveSession[]> = {};\n  try {\n    byAgent = liveSessionsByAgent({ titleLookup: codexTitleLookup() });\n  } catch {\n    byAgent = {}; // presence is best-effort, never fatal\n  }\n\n  const attach = (agent: Dict, sessions: LiveSession[]): void => {\n    for (const session of sessions) {\n      // Route presence strings through the same audited redaction pipeline\n      // every other exported field uses (project = cwd basename, host =\n      // hostname, title = thread name) — don't let presence bypass it on the\n      // way to a peer.\n      if (session.project) session.project = redactField(String(session.project));\n      if (session.host) session.host = redactField(String(session.host));\n      if (session.title) session.title = (redactField(String(session.title)) as string) || null;\n    }\n    agent.live_sessions = sessions;\n    agent.live_count = sessions.length;\n  };\n\n  const seen = new Set<string>();\n  for (const agent of agents) {\n    const agentId = String(agent.id ?? \"\");\n    seen.add(agentId);\n    attach(agent, byAgent[agentId] ?? []);\n  }\n\n  for (const [agentId, sessions] of Object.entries(byAgent)) {\n    if (seen.has(agentId)) continue;\n    // The id originates from a presence file (hook-supplied), so it goes\n    // through the same redaction pipeline as every other exported string —\n    // manifest rows get this in summarizeAgentManifest.\n    const row = errorAgentEntry(String(redactField(agentId)), \"\", { source });\n    row.parse_error = null; // not an error — just no manifest yet\n    row.session_count = 0;\n    attach(row, sessions);\n    agents.push(row);\n  }\n}\n\n/**\n * Summarize every local `*.l5.yaml` manifest into the tray envelope. Agents are\n * sorted by live-now then `last_updated` descending; per-manifest parse failures\n * are represented inline (`parse_error`) rather than raised, so one broken file\n * never sinks the whole export.\n */\nexport function exportLocalAgents(\n  agentsDir: string,\n  localName: string,\n  accessLevel = \"private\",\n): Dict {\n  // Refuse an unknown level up front rather than per manifest: every gate\n  // below (sessions, presence, threads) compares against the canonical value.\n  const level = normalizeAccessLevel(accessLevel);\n  const agents: Dict[] = [];\n  let isDir = false;\n  try {\n    isDir = statSync(agentsDir).isDirectory();\n  } catch {\n    isDir = false;\n  }\n  if (isDir) {\n    let manifestPaths: string[] = [];\n    try {\n      manifestPaths = readdirSync(agentsDir)\n        .filter((f) => f.endsWith(\".l5.yaml\"))\n        .filter((f) => {\n          try {\n            return statSync(join(agentsDir, f)).isFile();\n          } catch {\n            return false;\n          }\n        })\n        .sort();\n    } catch {\n      manifestPaths = [];\n    }\n    for (const fname of manifestPaths) {\n      const path = join(agentsDir, fname);\n      const stem = fname.slice(0, fname.length - \".l5.yaml\".length);\n      let text: string;\n      try {\n        text = readFileSync(path, \"utf8\");\n      } catch (exc) {\n        agents.push(errorAgentEntry(stem, String(exc), { source: localName }));\n        continue;\n      }\n      let loaded: unknown;\n      try {\n        loaded = yamlParse(text);\n      } catch (exc) {\n        agents.push(errorAgentEntry(stem, String(exc), { source: localName }));\n        continue;\n      }\n      if (loaded === null || typeof loaded !== \"object\" || Array.isArray(loaded)) {\n        agents.push(\n          errorAgentEntry(stem, \"manifest is not a YAML mapping\", { source: localName }),\n        );\n        continue;\n      }\n      try {\n        agents.push(\n          summarizeAgentManifest(loaded as Dict, { source: localName, accessLevel: level }),\n        );\n      } catch (exc) {\n        agents.push(errorAgentEntry(stem, String(exc), { source: localName }));\n      }\n    }\n  }\n\n  joinLivePresence(agents, level, localName);\n  joinCodexThreads(agents, level);\n\n  // Live-now outranks stale recency: without the live_count key, an agent that\n  // is live RIGHT NOW but has no manifest yet (synthesized row, last_updated\n  // null) would sort beneath months-stale entries. Mirrors the Python\n  // `key=(live_count > 0, last_updated), reverse=True` tuple sort. Stable —\n  // preserves glob order on ties.\n  agents.sort((a, b) => {\n    const liveA = Number(a.live_count ?? 0) > 0 ? 1 : 0;\n    const liveB = Number(b.live_count ?? 0) > 0 ? 1 : 0;\n    if (liveA !== liveB) return liveB - liveA;\n    const la = String(a.last_updated ?? \"\");\n    const lb = String(b.last_updated ?? \"\");\n    return la < lb ? 1 : la > lb ? -1 : 0;\n  });\n\n  return {\n    schema: AGENTS_SCHEMA,\n    machine: localName,\n    generated_from: agentsDir,\n    agents,\n  };\n}\n","// SPDX-License-Identifier: BUSL-1.1\n/**\n * Read side of federated procedural memory: the `list_skills` / `get_skill`\n * payloads. Port of the engine's `core/skill_tools.py` (plan 005, phase 3).\n *\n * Two kinds of skill reach a caller:\n *\n *  - **shared** -- promoted into the library's skill store (`promoteSkill` in\n *    `@getbourdon/participants`). Org tier: readable by every caller allowed to\n *    read the federation, writable only by promotion. Each row carries its\n *    provenance (`source_agent`, `promoted_by`, `version`, `content_sha256`)\n *    and its own `visibility`.\n *  - **advertised** -- a SkillRef an agent lists in its L5 manifest (discovery\n *    only). Refs with the same `content_sha256` are one row naming every agent\n *    that advertises them.\n *\n * A body is served only for a shared skill. An advertised skill is never read\n * from an agent's folder over MCP: {@link getSkillPayload} returns its index\n * data and says it must be promoted first.\n *\n * The functions here are pure over a store and two caller-derived inputs (the\n * clamped access level and a namespace predicate), so the server's\n * authorization stays in one place (`server.ts`) and the payloads are testable\n * without a transport.\n */\n\nimport { type L6Store, collectAdvertisedSkills } from \"@getbourdon/federation\";\nimport { normalizeAccessLevel } from \"@getbourdon/l5\";\nimport {\n  MAX_REFERENCE_FILE_BYTES,\n  MAX_SKILL_BODY_BYTES,\n  MAX_SKILL_TOTAL_BYTES,\n  SKILL_BODY_NAME,\n  SkillContentError,\n  SkillIndexError,\n  type SkillIndexRow,\n  SkillNotFoundError,\n  codePointSlice,\n  computeContentSha256,\n  getSkillRow,\n  listSkillRows,\n  pyStrip,\n  readSharedSkill,\n  validateSkillName,\n} from \"@getbourdon/participants\";\n\ntype Dict = Record<string, unknown>;\n\nexport const TIER_SHARED = \"shared\";\nexport const TIER_ADVERTISED = \"advertised\";\n/** A skill proposed for the shared library and awaiting a person's approval\n * (plan 005, phase 4). */\nexport const TIER_PROPOSED = \"proposed\";\n/** An advertised copy compared with the shared library: same bytes, or a\n * different version of a skill that is shared under the same name. */\nexport const STATUS_MATCHES = \"matches\";\nexport const STATUS_DIVERGED = \"diverged\";\nexport const MAX_QUERY_CHARS = 200;\n\nexport const PROMOTE_FIRST_MESSAGE =\n  \"This skill is advertised by an agent but is not in the shared library. \" +\n  \"Its body is served only after it is promoted into the shared library.\";\nexport const FILES_WITHHELD_MESSAGE =\n  \"Reference file contents are not served to quarantined callers.\";\n\nconst ACCESS_RANK: Record<string, number> = { public: 0, team: 1, private: 2 };\n\nfunction visibleAt(visibility: string, accessLevel: string): boolean {\n  const rank = Object.hasOwn(ACCESS_RANK, visibility) ? ACCESS_RANK[visibility]! : 3;\n  return rank <= ACCESS_RANK[accessLevel]!;\n}\n\nfunction sharedRow(row: SkillIndexRow): Dict {\n  const out: Dict = { tier: TIER_SHARED, ...row.toDict() };\n  delete out.spec_version;\n  return out;\n}\n\n/** Python's str order (code points), via the UTF-8 bytes. */\nfunction compareText(a: string, b: string): number {\n  return Buffer.compare(Buffer.from(a, \"utf8\"), Buffer.from(b, \"utf8\"));\n}\n\nfunction isDict(value: unknown): value is Dict {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Live, unretired shared rows whose `visibility` is within `accessLevel`. */\nexport function visibleSharedRows(libraryPath: string, accessLevel: string): SkillIndexRow[] {\n  const level = normalizeAccessLevel(accessLevel);\n  return listSkillRows(libraryPath).filter((row) => visibleAt(row.visibility, level));\n}\n\nfunction readableManifests(\n  store: L6Store,\n  accessLevel: string,\n  mayRead: (agentId: string) => boolean,\n): Map<string, Dict> {\n  const manifests = new Map<string, Dict>();\n  for (const agentId of store.listAgents()) {\n    if (!mayRead(agentId)) continue;\n    const manifest = store.getAgentManifest(agentId, false, accessLevel);\n    if (manifest !== null) manifests.set(agentId, manifest);\n  }\n  return manifests;\n}\n\n/** Prefer an `installed` origin (it carries the source) over `authored`. */\nfunction mergeOrigin(current: unknown, candidate: unknown): unknown {\n  if (!isDict(candidate)) return current;\n  if (!isDict(current)) return { ...candidate };\n  if (current.kind !== \"installed\" && candidate.kind === \"installed\") return { ...candidate };\n  return current;\n}\n\nexport interface SkillReadScope {\n  accessLevel: string;\n  mayRead: (agentId: string) => boolean;\n}\n\n/**\n * Advertised refs the caller may read, one row per `content_sha256`.\n *\n * Only namespaces `mayRead` admits are read, and each manifest is\n * visibility-filtered at `accessLevel` before a ref is looked at. A row names\n * every agent advertising those bytes (`advertised_by`). `shared` (rows the\n * caller may see) adds a `shared` comparison: `matches` when the bytes equal a\n * shared version's, `diverged` when a shared skill has the same name but other\n * bytes.\n */\nexport function advertisedSkillRows(\n  store: L6Store,\n  scope: SkillReadScope & { shared?: readonly SkillIndexRow[] },\n): Dict[] {\n  const level = normalizeAccessLevel(scope.accessLevel);\n  const refs = collectAdvertisedSkills(readableManifests(store, level, scope.mayRead));\n  const grouped = new Map<string, Dict & { advertised_by: string[] }>();\n  const order: string[] = [];\n  for (const ref of refs) {\n    const digest = ref.content_sha256;\n    const name = ref.name;\n    if (typeof digest !== \"string\" || typeof name !== \"string\") continue;\n    let row = grouped.get(digest);\n    if (row === undefined) {\n      row = {\n        tier: TIER_ADVERTISED,\n        name,\n        description: ref.description ?? \"\",\n        content_sha256: digest,\n        advertised_by: [],\n      };\n      grouped.set(digest, row);\n      order.push(digest);\n    }\n    const advertisers = Array.isArray(ref.advertised_by) ? ref.advertised_by : [];\n    for (const agent of advertisers) {\n      if (!row.advertised_by.includes(agent as string)) row.advertised_by.push(agent as string);\n    }\n    const origin = mergeOrigin(row.origin, ref.origin);\n    if (origin !== undefined && origin !== null) row.origin = origin;\n  }\n  const shared = scope.shared ?? [];\n  const byHash = new Map(shared.map((row) => [row.contentSha256, row]));\n  const byName = new Map(shared.map((row) => [row.name, row]));\n  const rows: Dict[] = [];\n  for (const digest of order) {\n    const row = grouped.get(digest)!;\n    row.advertised_by = [...row.advertised_by].sort(compareText);\n    const sameBytes = byHash.get(digest);\n    const sameName = byName.get(row.name as string);\n    if (sameBytes !== undefined) {\n      row.shared = { name: sameBytes.name, status: STATUS_MATCHES };\n    } else if (sameName !== undefined) {\n      row.shared = { name: sameName.name, status: STATUS_DIVERGED };\n    }\n    rows.push(row);\n  }\n  return rows.sort(\n    (a, b) =>\n      compareText(a.name as string, b.name as string) ||\n      compareText(a.content_sha256 as string, b.content_sha256 as string),\n  );\n}\n\n/** Approximates Python `str.casefold()` (full case folding). */\nfunction casefold(text: string): string {\n  return text.toUpperCase().toLowerCase();\n}\n\nfunction matchesQuery(row: Dict, needle: string): boolean {\n  if (!needle) return true;\n  const haystack = casefold(`${String(row.name ?? \"\")}\\n${String(row.description ?? \"\")}`);\n  return haystack.includes(needle);\n}\n\n/** The `list_skills` response: shared rows first, then advertised rows. */\nexport function listSkillsPayload(\n  store: L6Store,\n  options: SkillReadScope & {\n    query?: string | null;\n    includeLocal?: boolean;\n    /** Pending proposal summaries the server already decided this caller may\n     * see; each becomes a `proposed` row. */\n    proposals?: readonly Dict[];\n  },\n): Dict {\n  const level = normalizeAccessLevel(options.accessLevel);\n  const query = options.query ?? null;\n  const includeLocal = options.includeLocal ?? true;\n  const needle = codePointSlice(casefold(pyStrip(query ?? \"\")), MAX_QUERY_CHARS);\n  const shared = visibleSharedRows(store.libraryPath, level);\n  let rows: Dict[] = shared.map(sharedRow);\n  if (includeLocal) {\n    rows.push(...advertisedSkillRows(store, { accessLevel: level, mayRead: options.mayRead, shared }));\n  }\n  for (const item of options.proposals ?? []) rows.push({ tier: TIER_PROPOSED, ...item });\n  rows = rows.filter((row) => matchesQuery(row, needle));\n  return {\n    query,\n    include_local: includeLocal,\n    access_level: level,\n    skills: rows,\n    count: rows.length,\n  };\n}\n\nfunction notFound(name: string): Dict {\n  return { error: \"skill not found\", name };\n}\n\nconst UTF8 = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\nfunction decodeText(data: Uint8Array): string | null {\n  try {\n    return UTF8.decode(data);\n  } catch {\n    return null;\n  }\n}\n\n/** A Node filesystem error (Python's `OSError`). */\nfunction isOsError(err: unknown): boolean {\n  return err instanceof Error && typeof (err as NodeJS.ErrnoException).code === \"string\";\n}\n\n/**\n * The `get_skill` response.\n *\n * A shared skill the caller may see returns its provenance, its `SKILL.md`\n * text as `body` and, with `includeFiles`, its reference files (`file` and\n * size; the text too when `serveFileContents`). The stored bytes are re-hashed\n * before anything is served, and a version whose bytes do not match its row,\n * or exceed the store's size caps, is refused. A retired skill is served only\n * by explicit `version`.\n *\n * A name that is not shared but that a readable agent advertises returns the\n * advertised rows and {@link PROMOTE_FIRST_MESSAGE}, never a body. A name the\n * caller cannot see is reported exactly like a name that does not exist.\n */\nexport function getSkillPayload(\n  store: L6Store,\n  name: string,\n  options: SkillReadScope & {\n    version?: number | null;\n    includeFiles?: boolean;\n    serveFileContents?: boolean;\n  },\n): Dict {\n  const level = normalizeAccessLevel(options.accessLevel);\n  const version = options.version ?? null;\n  try {\n    validateSkillName(name);\n  } catch (err) {\n    if (err instanceof SkillIndexError) {\n      return { error: \"invalid skill name\", name, detail: err.message };\n    }\n    throw err;\n  }\n  if (version !== null && (typeof version !== \"number\" || !Number.isInteger(version) || version < 1)) {\n    return { error: \"invalid version\", name, version };\n  }\n\n  let row: SkillIndexRow | null = null;\n  let liveRow: SkillIndexRow | null = null;\n  let files: ReadonlyArray<readonly [string, Uint8Array]> = [];\n  try {\n    const read = readSharedSkill(store.libraryPath, name, version);\n    row = read.row;\n    files = read.content.files;\n    liveRow = version === null ? row : getSkillRow(store.libraryPath, name);\n  } catch (err) {\n    if (err instanceof SkillNotFoundError) {\n      row = null;\n    } else if (err instanceof SkillIndexError || err instanceof SkillContentError || isOsError(err)) {\n      return { error: \"skill unavailable\", name };\n    } else {\n      throw err;\n    }\n  }\n\n  if (\n    row !== null &&\n    liveRow !== null &&\n    visibleAt(liveRow.visibility, level) &&\n    visibleAt(row.visibility, level)\n  ) {\n    if (version === null && !row.isActive()) {\n      return {\n        error: \"skill retired\",\n        name,\n        valid_to: row.validTo,\n        version: row.version,\n        detail: \"a retired skill is served only by explicit version\",\n      };\n    }\n    return sharedBody(\n      row,\n      files,\n      options.includeFiles ?? false,\n      options.serveFileContents ?? true,\n    );\n  }\n\n  if (version !== null) return notFound(name);\n  const shared = visibleSharedRows(store.libraryPath, level);\n  const advertised = advertisedSkillRows(store, {\n    accessLevel: level,\n    mayRead: options.mayRead,\n    shared,\n  }).filter((r) => r.name === name);\n  if (advertised.length === 0) return notFound(name);\n  return {\n    name,\n    tier: TIER_ADVERTISED,\n    status: \"not_promoted\",\n    message: PROMOTE_FIRST_MESSAGE,\n    advertised,\n  };\n}\n\nfunction sharedBody(\n  row: SkillIndexRow,\n  files: ReadonlyArray<readonly [string, Uint8Array]>,\n  includeFiles: boolean,\n  serveFileContents: boolean,\n): Dict {\n  const unavailable: Dict = { error: \"skill unavailable\", name: row.name, version: row.version };\n  if (computeContentSha256(files) !== row.contentSha256) {\n    return { ...unavailable, detail: \"stored files do not match content_sha256\" };\n  }\n  const bodyBytes = files.find(([rel]) => rel === SKILL_BODY_NAME)?.[1];\n  if (bodyBytes === undefined || bodyBytes.length > MAX_SKILL_BODY_BYTES) {\n    return { ...unavailable, detail: \"SKILL.md is missing or over the size cap\" };\n  }\n  if (files.reduce((sum, [, data]) => sum + data.length, 0) > MAX_SKILL_TOTAL_BYTES) {\n    return { ...unavailable, detail: \"skill is over the total size cap\" };\n  }\n  const body = decodeText(bodyBytes);\n  if (body === null) return { ...unavailable, detail: \"SKILL.md is not UTF-8 text\" };\n  const out = sharedRow(row);\n  out.body = body;\n  const references = files.filter(([rel]) => rel !== SKILL_BODY_NAME);\n  out.file_count = references.length;\n  if (includeFiles) {\n    const listed: Dict[] = [];\n    for (const [rel, data] of references) {\n      const item: Dict = { file: rel, bytes: data.length };\n      if (serveFileContents) {\n        const text = decodeText(data);\n        if (text === null || data.length > MAX_REFERENCE_FILE_BYTES) {\n          return { ...unavailable, detail: `${rel} is not servable text` };\n        }\n        item.text = text;\n      }\n      listed.push(item);\n    }\n    out.files = listed;\n    if (!serveFileContents) out.files_note = FILES_WITHHELD_MESSAGE;\n  }\n  return out;\n}\n","// SPDX-License-Identifier: BUSL-1.1\n/**\n * Participant drift alerts for the recognition path — the TS mirror of the\n * oracle's `core.drift_context` + the alert-reading half of\n * `core.participant_watermark`.\n *\n * A participant that can still OPEN its native store but no longer PARSE it\n * yields nothing while every presence check stays green. The export path\n * persists a per-participant watermark verdict; this module reads those\n * verdicts back and renders the active `drift` ones as bounded\n * `{agent, checked_at, reason}` rows for `prepare_recognition_context`.\n *\n * State is advisory and untrusted: missing, malformed, and unrecognized\n * entries fail open (no alert), and every field is bounded through the\n * redaction SSOT before it can reach a prompt.\n */\n\nimport { readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { bourdonHome } from \"@getbourdon/federation\";\nimport { redactText } from \"@getbourdon/redaction\";\n\nconst WATERMARK_DIRNAME = \"participants\";\nconst MAX_WATERMARK_FILES = 64;\nconst MAX_ACTIVE_DRIFT_ALERTS = 5;\nconst MAX_VERDICT_REASON_CHARS = 500;\n\n/** Closed verdict set — `ok` and `idle` are healthy, `drift` is not. */\nconst VERDICTS = new Set([\"ok\", \"idle\", \"drift\"]);\nconst DRIFT = \"drift\";\n\nconst AGENT_CHARS = 60;\nconst CHECKED_AT_CHARS = 40;\n\n/** The MCP recognition response's per-alert reason budget, matching every\n * other MCP context fragment. */\nexport const MCP_DRIFT_REASON_CHARS = 240;\n\nexport interface DriftAlert {\n  agent: string;\n  checked_at: string;\n  reason: string;\n}\n\nfunction watermarkDir(): string {\n  return join(bourdonHome(), WATERMARK_DIRNAME);\n}\n\n/** Read one watermark file's alert-relevant fields. Anything unreadable or\n * out-of-contract degrades to \"no alert\", never an exception. */\nfunction readAlert(dir: string, file: string): DriftAlert | null {\n  let raw: unknown;\n  try {\n    raw = JSON.parse(readFileSync(join(dir, file), \"utf8\"));\n  } catch {\n    return null;\n  }\n  if (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n  const record = raw as Record<string, unknown>;\n  const verdict = typeof record.last_verdict === \"string\" && VERDICTS.has(record.last_verdict)\n    ? record.last_verdict\n    : \"\";\n  if (verdict !== DRIFT) return null;\n  const checkedAt =\n    typeof record.last_check_at === \"string\" ? record.last_check_at.slice(0, CHECKED_AT_CHARS) : \"\";\n  if (!checkedAt) return null;\n  const reason =\n    typeof record.last_verdict_reason === \"string\"\n      ? record.last_verdict_reason.slice(0, MAX_VERDICT_REASON_CHARS)\n      : \"\";\n  // The agent id is the filename stem — the same sanitized token the writer\n  // used, so a hostile id cannot smuggle path separators back in.\n  return { agent: file.replace(/\\.json$/, \"\"), checked_at: checkedAt, reason };\n}\n\n/** Newest-first active drift verdicts from bounded local state. */\nexport function activeDriftAlerts(): DriftAlert[] {\n  let files: string[];\n  try {\n    files = readdirSync(watermarkDir())\n      .filter((f) => f.endsWith(\".json\"))\n      .sort()\n      .slice(0, MAX_WATERMARK_FILES);\n  } catch {\n    return [];\n  }\n\n  const alerts: DriftAlert[] = [];\n  for (const file of files) {\n    const alert = readAlert(watermarkDir(), file);\n    if (alert) alerts.push(alert);\n  }\n\n  // Stable two-pass ordering: newest first, agent id as the deterministic\n  // tie-breaker.\n  alerts.sort((a, b) => (a.agent < b.agent ? -1 : a.agent > b.agent ? 1 : 0));\n  alerts.sort((a, b) => (a.checked_at < b.checked_at ? 1 : a.checked_at > b.checked_at ? -1 : 0));\n  return alerts.slice(0, MAX_ACTIVE_DRIFT_ALERTS);\n}\n\n/** Active drift alerts with every field bounded through the redaction SSOT.\n * Alerts whose agent collapses to empty are dropped: a drift warning that\n * cannot say which surface drifted is noise. */\nexport function boundedActiveAlerts(reasonLimit: number): DriftAlert[] {\n  const bounded: DriftAlert[] = [];\n  for (const alert of activeDriftAlerts()) {\n    const agent = redactText(alert.agent, AGENT_CHARS);\n    if (!agent) continue;\n    bounded.push({\n      agent,\n      checked_at: redactText(alert.checked_at, CHECKED_AT_CHARS),\n      reason: redactText(alert.reason, reasonLimit),\n    });\n  }\n  return bounded;\n}\n\n/** The recognition response's drift rows: present only when non-empty, and\n * degrading to absent when the watermark state is unreadable. */\nexport function driftingSurfaces(): DriftAlert[] {\n  try {\n    return boundedActiveAlerts(MCP_DRIFT_REASON_CHARS);\n  } catch (exc) {\n    console.warn(`could not read participant drift state: ${String(exc)}`);\n    return [];\n  }\n}\n","{\n  \"name\": \"@getbourdon/mcp-server\",\n  \"version\": \"0.16.0\",\n  \"mcpName\": \"ai.bourdon/bourdon\",\n  \"description\": \"Bourdon L6 MCP server (BUSL-1.1) — the facade over @getbourdon/federation that exposes the federation natively to any MCP-aware agent (Claude Code, Codex, Cursor). Faithful port of core/l6_server.py on @modelcontextprotocol/sdk. WIRE-COMPATIBLE with the Python server BOTH directions: every tool returns JSON-in-TextContent (text = JSON.stringify(payload)) so a Python RemoteL6Client's json.loads(item.text) recovers it. 15 tools + 3 resources, the public/team access_level default split, the Bearer/AsyncLocalStorage auth middleware (empty-Bearer never authenticates, HTTP-bypass -> quarantined fail-closed), stdio-first transport, and the loopback-only non-auth bind refusal. Python (pip install bourdon) is the oracle; asserts against @getbourdon/conformance mcp_snapshots.\",\n  \"license\": \"BUSL-1.1\",\n  \"type\": \"module\",\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.js\",\n  \"types\": \"./dist/index.d.ts\",\n  \"bin\": {\n    \"bourdon-l6-server\": \"./dist/cli.js\"\n  },\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.js\",\n      \"require\": \"./dist/index.cjs\"\n    },\n    \"./package.json\": \"./package.json\"\n  },\n  \"files\": [\n    \"dist\",\n    \"LICENSE\",\n    \"LICENSE_FAQ.md\"\n  ],\n  \"engines\": {\n    \"node\": \">=24.0.0\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true\n  },\n  \"homepage\": \"https://bourdon.ai\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://gitlab.com/bourdonai/bourdon-js.git\",\n    \"directory\": \"packages/mcp-server\"\n  },\n  \"scripts\": {\n    \"build\": \"tsup\",\n    \"smoke\": \"node dist/cli.js --help && node dist/cli.js --version && node scripts/smoke.mjs dedicated\",\n    \"test\": \"vitest run\"\n  },\n  \"dependencies\": {\n    \"@getbourdon/federation\": \"workspace:*\",\n    \"@getbourdon/inference\": \"workspace:*\",\n    \"@getbourdon/l5\": \"workspace:*\",\n    \"@getbourdon/participants\": \"workspace:*\",\n    \"@getbourdon/recognition\": \"workspace:*\",\n    \"@getbourdon/redaction\": \"workspace:*\",\n    \"@modelcontextprotocol/sdk\": \"^1.31.0\",\n    \"yaml\": \"^2.6.1\",\n    \"zod\": \"^4.4.3\"\n  },\n  \"devDependencies\": {\n    \"@getbourdon/conformance\": \"workspace:*\"\n  }\n}\n","// SPDX-License-Identifier: BUSL-1.1\nimport packageManifest from \"../package.json\" with { type: \"json\" };\n\n/** The version this package ships as, embedded from its own manifest at build time. */\nexport const PACKAGE_VERSION: string = packageManifest.version;\n","// SPDX-License-Identifier: BUSL-1.1\n/**\n * Recognition / context helpers for the L6 MCP tools — faithful port of the\n * module-level functions in `core/l6_server.py`\n * (`prepare_recognition_context_from_store`, `_recognition_prompt_context`,\n * `get_deeper_context_for_prompt`, `compile_codex_turn_from_store`).\n *\n * Thin glue between `@getbourdon/federation` (L6Store) and\n * `@getbourdon/recognition` (recognitionFirst). No business logic of its own.\n */\n\nimport { join } from \"node:path\";\n\nimport { L6Store, bourdonHome } from \"@getbourdon/federation\";\nimport { compileCodexTurn, queryL2, turnBriefToDict } from \"@getbourdon/inference\";\nimport {\n  DEFAULT_HYDRATION_TIMEOUT,\n  MAX_RECOGNITION_ANCHORS,\n  assembleLocalContext,\n  buildLocalPayload,\n  recognitionFirst,\n} from \"@getbourdon/recognition\";\nimport { redactText } from \"@getbourdon/redaction\";\n\ntype Dict = Record<string, unknown>;\n\n/**\n * The L1 synopsis directory, mirroring `orchestrator.L1_DIR`:\n * `BOURDON_L1_DIR` overrides; default `~/.bourdon/l1` (BOURDON_HOME honored).\n */\nexport function resolveL1Dir(): string {\n  const override = process.env.BOURDON_L1_DIR;\n  if (override) return override;\n  // bourdonHome() is the ONE home-resolution seam (presence + watermarks use\n  // it) -- re-deriving it here would drift the L1 dir the day it gains a rule.\n  return join(bourdonHome(), \"l1\");\n}\n\n/** Thin wrapper over the redaction SSOT (MCP recognition context budget, 240). */\nfunction safeContextText(value: string, limit = 240): string {\n  return redactText(value, limit);\n}\n\n/**\n * Redaction budget for the recognition string inside the prompt context\n * (`RECOGNITION_CONTEXT_CHARS`). The string carries a one-line gloss per named\n * anchor (up to three) since oracle 0.21.0, so the old 240-character cap would\n * cut it mid-sentence.\n */\nexport const RECOGNITION_CONTEXT_CHARS = 1_200;\n\n/**\n * The turn-start fragment an agent prepends to its own prompt.\n *\n * The recognition string already says what each named anchor is and how current\n * that knowledge is, so it is quoted WHOLE (redacted line by line, bounded)\n * rather than restated as a \"Matched entities:\" list. The provenance line\n * underneath says which agents know each matched entity; that is the part\n * recognition leaves out on purpose.\n */\nexport function recognitionPromptContext(result: {\n  recognition: string;\n  matchedEntities: Dict[];\n}): string {\n  if (!result.recognition) return \"\";\n\n  // Redact line by line: the redactors collapse whitespace, and the recognition\n  // string's structure (one anchor per line) is part of what makes it readable\n  // at the top of a prompt.\n  const lines: string[] = [\"Bourdon recognition context\"];\n  for (const line of result.recognition.split(\"\\n\")) {\n    if (line.trim()) lines.push(safeContextText(line, RECOGNITION_CONTEXT_CHARS));\n  }\n  // Bounded to the anchors the recognition string names, in the same ranked\n  // order; the rest are already counted by \"Also matched: N more.\".\n  const provenance: string[] = [];\n  for (const entity of result.matchedEntities.slice(0, MAX_RECOGNITION_ANCHORS)) {\n    const name = safeContextText(String(entity.name ?? \"\"));\n    const sourceAgents = (Array.isArray(entity.source_agents) ? entity.source_agents : []).filter(\n      (a): a is string => typeof a === \"string\" && a.length > 0,\n    );\n    if (name && sourceAgents.length > 0) {\n      provenance.push(`${name} via ${sourceAgents.join(\", \")}`);\n    }\n  }\n  if (provenance.length > 0) lines.push(`Known by: ${provenance.join(\"; \")}.`);\n  lines.push(\"Use this as timing-layer context, not as a final answer.\");\n  return lines.join(\"\\n\");\n}\n\n/**\n * One matched entity as the MCP payload reports it (`_matched_entity_row`).\n *\n * `name`/`type`/`source_agents` are the historical shape. `confidence` is the\n * per-entity bucket; `also_known_as` lists the names this row absorbed when\n * duplicates of the same thing were clustered, so a caller can still see that\n * \"Continuo\" matched even though it is no longer its own row. `formerly` lists\n * superseded names the prompt used that this row now stands in for. These keys\n * are present only when they carry something.\n */\nfunction matchedEntityRow(entity: Dict, entityConfidences: Record<string, string>): Dict {\n  const name = String(entity.name ?? \"\");\n  const row: Dict = {\n    name,\n    type: entity.type ? String(entity.type) : \"topic\",\n    source_agents: Array.isArray(entity.source_agents) ? [...entity.source_agents] : [],\n  };\n  if (Object.prototype.hasOwnProperty.call(entityConfidences, name)) {\n    row.confidence = entityConfidences[name];\n  }\n  const aka = entity.also_known_as;\n  if (Array.isArray(aka) && aka.length > 0) row.also_known_as = aka.map((a) => String(a));\n  const formerly = entity.formerly;\n  if (Array.isArray(formerly) && formerly.length > 0) {\n    row.formerly = formerly.map((n) => String(n));\n  }\n  return row;\n}\n\n/**\n * The ONE hydration door for both server surfaces (`_hydrate_local`).\n *\n * `prepare_recognition_context` used to hydrate through the runtime's L1-only\n * thunk while `get_deeper_context` assembled from the merged manifest plus L1.\n * The two disagreed on the same prompt: one returned nine thousand characters,\n * the other \"no match\". Both now go through `assembleLocalContext`, which reads\n * L1 when a document exists and the per-agent summaries (newest first,\n * age-marked) when it does not, under one character budget. Fail-open: any\n * failure is an empty string.\n */\nfunction hydrateLocal(prompt: string, manifest: Dict, accessLevel: string): string {\n  try {\n    return assembleLocalContext(prompt, manifest, {\n      accessLevel,\n      l1Dir: resolveL1Dir(),\n    }).text;\n  } catch {\n    // hydration degrades, never crashes a turn\n    return \"\";\n  }\n}\n\n/**\n * Immediate recognition + a bounded prompt-context fragment from the store. The\n * recognition string is computed synchronously; `recognition_latency_us` is the\n * measured micro-latency (rounded to 1 dp, like Python). `hydration_scheduled`\n * mirrors Python's `hydration is not None` (true iff there were matches).\n */\nexport async function prepareRecognitionContextFromStore(\n  store: L6Store,\n  prompt: string,\n  accessLevel = \"team\",\n  includePrivate = false,\n  hydrate = true,\n): Promise<Dict> {\n  const manifest = store.buildRecognitionManifest(includePrivate, accessLevel);\n  const l1Dir = resolveL1Dir();\n  const t0 = process.hrtime.bigint();\n  const result = recognitionFirst(prompt, manifest, { accessLevel, l1Dir });\n  const latencyUs = Number(process.hrtime.bigint() - t0) / 1000;\n  // Mirrors the oracle: bool(hydrate and iscoroutine(hydration)) -- with\n  // hydrate=false nothing is scheduled, whatever matched.\n  const hydrationScheduled = hydrate && result.matchedEntities.length > 0;\n\n  // Recognition stays instant (measured above); hydration is the SECOND phase\n  // and runs inside its own budget, mirroring the async adapter's\n  // DEFAULT_HYDRATION_TIMEOUT + 0.5 grace. Degrades to '' — never throws.\n  // The runtime's own L1-only thunk is deliberately left UNCALLED (Python\n  // closes the un-started coroutine): the server hydrates through the same\n  // local door `get_deeper_context` uses.\n  let detail = \"\";\n  if (hydrationScheduled) {\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const budget = new Promise<string>((resolveEmpty) => {\n      timer = setTimeout(() => resolveEmpty(\"\"), (DEFAULT_HYDRATION_TIMEOUT + 0.5) * 1000);\n    });\n    detail = await Promise.race([\n      Promise.resolve().then(() => hydrateLocal(prompt, manifest, accessLevel)),\n      budget,\n    ]).finally(() => clearTimeout(timer));\n  }\n\n  return {\n    prompt,\n    access_level: accessLevel,\n    include_private: includePrivate,\n    recognition: result.recognition,\n    confidence: result.confidence,\n    matched_entities: result.matchedEntities.map((entity) =>\n      matchedEntityRow(entity, result.entityConfidences),\n    ),\n    recognition_latency_us: Math.round(latencyUs * 10) / 10,\n    hydration_scheduled: hydrationScheduled,\n    hydration_chars: detail.length,\n    hydration: detail,\n    prompt_context: recognitionPromptContext(result),\n  };\n}\n\n/**\n * Deeper context for `prompt`, assembled locally and free — faithful port of\n * `get_deeper_context_for_prompt`. The local store is the source; an enabled\n * L2 backend still contributes when a deployment has one, appended rather\n * than depended on — retrieval that ships disabled must not be the only door.\n */\nexport async function getDeeperContextForPrompt(\n  store: L6Store,\n  prompt: string,\n  accessLevel = \"team\",\n  includePrivate = false,\n): Promise<Dict> {\n  let local;\n  try {\n    const manifest = store.buildRecognitionManifest(includePrivate, accessLevel);\n    local = assembleLocalContext(prompt, manifest, {\n      accessLevel,\n      l1Dir: resolveL1Dir(),\n    });\n  } catch {\n    // deeper context must not crash a turn\n    local = {\n      text: \"\",\n      entities: [],\n      doors: [],\n      l1Documents: 0,\n      truncated: false,\n      reason: \"local hydration failed\",\n    };\n  }\n\n  const payload = buildLocalPayload(prompt, local, accessLevel, includePrivate);\n\n  let l2Context = \"\";\n  try {\n    l2Context = await queryL2(prompt);\n  } catch {\n    // an optional door, never a hard one\n  }\n  if (l2Context) {\n    const joined = [payload.context, l2Context].filter(Boolean).join(\"\\n\\n\");\n    payload.context = joined;\n    payload.context_chars = joined.length;\n    payload.source = \"local-store+l2\";\n  }\n\n  return payload;\n}\n\n/**\n * The deferred stub the `mcp_snapshots` conformance fixture pins for\n * `compile_codex_turn`. Kept for back-compat: the generator special-cases this\n * tool's snapshot because its live output is environment-bound (resolves the live\n * cwd, git repo name + remote, repo-identity scoring), so it is NOT a portable\n * cross-impl parity surface. The real tool now returns a full brief at runtime\n * (matching the live Python server), so the snapshot test asserts structurally\n * rather than byte-equal to this stub.\n */\nexport const CODEX_TURN_DEFERRED = {\n  _status: \"deferred\",\n  schema_version: \"codex-turn-brief/v1\",\n  reason:\n    \"compile_codex_turn output is environment-bound (resolves the live cwd, git \" +\n    \"repo name + remote, and repo-identity scoring) and is not a portable \" +\n    \"cross-impl parity fixture. The req pins the tool surface + arg defaults; the \" +\n    \"res snapshot is this deferred stub.\",\n} as const;\n\n/**\n * Return a Codex turn-scoped recognition brief using this server's store —\n * delegates to the P7 `@getbourdon/inference` turn compiler (faithful port of\n * `compile_codex_turn_from_store` in `core/l6_server.py`). The live Python server\n * returns the same full brief; only the conformance SNAPSHOT is the deferred stub.\n */\nexport function compileCodexTurnFromStore(\n  store: L6Store,\n  prompt: string,\n  opts: { cwd?: string | null; accessLevel?: string; maxItems?: number; maxChars?: number } = {},\n): Dict {\n  const brief = compileCodexTurn(prompt, {\n    cwd: opts.cwd ?? null,\n    libraryPath: store.libraryPath,\n    accessLevel: opts.accessLevel ?? \"team\",\n    maxItems: opts.maxItems,\n    maxChars: opts.maxChars,\n    delivery: \"all\",\n  });\n  return turnBriefToDict(brief);\n}\n","// SPDX-License-Identifier: BUSL-1.1\n/**\n * stdio transport — the MCP-host default and `bourdon serve --transport stdio`.\n *\n * `StdioServerTransport` carries no auth: stdio has no HTTP request, so the\n * caller resolves to OPERATOR (trusted) via the unbound AsyncLocalStorage —\n * exactly v0.8.0 behavior. `server.connect(transport)` blocks the process until\n * the connecting MCP client disconnects.\n */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\n/** Connect `server` to a stdio transport. Resolves once connected; the process\n * stays alive until the client disconnects. */\nexport async function runStdio(server: McpServer): Promise<void> {\n  const transport = new StdioServerTransport();\n  await server.connect(transport);\n}\n"],"mappings":";;;;AAWA,IAAAA,qBAAkE;;;ACelE,yBAAgC;AAChC,uBAIO;AAEP,wBAOO;AAEP,4BAA8C;AAEvC,IAAM,eAAe;AACrB,IAAM,eAAe;AAC5B,IAAM,yBAAyB,IAAI,OAAO;AAC1C,IAAM,cAAc,IAAI,gCAAc,eAAe,8BAAY;AAO1D,SAAS,wBAAuC;AACrD,QAAM,QAAQ,QAAQ,IAAI;AAC1B,MAAI,UAAU,UAAa,MAAM,KAAK,MAAM,GAAI,QAAO;AACvD,SAAO,SAAS;AAClB;AAIA,SAAS,wBAAwB,GAAW,GAAoB;AAC9D,QAAM,KAAK,OAAO,KAAK,GAAG,MAAM;AAChC,QAAM,KAAK,OAAO,KAAK,GAAG,MAAM;AAChC,MAAI,GAAG,WAAW,GAAG,OAAQ,QAAO;AACpC,aAAO,oCAAgB,IAAI,EAAE;AAC/B;AAGO,SAAS,eAAe,MAAuB;AACpD,MAAI,SAAS,YAAa,QAAO;AAEjC,MAAI,mCAAmC,KAAK,IAAI,EAAG,QAAO;AAE1D,QAAM,WAAW,KAAK,Q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AAC;AAChB,CAAC;","names":["import_federation","createHttpServer","import_federation","import_streamableHttp","yamlParse","import_federation","import_inference","import_l5","import_participants","import_node_fs","import_node_path","import_node_fs","import_node_os","import_node_path","import_federation","import_yaml","yamlParse","import_federation","import_l5","import_participants","import_node_fs","import_node_path","import_federation","import_redaction","import_node_path","import_federation","import_redaction","isOsError","pathResolve","name","pathJoin","gate","options","ref"]}